Press "Enter" to skip to content

JavaScript advanced question list

1. What is the output?

function sayHi() {
  console.log(name)
  console.log(age)
  var name = 'Lydia'
  let age = 21
}

sayHi()
  • A: Lydiaandundefined
  • B: LydiaandReferenceError
  • C: ReferenceErrorand21
  • D: undefinedandReferenceError

Answer: D

Inside the function, we first varkeyword to declare a namevariable. This means that the variables are promoted (the memory space is set at the creation stage) until the default value is reached before the program runs to the location of the defined variable undefined. Because when we print namevariable If we can not perform to the position defined variables, so the value of the variable remains undefined.

By letand constvariable declaration keywords will increase, however, and vardifferent, they will not be initialized. They cannot be accessed until we declare (initialize). This behavior is called a temporary dead zone. When we tried to access them before the statement, JavaScript will throw an ReferenceErrorerror.


2. What is the output?

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1)
}

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1)
}
  • A: 0 1 2and0 1 2
  • B: 0 1 2and3 3 3
  • C: 3 3 3and0 1 2

Answer: C

Since the event loop of JavaScript, setTimeoutthe callback will after the end of the traverse before execution. Because the traversal first traversal iby varkeyword statement, so this value is under the global scope. During traversal, we unary operators by symbols ++to each increment ivalue. When setTimeoutthe time the callback is executed, ithe value is equal to 3.

In a second traversal, traversed iby letkeyword declared: by letand constvariables are declared keyword has block-level scope (refer to anything in the {}). In each traversal, ithere is a new value, and each value is in the scope of the loop.


3. What is the output?

const shape = {
  radius: 10,
  diameter() {
    return this.radius * 2
  },
  perimeter: () => 2 * Math.PI * this.radius
}

shape.diameter()
shape.perimeter()
  • A: 20and62.83185307179586
  • B: 20andNaN
  • C: 20and63
  • D: NaNand63

Answer: B

Note that diameterthe value is a routine function, but perimeterthe value is a function of the arrows.

For the arrow function, the thiskeyword points to its current surrounding scope (simply a regular function that contains an arrow function, or a global object if there is no regular function), which is different from a regular function. This means that when we call perimeterupon, thisinstead of pointing to shapeobjects, but its scope around (in the example window).

In windowno in radiusthis property, and therefore returns undefined.


4. What is the output?

+true;
!"Lydia";
  • A: 1andfalse
  • B: falseandNaN
  • C: falseandfalse

Answer: A

The unary operator plus sign attempts to convert bool to number. trueIs converted to a number, then 1falseit is 0.

String 'Lydia'is a true value, the true value is inverted it returns false.


5. Which one is invalid?

const bird = {
  size: 'small'
}

const mouse = {
  name: 'Mickey',
  small: true
}
  • A: mouse.bird.size
  • B: mouse[bird.size]
  • C: mouse[bird["size"]]
  • D: All valid

Answer: A

In JavaScript, the keys of all objects are strings (unless the object is a Symbol). Although we may not define them as strings, they are always converted to strings at the bottom.

When we use the parenthesis syntax ([]), JavaScript interprets (or unboxes) the statement. It first began to see the first brackets [and move on until you find the closing parenthesis ]. Only then will it calculate the value of the statement.

mouse[bird.size]: First calculate bird.size, this will get smallmouse["small"]Return true.

Then using the dot syntax, none of the above will happen. mouseNot birdthe key, which means mouse.birdShi undefined. Then when we use dot syntax mouse.bird.sizewhen, because mouse.birdShi undefined, which also it became undefined.size. This behavior is invalid and will throw an error similar Cannot read property "size" of undefined.


6. What is the output?

let c = { greeting: 'Hey!' }
let d

d = c
c.greeting = 'Hello'
console.log(d.greeting)
  • A: Hello
  • B: undefined
  • C: ReferenceError
  • D: TypeError

Answer: A

In JavaScript, when two objects are set equal to each other, they interact by reference .

First, the variable cvalue is an object. Next, we have to dassign one and cthe same reference object.

Clipboard.png

So when we change one of the objects, it actually changes all the objects.


7. What is the output?

let a = 3
let b = new Number(3)
let c = 3

console.log(a == b)
console.log(a === b)
console.log(b === c)
  • A: true false true
  • B: false false true
  • C: true false false
  • D: false true true

Answer: C

new Number()Is a built-in function constructor. Although it looks like a number, it’s actually not a real number: it has a bunch of extra features and it’s an object.

When we use ==the time operator, it only checks whether the two have the same value . Because their values ​​are all 3, they return true.

Then, when we use the ===operators are used, both the value and type should be the same. new Number()Is an object instead of a number, so it returns false.


8. What is the output?

class Chameleon {
  static colorChange(newColor) {
    this.newColor = newColor
    return this.newColor
  }

  constructor({ newColor = 'green' } = {}) {
    this.newColor = newColor
  }
}

