List of JavaScript Advanced Problems

I post JavaScript multiple selection issues daily on my Instagram and also in this repository.

From basic to advanced, test how much you know about JavaScript, refresh your knowledge, or help with your coding interview! : Muscle: : Rocket: I update new issues under this repository every week.

The answer is in the fold below the question. Click to expand the question. Good luck ❀️


1. What is the output?
function sayHi() {
  console.log(name)
  console.log(age)
  var name = 'Lydia'
  let age = 21
}

sayHi()
Copy the code
  • A: Lydia ε’Œ undefined
  • B: Lydia ε’Œ ReferenceError
  • C: ReferenceError ε’Œ 21
  • D: undefined ε’Œ ReferenceError
The answer

Answer: D

Inside the function, we first declare the name variable through the var keyword. This means that the variable is raised (the memory space is set during creation) and the default value is undefined until the program runs to where the variable is defined. Because the name variable has not been executed to the point where it is defined when we print it, the value of the variable remains undefined.

Variables declared with the let and const keywords are also promoted, but unlike var, they are not initialized. They are not accessible until we declare (initialize) them. This behavior is called a temporary dead zone. JavaScript will throw a ReferenceError when we try to access them before declaring them.


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)}Copy the code
  • A: 0 1 2 ε’Œ 0 1 2
  • B: 0 1 2 ε’Œ 3 3 3
  • C: 3 3 3 ε’Œ 0 1 2
The answer

Answer: C

Due to JavaScript’s event loop, the setTimeout callback is executed after the loop is completed. Because the traversal I in the first traversal is declared by the var keyword, this value is globally scoped. During the traversal, we increment the value of I each time by the unary operator ++. When the setTimeout callback executes, the value of I is equal to 3.

In the second traversal, the traversal I is declared by the let keyword: variables declared by the let and const keywords have block-level scope (anything in {}). During each iteration, I has a new value, and each value is in scope within 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()
Copy the code
  • A: 20 and 62.83185307179586
  • B: 20 and NaN
  • C: 20 and 63
  • D: NaN and 63
The answer

Answer: B

Note that the value of diameter is a regular function, but perimeter’s value is an arrow function.

For arrow functions, the this keyword refers to its current scope (simply the normal function that contains the arrow function, or the global object if there are no normal functions), which behaves differently from the normal function. This means that when we call perimeter, this does not point to the Shape object, but rather to its surrounding scope (in our case, window).

Radius does not exist in the window, so return undefined.


4. What is the output?
+true;
!"Lydia";
Copy the code
  • A: 1 and false
  • B: false and NaN
  • C: false and false
The answer

Answer: A,

The unary plus operator attempts to convert bool to number. True converts to number to 1 and false to 0.

The string ‘Lydia’ is a truth value, which returns false if reversed.


5. Which one is invalid?
const bird = {
  size: 'small'
}

const mouse = {
  name: 'Mickey'.small: true
}
Copy the code
  • A: mouse.bird.size
  • B: mouse[bird.size]
  • C: mouse[bird["size"]]
  • D: All of them are valid
The answer

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 underneath.

JavaScript interprets (or unboxes) statements when we use the parenthesis syntax ([]). It sees the first opening parenthesis [and continues until it finds the closing parenthesis]. Only then will it evaluate the value of the statement.

Mouse [bird.size] : Evaluates bird.size first, which gives small. Mouse [“small”] returns true.

And then using dot syntax, none of this would happen. Mouse does not have the bird key, which means that mouse. Bird is undefined. Then when we use the dot syntax mouse.bird.size, since mouse.bird is undefined, this becomes undefined. This behavior is invalid and throws an error like 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)
Copy the code
  • A: Hello
  • B: undefined
  • C: ReferenceError
  • D: TypeError
The answer

Answer: A,

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

First, the value of variable C is an object. Next, we assign d a reference to the same object as c.

So when we change one of these objects, we change all of them.


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)
Copy the code
  • A: true false true
  • B: false false true
  • C: true false false
  • D: false true true
The answer

Answer: C

New Number() is a built-in function constructor. Although it looks like a number, it’s not really a number: it has a bunch of extra functions and it’s an object.

When we use the == operator, it simply checks to see if both have the same value. Since they both have a value of 3, they return true.

Then, when we use the === operator, both values and types should be the same. New Number() is an object, not a Number, so 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')
Copy the code
  • A: orange
  • B: purple
  • C: green
  • D: TypeError
The answer

Answer: D

ColorChange is 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 instances. Because Freddie is an instance, static methods cannot be used by the instance, so TypeError is thrown.


9. What is the output?
let greeting
greetign = {} // Typo!
console.log(greetign)
Copy the code
  • A: {}
  • B: ReferenceError: greetign is not defined
  • C: undefined
The answer

Answer: A,

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

To avoid this, we can use ‘use strict’. This ensures that you have to assign values when you declare variables.


10. What happens when we do this?
function bark() {
  console.log('Woof! ')
}

bark.animal = 'dog'
Copy the code
  • A: Working fine!
  • B: SyntaxErrorYou cannot add attributes to functions in this way.
  • C: undefined
  • D: ReferenceError
The answer

Answer: A,

This is fine in JavaScript because functions are objects! (All but basic types are objects)

A function is a special object. The code you wrote is not actually a function. A function is an object that has properties that 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 `The ${this.firstName} The ${this.lastName}`;
}

console.log(member.getFullName());
Copy the code
  • A: TypeError
  • B: SyntaxError
  • C: Lydia Hallie
  • D: undefined undefined
The answer

Answer: A,

You can’t add attributes to a constructor like you would to a regular object. If you want to add features to all instances at once, you should use prototypes. Therefore, in this example, the following method is used:

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

That’s what makes member.getFullName() work. Why is it good to do that? Suppose we add this method to the constructor itself. This method may not be required for every Person instance. This wastes a lot of memory space because they still have that property, which takes up memory space per instance. Conversely, if we just add it to the prototype, it only exists in one location 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)
Copy the code
  • A: Person {firstName: "Lydia", lastName: "Hallie"} and undefined
  • B: Person {firstName: "Lydia", lastName: "Hallie"} and Person {firstName: "Sarah", lastName: "Smith"}
  • C: Person {firstName: "Lydia", lastName: "Hallie"} and {}
  • D:Person {firstName: "Lydia", lastName: "Hallie"} and ReferenceError
The answer

Answer: A,

For Sarah, we don’t use the new keyword. When using new, this refers to the empty object we created. When new is not used, this refers to a global object.

We say this.firstName equals “Sarah” and this.lastName equals “Smith”. What we’ve actually done is define global.firstName = ‘Sarah’ and global.lastName = ‘Smith’. And Sarah herself is undefined.


13. What are the three stages of event transmission?
  • A: Target > Capturing > Bubbling
  • B: Bubbling > Target > Capturing
  • C: Target > Bubbling > Capturing
  • D: Capturing > Target > Bubbling
The answer

Answer: D

In the capture phase, events propagate down from ancestor elements to target elements. The bubbling begins when the event reaches the target element.


14. All objects have prototypes.
  • A: true
  • B: false
The answer

Answer: B

All objects except base objects have prototypes. Basic objects have access to some methods and attributes, such as.toString. That’s why you can use built-in JavaScript methods! All of these methods are available on the prototype. Although JavaScript cannot find these methods directly on objects, JavaScript will find them along the prototype chain so that you can use them.


15. What is the output?
function sum(a, b) {
  return a + b
}