const freddie = new Chameleon({ newColor: 'purple' })
freddie.colorChange('orange')
  • A: orange
  • B: purple
  • C: green
  • D: TypeError

Answer: D

colorChangeIs a static method. Static methods are designed to be used only by the constructor that created them (that is, Chameleon) and cannot be passed to the instance. As freddiean example, and it can not be instantiated using the static method, so throw the TypeErrorerror.


9. What is the output?

let greeting
greetign = {} // Typo!
console.log(greetign)
  • A: {}
  • B: ReferenceError: greetign is not defined
  • C: undefined

Answer: A

The code prints out an object because we created an empty object on the global object! When we greetingwrong to greetignwhen, JS interpreter actually on the browser it as global.greetign = {}(or window.greetign = {}).

In order to avoid this problem, we can use it "use strict". This ensures that you must assign a value when you declare a variable.


10. What happens when we do this?

function bark() {
  console.log('Woof!')
}

bark.animal = 'dog'
  • A: Normal operation!
  • B: SyntaxError. You can’t add properties to a function this way.
  • C: undefined
  • D: ReferenceError

Answer: A

This is ok in JavaScript because functions are objects! (except for basic types are objects)

A function is a special object. The code you wrote is not actually an actual function. A function is an object that has an attribute, and the attribute can also be called.


11. What is the output?

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

const member = new Person("Lydia", "Hallie");
Person.getFullName = function () {
  return `${this.firstName} ${this.lastName}`;
}

console.log(member.getFullName());
  • A: TypeError
  • B: SyntaxError
  • C: Lydia Hallie
  • D: undefined undefined

Answer: A

You can’t add properties to a constructor like regular objects. If you want to add features to all instances at once, you should use prototypes. So in this case, use the following:

Person.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`;
}

This will member.getFullName()work. Why is it so useful? Suppose we add this method to the constructor itself. Maybe not every Personinstance needs this method. This will waste a lot of memory space because they still have this property, which will take up memory space for each instance. Conversely, if we only add it to the prototype, it only exists in one place in memory, but all instances can access it!


12. What is the output?

function Person(firstName, lastName) {
  this.firstName = firstName
  this.lastName = lastName
}

const lydia = new Person('Lydia', 'Hallie')
const sarah = Person('Sarah', 'Smith')

console.log(lydia)
console.log(sarah)
  • A: Person {firstName: "Lydia", lastName: "Hallie"}andundefined
  • B: Person {firstName: "Lydia", lastName: "Hallie"}andPerson {firstName: "Sarah", lastName: "Smith"}
  • C: Person {firstName: "Lydia", lastName: "Hallie"}and{}
  • D: Person {firstName: "Lydia", lastName: "Hallie"}andReferenceError

Answer: A

For sarahwe do not use newkeywords. When using new, the thisreference to a null object we created. When not in use new, the thisreference is a global object (global object).

We say this.firstNameequal "Sarah", and this.lastNameequal "Smith". In fact, we do is define global.firstName = 'Sarah'and global.lastName = 'Smith'. And sarahitself undefined.


13. What are the three stages of event communication?

  • A: Target > Capturing > Bubbling
  • B: Bubbling > Target > Capturing
  • C: Target > Bubbling > Capturing
  • D: Capturing > Target > Bubbling

Answer: D

In Capture (capturing) stage, the event spread downward from the ancestor to the target element. Bubblingbegins when the event reaches the target element .

Clipboard.png


14. All objects have prototypes.

  • A: true
  • B: false

Answer: B

In addition to the basic object (base object), all objects have a prototype. Basic objects can access some methods and properties, such as .toString. That’s why you can use the built-in JavaScript method! All of these methods are available on the prototype. Although JavaScript can’t find these methods directly on the object, JavaScript finds them along the prototype chain for you to use.


15. What is the output?

function sum(a, b) {
  return a + b
}

sum(1, '2')
  • A: NaN
  • B: TypeError
  • C: "12"
  • D: 3

Answer: C

JavaScript is a dynamically typed language : we don’t specify the type of some variables. Value can be automatically converted into a different type in a case where you do not know, this type is called implicit type conversion (implicit type coercion). Coercion refers to converting one type to another.

In the present embodiment, JavaScript digital 1converted to a string, so that the function and returns a meaningful value. When a number type ( 1) and a string type ( '2') are added, the number is treated as a string. We can connect to the string, for example "Hello" + "World", what happens here is "1" + "2"that it returns "12".


16. What is the output?

let number = 0
console.log(number++)
console.log(++number)
console.log(number)
  • A: 1 1 2
  • B: 1 2 2
  • C: 0 2 2
  • D: 0 1 2

Answer: C

After one dollar increment operator ++:

  1. Return value (return 0)
  2. Value increment (number is now 1)

One-time pre-increment operator ++:

  1. Value increment (number is now 2)
  2. Return value (return 2)

The result is 0 2 2.


17. What is the output?

function getPersonInfo(one, two, three) {
  console.log(one)
  console.log(two)
  console.log(three)
}

const person = 'Lydia'
const age = 21

getPersonInfo`${person} is ${age} years old`
  • A: "Lydia" 21 ["", " is ", " years old"]
  • B: ["", " is ", " years old"] "Lydia" 21
  • C: "Lydia" ["", " is ", " years old"] 21

Answer: B

If you use a tag template literal, the value of the first argument always contains an array of strings. The rest of the parameters get the value of the passed expression!


18. What is the output?

function checkAge(data) {
  if (data === { age: 18 }) {
    console.log('You are an adult!')
  } else if (data == { age: 18 }) {
    console.log('You are still an adult.')
  } else {
    console.log(`Hmm.. You don't have an age I guess`)
  }
}

checkAge({ age: 18 })
  • A: You are an adult!
  • B: You are still an adult.
  • C: Hmm.. You don't have an age I guess

Answer: C

When testing for equality, primitive types are compared by their values, and objects are compared by their references. JavaScript checks if the object has a reference to the same location in memory.

The two objects we are comparing in the title are not the same reference: the memory location of the object reference passed as a parameter is different from the memory location referenced by the object used to determine equality.

It is also { age: 18 } === { age: 18 }and { age: 18 } == { age: 18 }return falsereason.


19. What is the output?

function getAge(...args) {
  console.log(typeof args)
}

getAge(21)
  • A: "number"
  • B: "array"
  • C: "object"
  • D: "NaN"

Answer: C

The extended operator ( ...args) returns an array of arguments. The array is an object, therefore typeof argsreturn "object".


20. What is the output?

function getAge() {
  'use strict'
  age = 21
  console.log(age)
}

getAge()
  • A: 21
  • B: undefined
  • C: ReferenceError
  • D: TypeError

Answer: C

With "use strict"that, you can be sure that you don’t accidentally declare global variables. We never declare a variable age, because we use it "use strict", it will throw a reference error. If we do not use "use strict", it will work, because the property agewill be added to the global object.


21. What is the output?

const sum = eval('10*10+5')
  • A: 105
  • B: "105"
  • C: TypeError
  • D: "10*10+5"

Answer: A

The code is passed in as a string and evalevaluated. If it’s an expression, as in this example, it evaluates the expression. The expression is 10 * 10 + 5. This will return the number 105.


22. How long does cool_secret have access?

sessionStorage.setItem('cool_secret'123)
  • A: Forever, the data will not be lost.
  • B: When the user closes the tab page.
  • C: When the user turns off the entire browser, not just the tabs.
  • D: When the user turns off the computer.

Answer: B

Close tab tab , the sessionStoragestored data will be deleted.

If used localStorage, the data will always be there unless it is called localStorage.clear().


23. What is the output?

var num = 8
var num = 10

console.log(num)
  • A: 8
  • B: 10
  • C: SyntaxError
  • D: ReferenceError

Answer: B

Use varkeywords, you can use the same name declare multiple variables. The variable will then save the latest value.

You can not use let, or constto do this, because they block scope.


24. What is the output?

const obj = { 1: 'a', 2: 'b', 3: 'c' }
const set = new Set([1, 2, 3, 4, 5])

obj.hasOwnProperty('1')
obj.hasOwnProperty(1)
set.has('1')
set.has(1)
  • A: false true false true
  • B: false true true true
  • C: true true false true
  • D: true true true true

Answer: C

All object keys (not including Symbol) are strings at the bottom, even if you don’t enter them as strings. This is why the obj.hasOwnProperty('1')returns true.

For collections, it doesn’t work like this. There is no in our collection '1'set.has('1')return false. It has a numeric type of 1, and set.has(1)returns true.


25. What is the output?

const obj = { a: 'one', b: 'two', a: 'three' }
console.log(obj)
  • A: { a: "one", b: "two" }
  • B: { b: "two", a: "three" }
  • C: { a: "three", b: "two" }
  • D: SyntaxError

Answer: C

If you have two keys with the same name, the keys will be replaced. It is still in the position where the first key appears, but the value is the value of the last key that appeared.


26. The JavaScript global execution context does two things for you: the global object and the this keyword.

  • A: true
  • B: false
  • C: it depends

Answer: A

The basic execution context is the global execution context: it is accessible anywhere in the code.


27. What is the output?

for (let i = 1; i < 5; i++) {
  if (i === 3) continue
  console.log(i)
}
  • A: 1 2
  • B: 1 2 3
  • C: 1 2 4
  • D: 1 3 4

Answer: C

If a condition is returned true, the continuestatement skip this iteration.


28. What is the output?

String.prototype.giveLydiaPizza = () => {
  return 'Just give Lydia pizza already!'
}

const name = 'Lydia'