sum(1.'2')
Copy the code
  • A: NaN
  • B: TypeError
  • C: "12"
  • D: 3
The answer

Answer: C

JavaScript is a dynamically typed language: we don’t specify the types of certain variables. Values can be automatically converted to another type without you knowing it. This type is called implicit Type Coercion. Coercion means to convert one type to another.

In this case, JavaScript converts the number 1 to a string so that the function makes sense and returns a value. When the numeric type (1) is added to the string type (‘2’), the number is treated as a string. We can concatenate strings like “Hello” + “World”, what’s happening here is “1” + “2”, it returns “12”.


16. What is the output?
let number = 0
console.log(number++)
console.log(++number)
console.log(number)
Copy the code
  • A: 1 1 2
  • B: 1 2 2
  • C: 0 2 2
  • D: 0 1 2
The answer

Answer: C

Increment operator ++ after unary:

  1. Return value (Return0)
  2. Value increment (number is now1)

Unary increment operator ++ :

  1. Value increment (number is now2)
  2. Return value (Return2)

It’s 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`
Copy the code
  • A: "Lydia" 21 ["", " is ", " years old"]
  • B: ["", " is ", " years old"] "Lydia" 21
  • C: "Lydia" ["", " is ", " years old"] 21
The answer

Answer: B

If a tag template literal is used, the value of the first argument always contains an array of strings. The rest of the arguments take 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 })
Copy the code
  • A: You are an adult!
  • B: You are still an adult.
  • C: Hmm.. You don't have an age I guess
The answer

Answer: C

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

The two objects we are comparing are not the same reference: the memory location of the object reference passed as an argument is not the same as the memory location of the object used to determine equality.

This is why {age: 18} === {age: 18} and {age: 18} == {age: 18} both return false.


19. What is the output?
function getAge(. args) {
  console.log(typeof args)
}

getAge(21)
Copy the code
  • A: "number"
  • B: "array"
  • C: "object"
  • D: "NaN"
The answer

Answer: C

Extension operators (… Args) returns an array of arguments. Arrays are objects, so Typeof args returns “object”.


20. What is the output?
function getAge() {
  'use strict'
  age = 21
  console.log(age)
}

getAge()
Copy the code
  • A: 21
  • B: undefined
  • C: ReferenceError
  • D: TypeError
The answer

Answer: C

With “Use strict”, you can ensure that you don’t accidentally declare global variables. We never declared the variable age because we used “use strict”, which would throw a reference error. If we don’t use “use strict”, it will work because the age attribute is added to the global object.


21. What is the output?
const sum = eval('10 * 10 + 5')
Copy the code
  • A: 105
  • B: "105"
  • C: TypeError
  • D: "10 * 10 + 5"
The answer

Answer: A,

The code is passed in as a string, and eval evaluates it. If it is an expression, as in this case, it evaluates the expression. This expression is 10 times 10 plus 5. This will return the number 105.


22. How long is cool_secret accessible?
sessionStorage.setItem('cool_secret'.123)
Copy the code
  • A: Never, the data will not be lost.
  • B: When the user closes the TAB.
  • C: When the user closes the entire browser, not just the tabs.
  • D: When the user turns off the computer.
The answer

Answer: B

Data stored in sessionStorage will be deleted only after the TAB TAB is closed.

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


23. What is the output?
var num = 8
var num = 10

console.log(num)
Copy the code
  • A: 8
  • B: 10
  • C: SyntaxError
  • D: ReferenceError
The answer

Answer: B

Using the var keyword, you can declare multiple variables with the same name. The variable will then hold the most recent value.

You cannot do this using let or const because they are block-scoped.


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)
Copy the code
  • A: false true false true
  • B: false true true true
  • C: true true false true
  • D: true true true true
The answer

Answer: C

All object keys (except Symbol) are strings at the bottom, even if you don’t enter them as strings yourself. This is why obj.hasownProperty (‘1’) also returns true.

For sets, it doesn’t work that way. There is no ‘1’ in our collection: set.has(‘1’) returns 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)
Copy the code
  • A: { a: "one", b: "two" }
  • B: { b: "two", a: "three" }
  • C: { a: "three", b: "two" }
  • D: SyntaxError
The answer

Answer: C

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


The JavaScript global execution context does two things for you: the global object and the this keyword.
  • A: true
  • B: false
  • C: it depends
The answer

Answer: A,

The base execution context is the global execution context: it is something accessible anywhere in your code.


27. What is the output?
for (let i = 1; i < 5; i++) {
  if (i === 3) continue
  console.log(i)
}
Copy the code
  • A: 1 2
  • B: 1 2 3
  • C: 1 2 4
  • D: 1 3 4
The answer

Answer: C

If a condition returns true, the continue statement skips the iteration.


28. What is the output?
String.prototype.giveLydiaPizza = () = > {
  return 'Just give Lydia pizza already! '
}

const name = 'Lydia'

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

Answer: A,

String is the built-in constructor to which we can add attributes. I just added a method to its prototype. The primitive 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])
Copy the code
  • A: 123
  • B: 456
  • C: undefined
  • D: ReferenceError
The answer

Answer: B

The key of the object is automatically converted to a string. We are trying to set an object B to be the key of object A with the corresponding value 123.

However, when you string an object, it becomes “[Object object]”. So it says, a[“[object object]”] = 123. Then, we do the same thing again, c is another object, and there is also implicit stringification, so a[“[object object]”] = 456.

Then, we print a[b], which is a[“[object object]”]. It was just set to 456, so 456 is returned.


30. What is the output?
const foo = () = > console.log('First')
const bar = () = > setTimeout(() = > console.log('Second'))
const baz = () = > console.log('Third')

bar()
foo()
baz()
Copy the code
  • A: First Second Third
  • B: First Third Second
  • C: Second First Third
  • D: Second Third First
The answer

Answer: B

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

That’s because in the browser, we have not only a runtime engine, but also something called a WebAPI. WebAPI provides setTimeout functions, as well as others, such as DOM.

After pushing the callback to WebAPI, the setTimeout function itself (but not the callback!) Will pop from the stack.

Now foo is called, printing “First”.

Foo pops off the stack and baz is called. Print “Third”.

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

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

Bar gets called, prints “Second”, and it gets popped on 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>
Copy the code
  • A: Outer div
  • B: Inner div
  • C: button
  • D: An array containing all nested elements.
The answer

Answer: C

The deepest nested element that causes an event is the target of the event. You can stop bubbling by calling Event.stopPropagation.


32. What is the log output when you click the paragraph?
<div onclick="console.log('div')">
  <p onclick="console.log('p')">
    Click here!
  </p>
</div>
Copy the code
  • A: p div
  • B: div p
  • C: p
  • D: div
The answer

Answer: A,

If we click p, we see two logs: p and div. During event propagation, there are three phases: capture, target, and bubble. By default, event handlers are executed in the bubble phase (unless useCapture is set to true). It propagates outward from the deepest nested element.


33. What is the output?
const person = { name: 'Lydia' }

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

sayHi.call(person, 21)
sayHi.bind(person, 21)
Copy the code
  • A: undefined is 21 Lydia is 21
  • B: function function
  • C: Lydia is 21 Lydia is 21
  • D: Lydia is 21 function
The answer

Answer: D

Using both methods, we can pass objects that we want the this keyword to reference. However,.call is executed immediately.

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


34. What is the output?
function sayHi() {
  return (() = > 0) (the)}typeof sayHi()
Copy the code
  • A: "object"
  • B: "number"
  • C: "function"
  • D: "undefined"
The answer

Answer: B

The sayHi method returns the return value of the execute now function (IIFE). This immediate function returns 0 and is of type number

Reference: There are only seven built-in types: NULL, undefined, Boolean, number, String, Object, and symbol. Function is not a type. A function is an object. Its type is Object.


35. Which of the following values are Falsy?
0
new Number(0)
(' ')
(' ')
new Boolean(false)
undefined
Copy the code
  • A: 0.' '.undefined
  • B: 0.new Number(0).' '.new Boolean(false).undefined
  • C: 0.' '.new Boolean(false).undefined
  • D: All of them are falsy
The answer

Answer: A,

There are only 6 falsy values:

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

Function constructors, such as New Number and New Boolean, are truthy.


36. What is the output?
console.log(typeof typeof 1)
Copy the code
  • A: "number"
  • B: "string"
  • C: "object"
  • D: "undefined"
The answer

Answer: B

Typeof 1 returns “number”. Typeof “number” Returns “string”.


37. What is the output?
const numbers = [1.2.3]
numbers[10] = 11
console.log(numbers)
Copy the code
  • A: [1, 2, 3, 7 x null, 11]
  • B: [1, 2, 3, 11]
  • C: [1, 2, 3, 7 x empty, 11]
  • D: SyntaxError
The answer

Answer: C

JavaScript creates something called “Empty slots” when you set values for an array that exceed the length of the array. Their values are actually undefined. Here’s what you’ll see:

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

This depends on your running environment (each browser, and node environment, 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)
})()
Copy the code
  • A: 1 undefined 2
  • B: undefined undefined undefined
  • C: 1 1 2
  • D: 1 undefined undefined
The answer

Answer: A,

The catch block receives the parameter X. When we pass parameters, this is different from the variable x we defined earlier. This x is in the catch block-level scope.

We then assign a value of 1 to the variable in the block-level scope and also set the value of the variable y. Now, we print the variable x in the block-level scope with a value of 1.

The value of x outside the catch block is undefined and y is 2. When we execute console.log(x) outside of the catch block, undefined is returned and y returns 2.


39. Is everything in JavaScript?
  • A: Basic types and objects
  • B: Functions and objects
  • C: Only objects
  • D: Numbers and objects
The answer

Answer: A,

JavaScript only has basic types and objects.

Basic types include Boolean, NULL, undefined, bigint, number, string, and symbol.


40. What is the output?
[[0.1], [2.3]].reduce(
  (acc, cur) = > {
    return acc.concat(cur)
  },
  [1.2])Copy the code
  • A: [0, 1, 2, 3, 1, 2]
  • B: [6, 1, 2]
  • C: [1, 2, 0, 1, 2, 3]
  • D: [1, 2, 6]
The answer

Answer: C

[1, 2] is the initial value. The initial value will be the value of the first parameter acc when first called. On the first execution, acc has the value [1, 2] and cur has the value [0, 1]. Combine them and the result is [1, 2, 0, 1]. On the second execution, acc has the value [1, 2, 0, 1] and cur has the value [2, 3]. Combine them and the end result is [1, 2, 0, 1, 2, 3]


41. What is the output?
!!!!!null!!!!!' '!!!!!1
Copy the code
  • A: false true false
  • B: false false true
  • C: false true true
  • D: true true false
The answer

Answer: B

Null is falsy. ! The value of null is true. ! The value of true is false.

“” is falsy. !” The value of “is true. ! The value of true is false.

1 is truthy. ! The value of 1 is false. ! The value of false is true.


42. setIntervalWhat is the return value of the method?
setInterval(() = > console.log('Hi'), 1000)
Copy the code
  • A: A unique ID
  • B: The number of milliseconds specified by this method
  • C: Transfer function
  • D: undefined
The answer

Answer: A,

SetInterval returns a unique ID. This ID can be used by the clearInterval function to cancel timing.


43. What is the output?
[...'Lydia']
Copy the code
  • A: ["L", "y", "d", "i", "a"]
  • B: ["Lydia"]
  • C: [[], "Lydia"]
  • D: [["L", "y", "d", "i", "a"]]
The answer

Answer: A,

The string type is iterable. The extension operator maps each character of the iteration to 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);
Copy the code
  • A: [0, 10], [10, 20]
  • B: 20, 20
  • C: 10, 20
  • D: 0, 10 and 10, 20
The answer

Answer: C

A normal function cannot be stopped midway through its execution. Generator functions, however, can “stop” midway through and pick up where they left off. When the generator encounters the yield keyword, the value following yield is generated. Note that the generator does not return a value in this case, but rather generates a yield value.

First, we initialize the generator function with 10 as parameter I. The generator is then executed step by step using the next() method. The first time the generator is executed, the value of I is 10, and the first yield keyword is encountered, which generates the value of I. At this point, the generator “pauses” and produces 10.

We then execute the next() method. The generator will pick up where it left off, and I will still be 10. So we get to the second yield keyword, and the value that needs to be generated is I *2, and I is 10, so the value that needs to be generated is 20. So the final answer to this problem 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));
Copy the code
  • A: "one"
  • B: "two"
  • C: "two" "one"
  • D: "one" "two"
The answer

Answer: B

When we pass multiple promises into the promise.race method, priority resolution takes place. In this example, we use setTimeout to set the 500ms and 100ms timers for firstPromise and secondPromise, respectively. This means that secondPromise will parse the string two first. In this case, the res parameter is two and is the output result.


46. What is the output?
let person = { name: "Lydia" };
const members = [person];
person = null;

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

Answer: D

First we declare an object person with a name attribute.

We then declare a variable members. Assign the first element to the person variable. When two objects are set equal to each other, they interact by reference. But when you assign a reference from one variable to another, you’re just doing a copy. (Note that they are quoted differently!)

Next we make Person equal to null.

Instead of changing the value of the first element of the array, we just changed the value of the variable Person, because the element (copied) has a different reference than Person. The first element of Members retains a reference to the original object. When we print out the Members array, the first element prints out the referenced object.


47. What is the output?
const person = {
  name: "Lydia".age: 21
};

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

Answer: B

In a for-in loop, we can iterate over the object’s key, which is name and age here. At the bottom, objects’ keys are strings (if they are not symbols). In each loop, we set item to be the key we are currently traversing. So at first, item is name, and then item outputs age.


48. What is the output?
console.log(3 + 4 + "5");
Copy the code
  • A: "345"
  • B: "75"
  • C: 12
  • D: "12"
The answer

Answer: B

When all operators have the same precedence, the evaluation expression needs to determine the order in which the operators are combined, that is, from right to left or from left to right. In this case, we have only one class of operator +, and for addition, the order of incorporation is left to right.

3 + 4 is calculated first to get the number 7.

Due to type casting, 7 + ‘5’ results in “75”. JavaScript converts 7 to a string, see question 15. We can concatenate two strings with a + sign. “7” plus “5” gives me “75”.


49. numWhat is the value of theta?
const num = parseInt("7" x 6".10);
Copy the code
  • A: 42
  • B: "42"
  • C: 7
  • D: NaN
The answer

Answer: C

Only the first character of the string is returned. After setting the base (the second parameter, which specifies the base of the number to parse: decimal, 16, octal, binary, etc.) ,parseInt checks whether characters in a string are valid. On encountering an invalid character in the specified base, immediately stop parsing and ignore all subsequent characters.

* is an illegal numeric character. So only “7” is parsed, and the decimal value of 7. Num is 7.


50. What is the output?
[1.2.3].map(num= > {
  if (typeof num === "number") return;
  return num * 2;
});
Copy the code
  • A: []
  • B: [null, null, null]
  • C: [undefined, undefined, undefined]
  • D: [ 3 x empty ]
The answer

Answer: C

When mapping an array,num is the element currently looping through. In this example, all mappings are of type number, so typeof num === “number” in if results in true. The map function creates a new array and inserts the function’s return value into the array.

However, no value is returned. Undefined is returned by default when the function does not return any value. 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);
Copy the code
  • A: { name: "Lydia" }, "1997"
  • B: { name: "Sarah" }, "1998"
  • C: { name: "Lydia" }, "1998"
  • D: { name: "Sarah" }, "1997"
The answer

Answer: A,

Unlike ordinary parameters, which are passed by value, objects are passed by reference. So birthYear is value passed because it is a string rather than an object. When we pass a value to a parameter, a copy of that value is created. (Please refer to Q.46)

The birthYear variable has a reference to “1997” and the passed parameter also has a reference to “1997”, but the references are not the same. When we update the value of year by assigning “1998” to it, we are simply updating year. BirthYear is still “1997” at this point.

And person is an object. The member argument refers to the same object. When we modify the attributes of the object referenced by member, the corresponding attributes of person are also modified because they refer to the same object, and the name attribute of person becomes “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();
Copy the code
  • 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!
The answer

Answer: D

With the throw statement, we can create custom errors. And from that, we can throw an exception. An exception can be a string, a number, a Boolean type, or an object. In this case, our exception is the string ‘Hello world’.

With a catch statement, we can specify what to do when an exception is thrown in a try block. The exception thrown in this case is the string ‘Hello world’. E is the string and is therefore printed. The final 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);
Copy the code
  • A: "Lamborghini"
  • B: "Maserati"
  • C: ReferenceError
  • D: TypeError
The answer

Answer: B

When a property is returned, the value of the property is equal to the returned value, not the value specified in the constructor. We return the string “Maserati”, so mycar. make equals “Maserati”.


54. What is the output?
(() = > {
  let x = (y = 10); }) ();console.log(typeof x);
console.log(typeof y);
Copy the code
  • A: "undefined", "number"
  • B: "number", "number"
  • C: "object", "number"
  • D: "number", "undefined"
The answer

Answer: A,

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

y = 10;
let x = y;
Copy the code

When we set y to 10, we actually add a property y to the global object (window in the browser, global in Nodejs). In browsers, window.y is equal to 10.

We then declare the variable x equal to y, also 10. However, the variable is declared using let, which only applies to the block-level scope and is only valid in the block in which it is declared; This is the immediate invocation expression (IIFE) in this case. When using the Typeof operator, the operation value x is not defined: we cannot call it because we are outside the x declaration block. That means that x is undefined. Unassigned or undeclared variables of type “undefined”. Console. log(typeof x) returns “undefined”.

Instead, we create the global variable y and set y to 10. This value is accessed everywhere in our code. Y is already defined, and it has a value of type “number”. Console. log(typeof y) returns “number”.


55. What is the output?
class Dog {
  constructor(name) {
    this.name = name;
  }
}

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

const pet = new Dog("Mara");

pet.bark();

delete Dog.prototype.bark;

pet.bark();
Copy the code
  • A: "Woof I am Mara".TypeError
  • B: "Woof I am Mara"."Woof I am Mara"
  • C: "Woof I am Mara".undefined
  • D: TypeError.TypeError
The answer

Answer: A,

We can use the delete keyword to delete attributes of objects, which is also true for stereotypes. After the attribute of the stereotype is deleted, it is no longer available on the stereotype chain. In this case, the function bark is not available after the delete dog.prototype. bark is still called by subsequent code.

TypeError is thrown when we try to call a function that does not exist. In this case, TypeError: pet.bark is not a function, because pet.bark is undefined.


56. What is the output?
const set = new Set([1.1.2.3.4]);

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

Answer: D

A Set object is a collection of unique values: that is, the same value occurs only once in it.

We pass in the array [1, 1, 2, 3, 4], which has a duplicate value of 1. Because you can’t have two duplicate values in a set, 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;
Copy the code
// index.js
import myCounter from "./counter";

myCounter += 1;

console.log(myCounter);
Copy the code
  • A: 10
  • B: 11
  • C: Error
  • D: NaN
The answer

Answer: C

Imported modules are read-only: you cannot modify imported modules. Their values can only be modified by exporting their modules.

When we add a value to myCounter we throw an exception: myCounter is read-only and cannot be modified.


58. What is the output?
const name = "Lydia";
age = 21;

console.log(delete name);
console.log(delete age);
Copy the code
  • A: false.true
  • B: "Lydia".21
  • C: true.true
  • D: undefined.undefined
The answer

Answer: A,

The delete operator returns a Boolean value: true for successful deletion, false otherwise. However, variables declared by the var, const, or let keywords cannot be deleted using the DELETE operator.

The name variable is declared by the const keyword, so deletion failed: return false. And when we set age to 21, we’re actually adding a property called age to the global object. Properties in objects can be deleted, as can global objects, so delete Age returns true.


59. What is the output?
const numbers = [1.2.3.4.5];
const [y] = numbers;

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

Answer: C

We can parse the value of an array or property from an object by deconstructing assignment, for example:

[a, b] = [1.2];
Copy the code

The value of A is now 1, and the value of b is now 2. And here’s what we did:

[y] = [1.2.3.4.5];
Copy the code

That is, y equals the first value of the array is the number 1. We print y and return 1.


60. What is the output?
const user = { name: "Lydia".age: 21 };
const admin = { admin: true. user };console.log(admin);
Copy the code
  • A: { admin: true, user: { name: "Lydia", age: 21 } }
  • B: { admin: true, name: "Lydia", age: 21 }
  • C: { admin: true, user: ["Lydia", 21] }
  • D: { admin: true }
The answer

Answer: B

Extended operators… Provides the possibility of composing objects. You can copy key-value pairs from an object and add them to another object. In this case, we copy the user object key-value pairs and add them to the Admin object. The admin 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));
Copy the code
  • A: { name: "Lydia", age: 21 }.["name", "age"]
  • B: { name: "Lydia", age: 21 }.["name"]
  • C: { name: "Lydia"}.["name", "age"]
  • D: { name: "Lydia"}.["age"]
The answer

Answer: B

With the defineProperty method, we can add a new attribute to an object or modify an existing attribute. After we add a property to the Object using defineProperty, the property defaults to not Enumerable. The object.keys method only returns an enumerable property in the Object, so it’s just “name”.

Attributes added using the defineProperty method are immutable by default. You can change this behavior with the Writable, 64x and Enumerable properties. In this way, the attributes added by the defineProperty method have more control than those you add yourself.


62. What is the output?
const settings = {
  username: "lydiahallie".level: 19.health: 90
};

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

Answer: A,

The second argument to json.stringify is replacer. A replacer can be a function or an array that controls which values are converted to a string.

If the replacer is an array, then only the properties contained in the array will be converted to a string. In this case, only properties named “level” and “health” are included, and “username” is excluded. Data equals “{“level”:19, “health”:90}”.

If the replacer is a function, it will be called once for every property of the object. The value returned by the function becomes the value of this property, which is reflected in the converted JSON string. In Chrome, if there is an exception when all attributes return the same value, the return value will be directly output as the result of the JSON string), and if the return value is undefined, the attribute will be 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);
Copy the code
  • A: 10.10
  • B: 10.11
  • C: 11.11
  • D: 11.12
The answer

Answer: A,

The unary operator ++ returns and then accumulates the operands. Num1 is 10, since the increaseNumber function first returns the value of num, which is 10, and then accumulates num.

Num2 is 10 since we pass num1 increasePassedNumber. Number is equal to 10 (the value of num1). In the same way, ++ returns the operand and then accumulates the operand. Number is 10, so num2 is 10.


64. Output what?
const value = { number: 10 };

const multiply = (x = { ... value }) = > {
  console.log(x.number *= 2);
};

multiply();
multiply();
multiply(value);
multiply(value);
Copy the code
  • A: 20.40.80.160
  • B: 20.40.20.40
  • C: 20.20.20.40
  • D: NaN.NaN.20.40
The answer

Answer: C

In ES6, we can initialize parameters with default values. If no parameter is passed to the function, or if the parameter value is “undefined”, the parameter value will be the default value. In the example above, we deconstructed the value object and passed it to a new object, so the default value for x is {number: 10}.

Default arguments are evaluated only when called, and a new object is created each time the function is called. The multiply function is called the first two times without passing a value, so x defaults to {number: 10} each time, so the printed product of the number is 20.

On the third call to Multiply, we pass one argument, the object value. The *= operator is actually short for x.number = x.number * 2, and we changed the value of x.number and printed out the value 20.

The fourth time, we pass the value object again. X. number * = 2 is printed as 40 because it was changed to 20.


65. Output what?
[1.2.3.4].reduce((x, y) = > console.log(x, y));
Copy the code
  • A: 1 2 and 3 3 and 6 4
  • B: 1 2 and 2 3 and 3 4
  • C: 1 undefined and 2 undefined and 3 undefined and 4 undefined
  • D: 1 2 and undefined 3 and undefined 4
The answer

Answer: D

The reducer function receives four parameters:

  1. Accumulator (ACC)
  2. Current Value (CUR)
  3. Current Index (IDX)
  4. Source Array (SRC)

The return value from the Reducer function is assigned to the accumulator and is remembered in each iteration of the array and becomes the final single result value.

The Reducer function also has an optional parameter, initialValue, which will be the value of the first parameter when the callback function is first called. If no initialValue is provided, the first element in the array is used.

In the above example, the first parameter (Accumulator) received by the Reduce method is X and the second Current Value (Current Value) is Y.

On the first call, the accumulator x is 1 and the current value “y” is 2, printing out the accumulator and the current value: 1 and 2.

Our callback function in this example does not return any value, but simply prints the accumulator’s value and the current value. If the function returns no value, undefined is returned by default. On the next call, the accumulator is undefined and the current value is “3”, so undefined and 3 are printed.

On the fourth call, the callback function still returns no value. The accumulator is undefined again and the current value is “4”. Undefined and 4 are printed.


66. Which constructor to use for successful inheritanceDogThe class?
class Dog {
  constructor(name) {
    this.name = name; }};class Labrador extends Dog {
  / / 1
  constructor(name, size) {
    this.size = size;
  }
  / / 2
  constructor(name, size) {
    super(name);
    this.size = size;
  }
  / / 3
  constructor(size) {
    super(name);
    this.size = size;
  }
  / / 4
  constructor(name, size) {
    this.name = name;
    this.size = size; }};Copy the code
  • A: 1
  • B: 2
  • C: 3
  • D: 4
The answer

Answer: B

In subclasses, the this keyword cannot be accessed until super is called. If it does, it will throw a ReferenceError: 1 and 4 will raise a ReferenceError.

With the super keyword, the constructor of the parent class needs to be called with the given arguments. The constructor of the parent class takes the name argument, so we need to pass name to super.

The Labrador class receives two arguments, name because it inherits Dog and size as additional attributes of the Labrador class, both of which need to be passed to the Labrador constructor, so constructor 2 is used to do this correctly.


67. Output what?
// index.js
console.log('running index.js');
import { sum } from './sum.js';
console.log(sum(1.2));

// sum.js
console.log('running sum.js');
export const sum = (a, b) = > a + b;
Copy the code
  • A: running index.js.running sum.js.3
  • B: running sum.js.running index.js.3
  • C: running sum.js.3.running index.js
  • D: running index.js.undefined.running sum.js
The answer

Answer: B

The import command is executed at compile time, before the code runs. So this means that the imported module will run first, and the imported module’s file will run after.

This is the difference between require () and import in CommonJS. With require(), you can load dependencies as needed at run time. If we use require instead of import, running index.js, running sum.js, 3 will be printed in sequence.


68. Output what?
console.log(Number(2) = = =Number(2))
console.log(Boolean(false) = = =Boolean(false))
console.log(Symbol('foo') = = =Symbol('foo'))
Copy the code
  • A: true.true.false
  • B: false.true.false
  • C: true.false.true
  • D: true.true.true
The answer

Answer: A,

Each Symbol is completely unique. The parameter passed to Symbol is just a description given to Symbol. The value of Symbol does not depend on the parameter passed. When we test for equality, we create two brand new symbols: the first Symbol (‘foo’) and the second Symbol (‘foo’). These two values are unique and not equal to each other, so return false.


69. Output what?
const name = "Lydia Hallie"
console.log(name.padStart(13))
console.log(name.padStart(2))
Copy the code
  • A: "Lydia Hallie"."Lydia Hallie"
  • B: " Lydia Hallie"." Lydia Hallie" ("[13x whitespace]Lydia Hallie"."[2x whitespace]Lydia Hallie")
  • C: " Lydia Hallie"."Lydia Hallie" ("[1x whitespace]Lydia Hallie"."Lydia Hallie")
  • D: "Lydia Hallie"."Lyd"
The answer

Answer: C

Using the padStart method, we can add padding at the beginning of the string. The argument passed to this method is the total length of the string, including padding. The string Lydia Hallie is 12 in length, so name.padstart (13) inserts only 1 (13-12 = 1) space at the beginning of the string.

If the parameter passed to the padStart method is less than the length of the string, no padding is added.


70. Output what?
console.log("πŸ₯‘" + "πŸ’»");
Copy the code
  • A: "πŸ₯‘ πŸ’»"
  • B: 257548
  • C: A string containing their code points
  • D: Error
The answer

Answer: A,

Using the + operator, you can concatenate strings. In the above case, we concatenate the string “πŸ₯‘” with the string “πŸ’»” to produce “πŸ₯‘πŸ’»”.


71. How can I print itconsole.logThe value commented out after the statement?
function* startGame() {
  const answer = yield "Do you love JavaScript?";
  if(answer ! = ="Yes") {
    return "Oh wow... Guess we're gone here";
  }
  return "JavaScript loves you back ❀️";
}

const game = startGame();
console.log(/ * 1 * /); // Do you love JavaScript?
console.log(/ * 2 * /); // JavaScript loves you back ❀️
Copy the code
  • A: game.next("Yes").value and game.next().value
  • B: game.next.value("Yes") and game.next.value()
  • C: game.next().value and game.next("Yes").value
  • D: game.next.value() and game.next.value("Yes")
The answer

Answer: C

Generator functions “pause” their execution when they encounter the yield keyword. First, we need to make the function produce a string Do you love JavaScript? This can be done by calling game.next().value. The first line of the above function has a yield keyword, so the operation stops immediately. The yield expression itself returns no value, or always returns undefined, which means that the variable answer is undefined at this point

The next method can take an argument that is treated as the return value of the previous yield expression. When we call game.next(“Yes”).value, the return value of the previous yield will be replaced with the argument “Yes” passed to the next() function. At this point the variable answer is assigned to “Yes” and the if statement returns false, so JavaScript loves you back ❀️ is printed.


72. Output what?
console.log(String.raw`Hello\nworld`);
Copy the code
  • A: Hello world!
  • B: Hello

    Β  Β  Β world
  • C: Hello\nworld
  • D: Hello\n

    Β  Β  Β world
The answer

Answer: C

The string. raw function is used to get the raw String of a template String. It returns a String in which the escape characters (\n, \v, \t, etc.) are ignored. Backslashes can cause problems, however, because you might encounter something like the following:

const path = `C:\Documents\Projects\table.html`
String.raw`${path}`
Copy the code

This will result in:

"C:DocumentsProjects able.html"

Use string.raw directly

String.raw`C:\Documents\Projects\table.html`
Copy the code

It ignores the escape character and prints: C:\Documents\Projects\table.html

In the above case, the string Hello\nworld is printed out.


73. Output what?
async function getData() {
  return await Promise.resolve("I made it!");
}

const data = getData();
console.log(data);
Copy the code
  • A: "I made it!"
  • B: Promise {<resolved>: "I made it!" }
  • C: Promise {<pending>}
  • D: undefined
The answer

Answer: C

Asynchronous functions always return a promise. Await the promise: When we call getData() and assign it to data, data is a pending promise returned by the getData method, and the promise is not resolved.

If we want to access the resolved value “I made it!” The.then() method is used on data:

data.then(res => console.log(res))

This will print “I made it!”


74. Output what?
function addToList(item, list) {
  return list.push(item);
}

const result = addToList("apple"["banana"]);
console.log(result);
Copy the code
  • A: ['apple', 'banana']
  • B: 2
  • C: true
  • D: undefined
The answer

Answer: B

The push() method returns the length of the new array. Initially, the array contains one element (the string “banana”) of length 1. After adding the string “apple” to the array, the length becomes 2 and is returned from the addToList function.

The push method modifies the original array. If you want to return the array from a function instead of its length, you should return the list after the push item.


75. Output what?
const box = { x: 10.y: 20 };

Object.freeze(box);

const shape = box;
shape.x = 100;
console.log(shape)
Copy the code
  • A: { x: 100, y: 20 }
  • B: { x: 10, y: 20 }
  • C: { x: 100 }
  • D: ReferenceError
The answer

Answer: B

Object.freeze makes it impossible to add, delete, or modify attributes of an Object (unless the value of the attribute is another Object).

When we create the variable shape and set it to be equal to the frozen object box, shape also refers to the frozen object. You can use object. isFrozen to check if an Object isFrozen, in which case object. isFrozen (shape) returns true.

Since shape is frozen and the value of x is not an object, we cannot modify property X. X is still equal to 10 and {x: 10, y: 20} is printed.

Note that in the example above we made changes to attribute X that might cause TypeError exceptions to be thrown (most commonly but not exclusively in strict mode).


76. Output what?
const { name: myName } = { name: "Lydia" };

console.log(name);
Copy the code
  • A: "Lydia"
  • B: "myName"
  • C: undefined
  • D: ReferenceError
The answer

Answer: D

When we deconstruct the attribute name from the object on the right, we assign its value Lydia to a variable named myName.

With {name: myName}, we are telling JavaScript that we want to create a new variable named myName whose value is the value of the name property of the object on the right.

ReferenceError is raised when we try to print name, an undefined variable.


Is the following a pure function?
function sum(a, b) {
  return a + b;
}
Copy the code
  • A: Yes
  • B: No
The answer

Answer: A,

Pure function A function that always yields the same output if the input parameters are the same.

The sum function always returns the same result. If we pass 1 and 2, it will always return 3 with no side effects. If we pass 5 and 10, it will always return 15, and so on, which is the definition of a pure function.


78. Output what?
const add = () = > {
  const cache = {};
  return num= > {
    if (num in cache) {
      return `From cache! ${cache[num]}`;
    } else {
      const result = num + 10;
      cache[num] = result;
      return `Calculated! ${result}`; }}; };const addFunction = add();
console.log(addFunction(10));
console.log(addFunction(10));
console.log(addFunction(5 * 2));
Copy the code
  • A: Calculated! 20 Calculated! 20 Calculated! 20
  • B: Calculated! 20 From cache! 20 Calculated! 20
  • C: Calculated! 20 From cache! 20 From cache! 20
  • D: Calculated! 20 From cache! 20 Error
The answer

Answer: C

The add function is a memory function. By mnemonizing, we can cache the results of a function to speed up its execution. In this case, we create a cache object to store the previously returned value.

If we call the addFunction function multiple times with the same argument, it first checks to see if the value is already in the cache, and if so, returns the cached value, which saves execution time. If not, it calculates the value and stores it in the cache.

We call the addFunction function three times with the same value:

On the first call, the value of the function is not cached when num equals 10. The if statement num in cache returns false, and the code for the else block is executed: Calculated! 20, and the result is added to the cache object, cache now looks like {10:20}.

The second time, the cache object contains the return value of 10. If num in cache returns true, From cache! 20 is printed.

The third time, we pass 5 * 2(value 10) to the function. The cache object contains the return value of 10. If num in cache returns true, From cache! 20 is printed.


79. Output what?
const myLifeSummedUp = ["β˜•"."πŸ’»"."🍷"."🍫"]

for (let item in myLifeSummedUp) {
  console.log(item)
}

for (let item of myLifeSummedUp) {
  console.log(item)
}
Copy the code
  • A: 0 1 2 3 and "β˜•" "πŸ’»" "🍷" "🍫"
  • B: "β˜•" "πŸ’»" "🍷" "🍫" and "β˜•" "πŸ’»" "🍷" "🍫"
  • C: "β˜•" "πŸ’»" "🍷" "🍫" and 0 1 2 3
  • D: 0 1 2 3 and {0: "β˜•", 1: "πŸ’»", 2: "🍷", 3: "🍫"}
The answer

Answer: A,

Through a for-in loop, we can iterate over an object’s own, inherited, enumerable, non-symbol properties. In arrays, enumerable properties are the “keys” of the array elements, their indexes. This object looks like the following:

{0: "β˜•", 1: "πŸ’»", 2: "🍷", 3: "🍫"}

Keys are enumerable properties, so 0, 1, 2, and 3 are recorded.

With a for-of loop, we can iterate over iterables (Array, Map, Set, String, arguments, etc.). As we iterate over the array, in each iteration, the values of the different attributes will be assigned to the variable item, so “β˜•”, “πŸ’»”, “🍷”, “🍫” are printed.


80. Output what?
const list = [1 + 2.1 * 2.1 / 2]
console.log(list)
Copy the code
  • A: ["1 + 2", "1 * 2", "1/2 "]
  • B: [" 12 ", 2, 0.5]
  • C: [3, 2, 0.5]
  • D: [1, 1, 1)
The answer

Answer: C

Array elements can contain any value. Numbers, strings, booleans, objects, arrays, null, undeifned, and other expressions such as dates, functions, and calculations.

The element will be equal to the value returned. 1 + 2 returns 3,1 * 2 returns ‘2, ‘and 1/2 returns 0.5.


81. Output what?
function sayHi(name) {
  return `Hi there, ${name}`
}

console.log(sayHi())
Copy the code
  • A: Hi there,
  • B: Hi there, undefined
  • C: Hi there, null
  • D: ReferenceError
The answer

Answer: B

By default, if no parameter is passed to a function, the parameter value is undefined. In the above case, we did not pass a value to the parameter name. Name equals undefined and is printed.

In ES6, we can override this default undefined value with a default parameter. Such as:

Function sayHi (name = "Lydia") {... }

In this case, if we’re not passing a value or if we’re passing undefined, name is always equal to the string Lydia


82. Output what?
var status = "😎"

setTimeout(() = > {
  const status = "😍"

  const data = {
    status: "πŸ₯‘".getStatus() {
      return this.status
    }
  }

  console.log(data.getStatus())
  console.log(data.getStatus.call(this))},0)
Copy the code
  • A: "πŸ₯‘" and "😍"
  • B: "πŸ₯‘" and "😎"
  • C: "😍" and "😎"
  • D: "😎" and "😎"
The answer

Answer: B

The orientation of the this keyword depends on where it is used. In a function, such as getStatus, this refers to the object on which it was called. In the above example, the data object calls getStatus, so this refers to the data object. When we print this.status, the status property of the data object is printed, which is “πŸ₯‘”.

Using the call method, you can change the object to which this points. Data.getstatus. call(this) changes the reference of this from a data object to a global object. On the global object, there is a variable called status with a value of “😎”. So when this.status is printed, 😎 is printed.


83. Output what?
const person = {
  name: "Lydia".age: 21
}

let city = person.city
city = "Amsterdam"

console.log(person)
Copy the code
  • A: { name: "Lydia", age: 21 }
  • B: { name: "Lydia", age: 21, city: "Amsterdam" }
  • C: { name: "Lydia", age: 21, city: undefined }
  • D: "Amsterdam"
The answer

Answer: A,

We set the variable city to equal the value of the property named City on the Person object. There is no property named city on this object, so the value of the variable city is undefined.

Notice that we are not referencing the Person object itself, but simply setting the variable city to equal the current value of the city property on the Person object.

We then set city to equal the string “Amsterdam”. This does not change the Person object: there is no reference to it.

So when you print the Person object, you return the unmodified object.


84. Output what?
function checkAge(age) {
  if (age < 18) {
    const message = "Sorry, you're too young."
  } else {
    const message = "Yay! You're old enough!"
  }

  return message
}

console.log(checkAge(21))
Copy the code
  • A: "Sorry, you're too young."
  • B: "Yay! You're old enough!"
  • C: ReferenceError
  • D: undefined
The answer

Answer: C

Variables declared by const and let are block-level scoped, and a block is anything between curly braces ({}), the curly braces of the if/else statement described above. Because of block-level scope, we cannot refer to variables outside of the declared block, so a ReferenceError is thrown.


85. What kind of information will be printed?
fetch('https://www.website.com/api/user/1')
  .then(res= > res.json())
  .then(res= > console.log(res))
Copy the code
  • A: fetchResults of the method
  • B: The second callfetchResults of the method
  • C: the former one.then()The result returned by the callback method in
  • D: alwaysundefined
The answer

Answer: C

The value of res in the second.then is the value returned by the callback function in the previous.then. You can continue linking.then like this, passing the value to the next handler.


86. Which option is the besthasNameSet totrueThe premise is that the method can not betruePass it as a parameter?
function getName(name) {
  const hasName = //
}
Copy the code
  • A: !!!!! name
  • B: name
  • C: new Boolean(name)
  • D: name.length
The answer

Answer: A,

Use logical non-operators! , will return a Boolean value, using!! Name, we can determine whether the value of name is true or false. If name is true, then! Name returns false. ! False returns true.

By setting hasName to name, you can set hasName to be equal to the value passed to getName instead of the Boolean value true.

New Boolean (true) returns an object wrapper, not the Boolean value itself.

Name. length returns the length of the passed argument, not the Boolean value true.

87. Output what?
console.log("I want pizza"[0])
Copy the code
  • A: "" "
  • B: "I"
  • C: SyntaxError
  • D: undefined
The answer

Answer: B

You can use square bracket notation to get the characters of a particular index in a string, where the first character has the index 0, and so on. In this case, we want to get the element with an index of 0, and the character ‘I’ is recorded.

Note that this method is not supported by IE7 and earlier. In this case,.charat () should be used


88. Output what?
function sum(num1, num2 = num1) {
  console.log(num1 + num2)
}

sum(10)
Copy the code
  • A: NaN
  • B: 20
  • C: ReferenceError
  • D: undefined
The answer

Answer: B

You can set the value of the default parameter to another parameter of the function, as long as the other parameter is defined before it. We pass the value 10 to the sum function. If the sum function takes only one argument, it means that no num2 is passed, in which case num1 is equal to the passed value of 10. The default value for num2 is the value of num1, which is 10. Num1 + num2 returns 20.

If you try to set the value of the default parameter to the parameter defined later, the value of the parameter may not be initialized, resulting in an error. Such as:

function test(m = n, n = 2) {
	console.log(m, n)
}
test() // Uncaught ReferenceError: Cannot access 'n' before initialization
test(3) 2 / / 3
test(3.4) / / 3 4
Copy the code


89. Output what?
// module.js 
export default() = >"Hello world"
export const name = "Lydia"

// index.js 
import * as data from "./module"

console.log(data)
Copy the code
  • A: { default: function default(), name: "Lydia" }
  • B: { default: function default() }
  • C: { default: "Hello world", name: "Lydia" }
  • D: Global object of module.js
The answer

Answer: A,

Using the import * as name syntax, we import all exports from the module.js file into the index.js file and create a new object named data. In the module.js file, there are two exports: default and named. The default export is a function that returns the string “Hello World”, and the named export is a variable named name whose value is the string “Lydia”.

The data object has the default exported property, and the other properties have the name of the specified exports and its corresponding value.


90. Output what?
class Person {
  constructor(name) {
    this.name = name
  }
}

const member = new Person("John")
console.log(typeof member)
Copy the code
  • A: "class"
  • B: "function"
  • C: "object"
  • D: "string"
The answer

Answer: C

Class is the syntactic sugar of the constructor, and if you overwrite the Person class as a constructor it will look like this:

function Person() {
  this.name = name
}
Copy the code

Calling the constructor with new generates an instance of the constructor Person, on which typeof the keyword returns “object”, in which case “object” is printed.


91. Output what?
let newList = [1.2.3].push(4)

console.log(newList.push(5))
Copy the code
  • A: [1, 2, 3, 4, 5]
  • B: [1, 2, 3, 5]
  • C: [1, 2, 3, 4]
  • D: Error
The answer

Answer: D

The.push method returns the length of the array, not the array itself! By setting newList to [1,2,3].push(4), newList is actually equal to the new length of the array: 4.

Then, try using the.push method on newList. Since newList is a value of 4, TypeError is raised.


92. Output what?
function giveLydiaPizza() {
  return "Here is pizza!"
}

const giveLydiaChocolate = () = > "Here's chocolate... now go hit the gym already."

console.log(giveLydiaPizza.prototype)
console.log(giveLydiaChocolate.prototype)
Copy the code
  • A: { constructor: ... } { constructor: ... }
  • B: {} { constructor: ... }
  • C: { constructor: ... } {}
  • D: { constructor: ... } undefined
The answer

Answer: D

Regular functions, such as the giveLydiaPizza function, have a Prototype attribute, which is an object with the constructor attribute. However, arrow functions, such as the giveLydiaChocolate function, do not have this Prototype attribute. Try to use giveLydiaChocolate. Prototype access prototype property when it returns undefined.


93. Output what?
const person = {
  name: "Lydia".age: 21
}

for (const [x, y] of Object.entries(person)) {
  console.log(x, y)
}
Copy the code
  • A: name Lydia and age 21
  • B: ["name", "Lydia"] and ["age", 21]
  • C: ["name", "age"] and undefined
  • D: Error
The answer

Answer: A,

The object.entries () method returns an array of key-value pairs for a given Object’s own enumerable properties. In this case, it returns a two-dimensional array where each element is an array of keys and values:

[['name', 'Lydia'], ['age', 21]

With a for-of loop, we can iterate over each element in an array, in this case subarrays. We can use const [x, y] to deconstruct subarrays in a for-of loop. X is equal to the first element in the subarray, and y is equal to the second element in the subarray.

The first subarray is [” name “, “Lydia”], where X equals name and Y equals Lydia. The second subarray is [” age “, 21], where x equals age and y equals 21.


94. Output what?
function getItems(fruitList, ... args, favoriteFruit) {
  return [...fruitList, ...args, favoriteFruit]
}

getItems(["banana"."apple"]."pear"."orange")
Copy the code
  • A: ["banana", "apple", "pear", "orange"]
  • B: [["banana", "apple"], "pear", "orange"]
  • C: ["banana", "apple", ["pear"], "orange"]
  • D: SyntaxError
The answer

Answer: D

. Args is the remaining parameter, and the value of the remaining parameter is an array containing all remaining parameters and can only be used as the last parameter. In the example above, the remaining argument is the second argument, which is impossible and throws a syntax error.

function getItems(fruitList, favoriteFruit, ... args) {
  return [...fruitList, ...args, favoriteFruit]
}

getItems(["banana"."apple"]."pear"."orange")
Copy the code

The above example is valid and will return arrays: [‘banana’, ‘apple’, ‘orange’, ‘Pear’]


95. Output what?
function nums(a, b) {
  if
  (a > b)
  console.log('a is bigger')
  else 
  console.log('b is bigger')
  return 
  a + b
}

console.log(nums(4.2))
console.log(nums(1.2))
Copy the code
  • A: a is bigger.6 and b is bigger.3
  • B: a is bigger.undefined and b is bigger.undefined
  • C: undefined and undefined
  • D: SyntaxError
The answer

Answer: B

In JavaScript, we don’t have to explicitly write semicolons (;) , but the JavaScript engine still automatically adds semicolons after statements. This is called automatic semicolon insertion. For example, a statement can be a variable, or a keyword like throw, return, or break.

Here, we write a return statement and another value a + b on a new line. However, since it’s a new line, the engine doesn’t know that it’s actually the value we want to return. Instead, it automatically adds a semicolon after the return. You can look at it this way:

  return;
  a + b
Copy the code

This means that it never reaches a + B because the function stops running after the return keyword. If there is no return value, as here, the function returns undefined. Note that there is no automatic insertion after the if/else statement!


96. Output what?
class Person {
  constructor() {
    this.name = "Lydia"
  }
}

Person = class AnotherPerson {
  constructor() {
    this.name = "Sarah"}}const member = new Person()
console.log(member.name)
Copy the code
  • A: "Lydia"
  • B: "Sarah"
  • C: Error: cannot redeclare Person
  • D: SyntaxError
The answer

Answer: B

We can set the class to be equal to other class/function constructors. In this case, we set Person to AnotherPerson. The constructor name is Sarah, so the name attribute on the new Person instance member is Sarah.


97. Output what?
const info = {
  [Symbol('a')]: 'b'
}

console.log(info)
console.log(Object.keys(info))
Copy the code
  • A: {Symbol('a'): 'b'} and ["{Symbol('a')"]
  • B: {} and []
  • C: { a: "b" } and ["a"]
  • D: {Symbol('a'): 'b'} and []
The answer

Answer: D

The Symbol type is not enumerable. The object.keys method returns all the enumerable key properties on an Object. The Symbol type is invisible and returns an empty array. When recording the entire object, all properties are visible, even non-enumerable properties.

This is one of Symbol’s many features: in addition to representing completely unique values (preventing accidental object name conflicts, such as when using two libraries that want to add attributes to the same object), you can also hide the attributes of objects in this way (although not completely). You can still use the Object. GetOwnPropertySymbols visit Symbol () method.


98. Output what?
const getList = ([x, ...y]) = > [x, y]
const getUser = user= > { name: user.name, age: user.age }

const list = [1.2.3.4]
const user = { name: "Lydia".age: 21 }

console.log(getList(list))
console.log(getUser(user))
Copy the code
  • A: [1, 2, 3, 4]] and undefined
  • B: [1, 2, 3, 4]] and { name: "Lydia", age: 21 }
  • C: [1, 2, 3, 4] and { name: "Lydia", age: 21 }
  • D: Error and { name: "Lydia", age: 21 }
The answer

Answer: A,

The getList function takes an array as its argument. Between the parentheses of the getList function, we immediately deconstruct the array. You can think of it as:

[x, ...y] = [1, 2, 3, 4]

Using the remaining parameters… Y, we put all the remaining arguments in an array. In this case, the remaining parameters are 2,3 and 4. The value of y is an array containing all the remaining parameters. In this case, the value of x is 1, so when we print [x, y], we print [1, [2,3,4]].

The getUser function receives an object. For arrow functions, if only one value is returned, we do not need to write curly braces. However, if you want to return an object from an arrow function, you must write it between parentheses or nothing will be returned! The following function returns an object:

const getUser = user => ({ name: user.name, age: user.age })

Since no value is returned in this case, the function returns undefined.


99. Output what?
const name = "Lydia"

console.log(name())
Copy the code
  • A: SyntaxError
  • B: ReferenceError
  • C: TypeError
  • D: undefined
The answer

Answer: C

The variable name holds the value of the string, which is not a function and therefore cannot be called.

TypeErrors is thrown when the value is not of the expected type. JavaScript expects name to be a function because we’re trying to call it. But it is a string, so TypeError is raised: Name is not a function

Syntax errors are thrown when you write JavaScript that is not valid, such as when you write the word return as retrun. Throws ReferenceErrors when JavaScript cannot find a reference to the value you are trying to access.


100. Output what?
// πŸŽ‰βœ¨ This is my 100th question! ✨ πŸŽ‰

const output = `The ${[] &&'Im'}possible!
You shouldThe ${' ' && `n't`} see a therapist after so much JavaScript lol`
Copy the code
  • A: possible! You should see a therapist after so much JavaScript lol
  • B: Impossible! You should see a therapist after so much JavaScript lol
  • C: possible! You shouldn't see a therapist after so much JavaScript lol
  • D: Impossible! You shouldn't see a therapist after so much JavaScript lol
The answer

Answer: B

[] is a true value. Use the && operator to return the right-hand value if the left-hand value is true. In this case, the left-hand value [] is a true value, so Im is returned.

“Is a false value. If the left-hand value is false, nothing is returned. N’t will not be returned.


❀️ Three things after reading: If you found this article inspiring, I’d like to ask you to do me a small favor:

Praise, so that more people can see this content, but also convenient to find their own content at any time (collection does not praise, are playing rogue -_-) pay attention to us, not regular points good article. Look at other articles as well

πŸ‘ You are welcome to write your own learning experience in the comments section, and discuss with me and other students. Feel free to share this article with your friends if you find it rewarding.