name.giveLydiaPizza()
  • A: "Just give Lydia pizza already!"
  • B: TypeError: not a function
  • C: SyntaxError
  • D: undefined

Answer: A

StringIs a built-in constructor, we can add properties to it. I just added a method to its prototype. The base type string is automatically converted to a string object, which is generated by the string prototype function. Therefore, all strings (string objects) can access this method!


29. What is the output?

const a = {}
const b = { key: 'b' }
const c = { key: 'c' }

a[b] = 123
a[c] = 456

console.log(a[b])
  • A: 123
  • B: 456
  • C: undefined
  • D: ReferenceError

Answer: B

The object’s keys are automatically converted to strings. We tried to object bto the object aof the key, and the corresponding value 123.

However, when an object is stringed, it becomes "[object Object]". So what is said here is, a["[object Object]"] = 123. Then, we did the same thing again, it cis another object, there is also implicit stringification, so, a["[object Object]"] = 456.

Then we print a[b], that is a["[object Object]"]. It was just set to before 456, so the return is 456.


30. What is the output?

const foo = () => console.log('First')
const bar = () => setTimeout(() => console.log('Second'))
const baz = () => console.log('Third')

bar()
foo()
baz()
  • A: First Second Third
  • B: First Third Second
  • C: Second First Third
  • D: Second Third First

Answer: B

We have a setTimeoutfunction, and call it first. However, it is the last to print the log.

This is because in the browser, we not only have a run-time engine, there is a known WebAPIthing. WebAPIProvides a setTimeoutfunction, also contain other, such as DOM.

After pushing the callback to the WebAPI, the setTimeoutfunction itself (but not the callback!) will pop up from the stack.

Clipboard.png

Now, it foois called and printed "First".

fooPopped from the stack, bazcalled. Print "Third".

WebAPI cannot add content to the stack at any time. Instead, it pushes the callback function to a place called queue .

Clipboard.png

This is where the event loop begins to work. An event loop looks at the stack and the task queue. If the stack is empty, it accepts the first element on the queue and pushes it onto the stack.

Clipboard.png

barCalled, printed "Second", and then it is popped off the stack.


31. What is event.target when the button is clicked?

<div onclick="console.log('first div')">
  <div onclick="console.log('second div')">
    <button onclick="console.log('button')">
      Click!
    </button>
  </div>
</div>
  • A: Outer div
  • B: Inner div
  • C: button
  • D: An array containing all the nested elements.

Answer: C

The deepest nested element that causes the event is the target of the event. You can event.stopPropagationstop bubbling.


32. What is the log output when you click on the paragraph?

<div onclick="console.log('div')">
  <p onclick="console.log('p')">
    Click here!
  
</div>
  • A: p div
  • B: div p
  • C: p
  • D: div

Answer: A

If we click p, we will see two logs: pand div. During the event propagation, there are three phases: capture, target, and bubbling. By default, event handler execution (unless bubbling stage useCaptureset true). It propagates outward from the deepest elements of the nest.


33. What is the output?

const person = { name: 'Lydia' }

function sayHi(age) {
  console.log(`${this.name} is ${age}`)
}

sayHi.call(person, 21)
sayHi.bind(person, 21)
  • A: undefined is 21 Lydia is 21
  • B: function function
  • C: Lydia is 21 Lydia is 21
  • D: Lydia is 21 function

Answer: D

Using these two methods, we hope we can pass thiskeywords referenced object. However, it .callis implemented immediately .

.bindReturns a copy of the function , but with a binding context! It is not executed immediately.


34. What is the output?

function sayHi() {
  return (() => 0)()
}

typeof sayHi()
  • A: "object"
  • B: "number"
  • C: "function"
  • D: "undefined"

Answer: B

sayHiThe method returns the return value of the immediate execution function (IIFE). The return value of this immediate execution function is 0, the type isnumber

Reference: There are only 7 built-in types: nullundefinedbooleannumberstringobjectand symbolfunctionNot a type, a function is an object, and its type is object.


35. Which of the following values ​​are falsy?

0
new Number(0)
('')
(' ')
new Boolean(false)
undefined
  • A: 0'',undefined
  • B: 0new Number(0)''new Boolean(false),undefined
  • C: 0''new Boolean(false),undefined
  • D: All are of them are falsy

Answer: A

There are only 6 falsy values:

  • undefined
  • null
  • NaN
  • 0
  • '' (empty string)
  • false

FunctionConstructors, such as new Numberand new Boolean, are truthy .


36. What is the output?

console.log(typeof typeof 1)
  • A: "number"
  • B: "string"
  • C: "object"
  • D: "undefined"

Answer: B

typeof 1Return "number"
typeof "number"Return "string".


37. What is the output?

const numbers = [1, 2, 3]
numbers[10] = 11
console.log(numbers)
  • A: [1, 2, 3, 7 x null, 11]
  • B: [1, 2, 3, 11]
  • C: [1, 2, 3, 7 x empty, 11]
  • D: SyntaxError

Answer: C

When you set a value for an array that exceeds the length of the array, JavaScript creates something called “empty slots”. Their values ​​are actually undefined. You will see the following scenario:

[1, 2, 3, 7 x empty, 11]

It depends on your operating environment (per browser, and node environment, it may be different)


38. What is the output?

(() => {
  let x, y
  try {
    throw new Error()
  } catch (x) {
    (x = 1), (y = 2)
    console.log(x)
  }
  console.log(x)
  console.log(y)
})()
  • A: 1 undefined 2
  • B: undefined undefined undefined
  • C: 1 1 2
  • D: 1 undefined undefined

Answer: A

catchThe code block receives the parameters x. When we pass an argument, which is variable previously defined xdifferently. This xis part of catchblock-level scope.

We will then variable block-level scope of the assignment is 1also set variable yvalues. Now we print the variable in the block-level scope x, with a value of 1.

catchVariables outside the block xvalue remains undefinedyvalue 2. When we catchperform outside the block console.log(x), the return undefinedyreturn 2.


39. Everything in JavaScript?

  • A: Basic types and objects
  • B: Functions and objects
  • C: only objects
  • D: numbers and objects

Answer: A

JavaScript has only basic types and objects.

The basic types include booleannullundefinedbigintnumberstringsymbol.


40. What is the output?

[[0, 1], [2, 3]].reduce(
  (acc, cur) => {
    return acc.concat(cur)
  },
  [1, 2]
)
  • A: [0, 1, 2, 3, 1, 2]
  • B: [6, 1, 2]
  • C: [1, 2, 0, 1, 2, 3]
  • D: [1, 2, 6]

Answer: C

[1, 2]Is the initial value. The initial value as the first argument will be the first call accvalue. At the first execution, accthe value is [1, 2]curthe value is [0, 1]. Combine them and the result is [1, 2, 0, 1]
The second time, accthe value of [1, 2, 0, 1], is , curthe value is [2, 3]. Merge them, the end result is[1, 2, 0, 1, 2, 3]


41. What is the output?

!!null
!!''
!!1
  • A: false true false
  • B: false false true
  • C: false true true
  • D: true true false

Answer: B

nullIt is falsy . !nullThe value is true!trueThe value is false.

""It is falsy . !""The value is true!trueThe value is false.

1It is truthy . !1The value is false!falseThe value is true.


42. setIntervalWhat is the return value of the method?

setInterval(() => console.log('Hi'), 1000)
  • A: A unique id
  • B: the number of milliseconds specified by this method
  • C: passed function
  • D: undefined

Answer: A

setIntervalReturns a unique id. This id can be used for clearIntervala function to cancel the timer.


43. What is the output?

[...'Lydia']
  • A: ["L", "y", "d", "i", "a"]
  • B: ["Lydia"]
  • C: [[], "Lydia"]
  • D: [["L", "y", "d", "i", "a"]]

Answer: A

The string type is iterable. The extended operator maps each character of the iteration into an element.


44. What is the output?

function* generator(i) {
  yield i;
  yield i * 2;
}

const gen = generator(10);

console.log(gen.next().value);
console.log(gen.next().value);
  • A: [0, 10], [10, 20]
  • B: 20, 20
  • C: 10, 20
  • D: 0, 10 和 10, 20

Answer: C

The general function cannot be stopped halfway after execution. However, the generator function can “stop” midway, and then continue from where it left off. When the generator encounters a yieldkeyword, it will generate the yieldfollowing value. Note that, the generator is not in this case returned (_return_) value, but generates (_yield_) value.

First, we use the 10parameters as a parameter ito initialize the generator function. Then use the next()method to execute the generator step by step. The first time the generator is executed, ithe value is the 10first yieldkeyword that it will generate i. At this point, the generator “pauses” and is generated 10.

Then we execute the next()method again . The generator will continue from where it was just paused, this time istill 10. So we went to the second yieldkey at this time need to generate value i*2iis 10, then the time value is generated 20. So the end result of this question is 10,20.

45. What is the return value?

const firstPromise = new Promise((res, rej) => {
  setTimeout(res, 500, "one");
});

const secondPromise = new Promise((res, rej) => {
  setTimeout(res, 100, "two");
});

Promise.race([firstPromise, secondPromise]).then(res => console.log(res));
  • A: "one"
  • B: "two"
  • C: "two" "one"
  • D: "one" "two"

Answer: B

When we have to Promise.racepass more than one method Promise, the will be a priority resolution. In this example, we used setTimeoutto firstPromiseand secondPromiseare set 500ms and 100ms timer. This means that secondPromisethe string will be parsed first two. Then the resparameter is now two, it is the output result.


46. ​​What is the output?

let person = { name: "Lydia" };
const members = [person];
person = null;

console.log(members);
  • A: null
  • B: [null]
  • C: [{}]
  • D: [{ name: "Lydia" }]

Answer: D

First we declare an nameobject that has an attribute person.

Clipboard.png

Then we declare a variable again members. Assign the first element to the variable person. When two objects set equal to each other, they will by reference interaction. But when you assign a reference from a variable to another variable, in fact, just execute a copy operation. (Note that their references are not the same _!)

Clipboard.png

Next we let personequal null.

Clipboard.png

We didn’t modify the value of the first element of the array, but just modified the value personof the variable , because the reference to the element (which is copied) is persondifferent. membersThe first element still retains a reference to the original object. When we output the membersarray, the first element prints the referenced object.


47. What is the output?

const person = {
  name: "Lydia",
  age: 21
};

for (const item in person) {
  console.log(item);
}
  • A: { name: "Lydia" }, { age: 21 }
  • B: "name", "age"
  • C: "Lydia", 21
  • D: ["name", "Lydia"], ["age", 21]

Answer: B

In the for-inloop, we can iterate through the key of the object, which is the namesum here age. At the bottom, the object’s keys are all strings (if they are not Symbols). In each cycle, we will be itemset to the current traverse to the key. So the beginning, itemShi name, after itemthe output is age.


48. What is the output?

console.log(3 + 4 + "5");
  • A: "345"
  • B: "75"
  • C: 12
  • D: "12"

Answer: B

When all operator precedence are the same, the calculation expression is determined in conjunction operator sequence, i.e., from left to right or right to left. In this example, we only have one type of operator +. For addition, the order of joins is dead from left to right.

3 + 4First calculate and get the numbers 7.

As a result of the type cast, 7 + '5'the "75"JavaScript will be 7converted to a string, see question 15. We can +connect the two strings with a number. "7" + "5"I got it "75".


numWhat is the value of 49 .

const num = parseInt("7*6"10);
  • A: 42
  • B: "42"
  • C: 7
  • D: NaN

Answer: C

Only return to the first letter of the string set hex after (that is, the second argument, the specified number needs to be resolved is what decimal: decimal, hexadecimal mechanism, octal, binary, etc. ……), parseIntChecks if the characters in the string are legal. Once you encounter a character that is not legal in the specified hex, it immediately stops parsing and ignores all subsequent characters.

*It is an illegal numeric character. So only parse it "7"and parse it into decimal 7numThe value is 7.


50. What is the output?

[1, 2, 3].map(num => {
  if (typeof num === "number") return;
  return num * 2;
});
  • A: []
  • B: [null, null, null]
  • C: [undefined, undefined, undefined]
  • D: [ 3 x empty ]

Answer: C

When mapping an array, it numis the element that is currently looped. In this example, all the mappings are of type number, so the typeof num === "number"result of the determination in if is that the true.map function creates a new array and inserts the return value of the function into the array. .

However, no value is returned. When the function does not return any value, it returns by default undefined. For each element in the array, the function block gets the return value, so each element in the result is undefined.


51. What is the output?

function getInfo(member, year) {
  member.name = "Lydia";
  year = "1998";
}

const person = { name: "Sarah" };
const birthYear = "1997";

getInfo(person, birthYear);

console.log(person, birthYear);
  • A: { name: "Lydia" }, "1997"
  • B: { name: "Sarah" }, "1998"
  • C: { name: "Lydia" }, "1998"
  • D: { name: "Sarah" }, "1997"

Answer: A

Common parameters are values passed, and the object is different, a reference transmission. So, it’s birthYeara value passed because it’s a string and not an object. When we passed by value parameters, the value will create a copy . (can refer to question 46)

A variable birthYearhas a "1997"reference to a pair , and the passed argument has a "1997"reference to the pair , but the references to the two are not the same. When we pass to yearthe assignment "1998"to update the yeartime value of we just updated the year(reference). It birthYearis still at this time "1997".

And persona target. Parameters memberreferenced with the same object. When we modify memberthe time attributes of the referenced object, personthe corresponding attribute is also changed, because they refer to the same object. personThe nameproperty has become "Lydia".


52. What is the output?

function greeting() {
  throw "Hello world!";
}

function sayHi() {
  try {
    const data = greeting();
    console.log("It worked!", data);
  } catch (e) {
    console.log("Oh no an error!", e);
  }
}

sayHi();
  • A: "It worked! Hello world!"
  • B: "Oh no an error: undefined
  • C: SyntaxError: can only throw Error objects
  • D: "Oh no an error: Hello world!

Answer: D

Through the throwstatement, we can create a custom error. And through it, we can throw an exception. Exception may be a string , a digit , a Boolean type , or a target . In this case, our exception is a string 'Hello world'.

By catchthe statement, we can set when trya block of statements should deal with what to do after throwing an exception. The exception thrown in this example is a string 'Hello world'eThis is the string and is therefore output. The end result is 'Oh an error: Hello world'.


53. What is the output?

function Car() {
  this.make = "Lamborghini";
  return { make: "Maserati" };
}

const myCar = new Car();
console.log(myCar.make);
  • A: "Lamborghini"
  • B: "Maserati"
  • C: ReferenceError
  • D: TypeError

Answer: B

Attributes are returned when the value of the property is equal to the return value, rather than the value set in the constructor. We return to the string "Maserati", so myCar.makeequal "Maserati".


54. What is the output?

(() => {
  let x = (y = 10);
})();

console.log(typeof x);
console.log(typeof y);
  • A: "undefined", "number"
  • B: "number", "number"
  • C: "object", "number"
  • D: "number", "undefined"

Answer: A

let x = y = 10; Is an abbreviation for the following expression:

y = 10;
let x = y;

When we set the yequal value 10, we actually added a property yto the global object (in the browser, in windowNodejs global). In the browser, window.yequal to 10.

Then we declare a variable xequal to y, is 10but the variable is using. letStatement, it only acts on the block-level scope _ _ only it is declared valid block; in that case immediately call expression (IIFE). Use typeofwhen operator action value xis not defined: Because we are xdeclared outside the block, you can not call it. This means xundefined. Variable type is not assigned or is not declared "undefined"console.log(typeof x)Return "undefined".

And we created the global variable yand set it yequal to 10. This value is accessed throughout our code. yIt has been defined and has a "number"type of value. console.log(typeof y)Return "number".


55. What is the output?

class Dog {
  constructor(name) {
    this.name = name;
  }
}

Dog.prototype.bark = function() {
  console.log(`Woof I am ${this.name}`);
};

const pet = new Dog("Mara");

pet.bark();

delete Dog.prototype.bark;

pet.bark();
  • A: "Woof I am Mara",TypeError
  • B: "Woof I am Mara","Woof I am Mara"
  • C: "Woof I am Mara",undefined
  • D: TypeError,TypeError

Answer: A

We can use the deletekeyword to delete the properties of the object, which is also applicable to the prototype. Once the properties of the prototype have been removed, the property is not available on the prototype chain. In this case, the function is not available after barkexecution delete Dog.prototype.bark, but the code behind it is still calling it.

An TypeErrorexception is thrown when we try to call a function that doesn’t exist . In this case TypeError: pet.bark is not a function, because it pet.barkis undefined.


56. What is the output?

const set = new Set([1, 1, 2, 3, 4]);

console.log(set);
  • A: [1, 1, 2, 3, 4]
  • B: [1, 2, 3, 4]
  • C: {1, 1, 2, 3, 4}
  • D: {1, 2, 3, 4}

Answer: D

SetTarget phone unique value: that is the same value which appears only once.

We passed in the array [1, 1, 2, 3, 4]and it has a duplicate value 1. I think there can be no duplicate values in a collection, and one of them is removed. So the result is {1, 2, 3, 4}.


57. What is the output?

// counter.js
let counter = 10;
export default counter;
// index.js
import myCounter from "./counter";

myCounter += 1;

console.log(myCounter);
  • A: 10
  • B: 11
  • C: Error
  • D: NaN

Answer: C

Module is introduced read-only : you can not modify module introduced. Only the modules that export them can modify their values.

When we myCounteradd a value, we throw an exception: it myCounteris read-only and cannot be modified.


58. What is the output?

const name = "Lydia";
age = 21;

console.log(delete name);
console.log(delete age);
  • A: false,true
  • B: "Lydia",21
  • C: true,true
  • D: undefined,undefined

Answer: A

deleteOperator returns a Boolean value: truerefers to the deletion is successful, otherwise falseit through. varconstOr letkeyword to declare variables can not be used deleteto remove the operator.

nameThe variable is constdeclared by the keyword, so the delete is unsuccessful: return false. And when we set ageequal 21, we actually added a ageproperty named to the global object. The properties in the object can be deleted, as are the global objects, so delete agereturn true.


59. What is the output?

const numbers = [1, 2, 3, 4, 5];
const [y] = numbers;

console.log(y);
  • A: [[1, 2, 3, 4, 5]]
  • B: [1, 2, 3, 4, 5]
  • C: 1
  • D: [1]

Answer: C

We can parse the value of an array or property from an object by destructuring the assignment, say:

[a, b] = [12];

Clipboard.png

aThe value is now 1bthe value is now 2. And in the title, we are doing this:

[y] = [12345];

Clipboard.png

In other words, ythe first value equal to the array is the number 1. We output y, return 1.


60. What is the output?

const user = { name: "Lydia", age: 21 };
const admin = { admin: true, ...user };

console.log(admin);
  • A: { admin: true, user: { name: "Lydia", age: 21 } }
  • B: { admin: true, name: "Lydia", age: 21 }
  • C: { admin: true, user: ["Lydia", 21] }
  • D: { admin: true }

Answer: B

The extension operator ...provides the possibility to combine objects. You can copy the key-value pairs in the object and add them to another object. In this case, we copied the userobject key-value pairs and added them to the adminobject. adminThe object has these key-value pairs, so the result is { admin: true, name: "Lydia", age: 21 }.


61. What is the output?

const person = { name: "Lydia" };

Object.defineProperty(person, "age", { value: 21 });

console.log(person);
console.log(Object.keys(person));
  • A: { name: "Lydia", age: 21 },["name", "age"]
  • B: { name: "Lydia", age: 21 },["name"]
  • C: { name: "Lydia"},["name", "age"]
  • D: { name: "Lydia"},["age"]

Answer: B

By definePropertymethod, we can add a new property to the object, or modify an existing property. And we use the definePropertyfollowing method to add a property to the object, the default property is not enumerable (not enumerable) _. Object.keysThe method returns only objects _ enumerable (enumerable) properties, thus leaving only "name".

definePropertyThe properties added by the method are not mutable by default. You can writableconfigurableand enumerableproperty to change this behavior. In this case, the attributes definePropertyadded by the method have more control than the attributes added by themselves .


62. What is the output?

const settings = {
  username: "lydiahallie",
  level: 19,
  health: 90
};

const data = JSON.stringify(settings, ["level", "health"]);
console.log(data);
  • A: "{"level":19, "health":90}"
  • B: "{"username": "lydiahallie"}"
  • C: "["level", "health"]"
  • D: "{"username": "lydiahallie", "level":19, "health":90}"

Answer: A

JSON.stringifyThe second parameter is the replacer_. The replacer can be a function or array that controls how values ​​are converted to strings.

If the replacement (the replacer) is an array , then only contains the attributes in the array will be converted into a string. In the present embodiment, only the name "level"and "health"attributes are included, "username"were excluded. dataIt is equal to "{"level":19, "health":90}".

And if the replacer is a _function_, this function will be called once for each property of the object. 
The value returned by the function will become the value of this property, and will eventually be reflected in the converted JSON string. (Translator’s Note: Under Chrome, after experiment, if all properties return the same value, there will be an exception, the return value will be directly The JSON string is not output as a result, and if the return value is undefined, the property is excluded.


63. What is the output?

let num = 10;

const increaseNumber = () => num++;
const increasePassedNumber = number => number++;

const num1 = increaseNumber();
const num2 = increasePassedNumber(num1);

console.log(num1);
console.log(num2);
  • A: 10,10
  • B: 10,11
  • C: 11,11
  • D: 11,12

Answer: A

Unary operator ++ to go back to the operating value, then the accumulated operation value. num1Values are 10because the increaseNumberfirst function return numvalues, i.e. 10, subsequent further numaccumulation.

num2Is 10because we will num1pass increasePassedNumbernumberEquals 10num1value. Similarly, the ++ first return to the operating value, then the cumulative operation values.) numberIs 10, so num2also 10.

97 Comments

  1. nimabi nimabi November 27, 2023

    Thank you very much for sharing, I learned a lot from your article. Very cool. Thanks. nimabi

  2. nimabi nimabi November 29, 2023

    Thank you very much for sharing, I learned a lot from your article. Very cool. Thanks. nimabi

  3. sadasdee sadasdee December 8, 2023

    sadasdee

  4. Szpiegowskie Telefonu Szpiegowskie Telefonu January 30, 2024

    Obecnie technologia pozycjonowania jest szeroko stosowana. Wiele samochodów i telefonów komórkowych ma funkcje pozycjonowania, a także wiele aplikacji do pozycjonowania. Gdy zgubisz telefon, możesz użyć takich narzędzi do szybkiego zainicjowania żądań śledzenia lokalizacji. Zrozumieć, jak zlokalizować telefon, jak zlokalizować telefon po jego zgubieniu?

  5. Szpiegowskie Telefonu Szpiegowskie Telefonu February 11, 2024

    Dopóki istnieje sieć, zdalne nagrywanie w czasie rzeczywistym może odbywać się bez specjalnego instalowania sprzętu.

  6. oj6po3j53 oj6po3j53 February 19, 2024

    canadian online pharmacy cialis Walmart Pharmacy Prices
    us pharmacy cialis [url=http://canadianphrmacy23.com/]Pharmacy canadianphrmacy23.com[/url]

  7. byqxl31ne byqxl31ne February 25, 2024

    pharmacy rx one india pharmacy
    canadian pharmacy without a prescription [url=http://canadianphrmacy23.com/]canadian pharmacies online canadianphrmacy23.com[/url]

  8. Sign Up Sign Up March 12, 2024

    Thanks for sharing. I read many of your blog posts, cool, your blog is very good.

  9. Akagdw Akagdw March 26, 2024

    retrovir 300 mg uk – order zyloprim 100mg generic

Leave a Reply

Your email address will not be published. Required fields are marked *