Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.


preface

Think about it and see the answer

Question 1

What is the output?

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

sayHi()
Copy the code
  1. Lydia and undefined
  2. Lydia and ReferenceError
  3. ReferenceError and 21
  4. Undefined and ReferenceError
⏳ Click here to find out

Answer: 4

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.

Second question

Which of the following will return ‘6’?

function sumValues(x, y, z) {
	return x + y + z;
}
Copy the code
  1. sumValues([…1, 2, 3])
  2. sumValues([…[1, 2, 3]])
  3. sumValues(… [1, 2, 3])
  4. sumValues([1, 2, 3])
⏳ Click here to find out

Answer: 3

By expanding the operator… , we can suspend a single iterable element. The sumValues function takes three arguments: x, y, and z. . The result of [1, 2, 3] is 1, 2, 3, which is passed to sumValues.

The third question

Which method returns ‘Hello world! ‘?

const myMap = new Map(a)const myFunc = () = > 'greeting'

myMap.set(myFunc, 'Hello world! ')

/ / 1
myMap.get('greeting')
/ / 2
myMap.get(myFunc)
/ / 3
myMap.get(() = > 'greeting')
Copy the code
  1. 1
  2. 2
  3. 2 and 3
  4. All of them
⏳ Click here to find out

Answer: 2

When a key-value pair is added through the set method, one argument passed to the set method will be the key name and the second argument will be the value. In this case, the key name function () => ‘greeting’ and the value is ‘Hello world’. MyMap is now {() => ‘greeting’ => ‘Hello world! ‘}. 1 is wrong because the key name is not ‘greeting’ but () => ‘greeting’. 3 is wrong because we passed a new function to the get method. Objects are affected by references. Functions are also objects, so the two functions are not strictly equivalent, even though they are the same: they have two different memory reference addresses.

Number 4

What is the return value of the setInterval method?

setInterval(() = > console.log('Hi'), 1000)
Copy the code
  1. A unique ID
  2. The number of milliseconds specified by this method
  3. Transitive function
  4. undefined
⏳ Click here to find out

Answer: 1.

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

5

Output what?

let randomValue = { name: "Lydia" }
randomValue = 23

if (!typeof randomValue === "string") {
	console.log("It's not a string!")}else {
	console.log("Yay it's a string!")}Copy the code
  1. It’s not a string!
  2. Yay it’s a string!
  3. TypeError
  4. undefined
⏳ Click here to find out

Answer: 2

If statement conditional judgment! Whether the value of typeof randomValue equals “string”. ! The operator converts the value to a Boolean value. The return value is false if truthy, and true if falsy. In this case, typeof randomValue returns a truthy value of “number”, meaning! The value of typeof randomValue is a Boolean value false. ! Typeof randomValue === “string” always returns false because we are actually executing false === “string”. Because the condition returns false, the code block in the else statement is run, so print Yay it’s a string! .

Number 6

Output what?

const createMember = ({ email, address = {}}) = > {
	const validEmail = /. + \ @ + \.. +/.test(email)
	if(! validEmail)throw new Error("Valid email pls")

	return {
		email,
		address: address ? address : null}}const member = createMember({ email: "[email protected]" })
console.log(member)
Copy the code
  1. { email: “[email protected]”, address: null }
  2. { email: “[email protected]” }
  3. { email: “[email protected]”, address: {} }
  4. { email: “[email protected]”, address: undefined }
⏳ Click here to find out

Answer: 3

The default value of address is an empty object {}. When we set the member variable to the object returned by createMember, we did not pass a value for the address parameter, which means that the value of address is the default empty object {}. An empty object is a truthy value, meaning address? The address: null condition returns true. The value of address is an empty object {}.

Question 7

{name: “Lydia”, age: 22}?

const keys = ["name"."age"]
const values = ["Lydia".22]

const method = / *?? * /
Object[method](keys.map((_, i) = > {
	return [keys[i], values[i]]
})) // { name: "Lydia", age: 22 }
Copy the code
  1. entries
  2. values
  3. fromEntries
  4. forEach
⏳ Click here to find out

Answer: 3

The fromEntries method converts a two-dimensional array into an object. The first element in each subarray is key, and the second element in each subarray is value. In this example, we map the keys array, which returns an array where the first element is the value of the current keys index and the second element is the value of the current keys index. This creates an array of subarrays of the correct keys and values, so the result is {name: “Lydia”, age: 22}.

8 the topic

Output what?

const promise1 = Promise.resolve('First')
const promise2 = Promise.resolve('Second')
const promise3 = Promise.reject('Third')
const promise4 = Promise.resolve('Fourth')

const runPromises = async() = > {const res1 = await Promise.all([promise1, promise2])
	const res2  = await Promise.all([promise3, promise4])
	return [res1, res2]
}

runPromises()
	.then(res= > console.log(res))
	.catch(err= > console.log(err))
Copy the code
  1. [[‘First’, ‘Second’], [‘Fourth’]]
  2. [[‘First’, ‘Second’], [‘Third’, ‘Fourth’]]
  3. [[‘First’, ‘Second’]]
  4. ‘Third’
⏳ Click here to find out

Answer: 4

The promise.all method runs promises in parallel. If one of the promises fails, the promise. all method takes the reject promise value _rejects_. In this example, promise3 takes the value “Third” reject. We call runPromises with the catch method inside the runPromises function to catch any error and thus catch the rejected value. As promise3 is rejected with “Third”, only “Third” prints.

Question 9

Output what?

const user = {
	email: "[email protected]".updateEmail: email= > {
		this.email = email
	}
}

user.updateEmail("[email protected]")
console.log(user.email)
Copy the code
  1. [email protected]
  2. [email protected]
  3. undefined
  4. ReferenceError
⏳ Click here to find out

Answer: 1.

The updateEmail function is an arrow function that is not bound to the User object. This means that the this keyword does not refer to the User object, but to the global object. The email value inside the User object is not updated. When printing user.email, the original value [email protected] is returned.

Question 10

Output what?

const animals = {};
let dog = { emoji: '🐶' }
let cat = { emoji: '🐈'} animals[dog] = { ... dog,name: "Mara"} animals[cat] = { ... cat,name: "Sara" }

console.log(animals[dog])
Copy the code
  1. {emoji: “🐶”, name: “Mara”}
  2. {emoji: “🐈”, name: “Sara”}
  3. undefined
  4. ReferenceError
⏳ Click here to find out

Answer: 2

The key of the object is converted to a string. Because the value of dog is an object, animals[dog] actually means that we create a property called “object object “to represent the new object. Animals [“object object “] is now equal to {emoji: “🐶”, name: “Mara”}. Cat is also an object. Animals [cat] actually means that we are overwriting the value of animals[‘ ‘object’ ‘ ‘] with the new cat property. Prints animals[dog], which is actually animals[“object object “]. This is because the dog object is converted to a string resulting in “object object “, so the return {emoji: “🐈”, name: “Sara”}.

Question 11

Output what?

const fruit = ['🍌'.'🍊'.'🍎']

fruit.slice(0.1)
fruit.splice(0.1)
fruit.unshift('🍇')

console.log(fruit)
Copy the code
  1. [‘ 🍌 ‘, ‘🍊’, ‘🍎]
  2. [‘ 🍊 ‘, ‘🍎]
  3. [‘ 🍇 ‘, ‘🍊’, ‘🍎]
  4. [‘ 🍇 ‘, ‘🍌’, ‘🍊’, ‘🍎]
⏳ Click here to find out

Answer: 3

First, we call the slice method on the Fruit array. The Slice method does not modify the original array, but returns the value sliced from the array: banana emoji. Second, we call the splice method on the Fruit array. The splice method modifies the original array, meaning that the fruit array is now [‘🍊’, ‘🍎’]. Finally, we call the unshift method on the Fruit array and change the original array by adding a value, ‘🍇’, which becomes the first element of the array. The fruit array now consists of [‘🍇’, ‘🍊’, ‘🍎’].

Number 12

Output what?

const user = {
	email: "[email protected]".password: "12345"
}

const updateUser = ({ email, password }) = > {
	if (email) {
		Object.assign(user, { email })
	}

	if (password) {
		user.password = password
	}

	return user
}

const updatedUser = updateUser({ email: "[email protected]" })

console.log(updatedUser === user)
Copy the code
  1. false
  2. true
  3. TypeError
  4. ReferenceError
⏳ Click here to find out

Answer: 2

The updateUser function updates the value of the email and password attributes of user. If their values are passed to the function, the function returns the User object. The return value of the updateUser function is a User object, meaning that the value of updatedUser and user point to the same user object. UpdatedUser === user is true.

13 questions

Output what?

class Calc {
	constructor() {
		this.count = 0 
	}

	increase() {
		this.count ++
	}
}

const calc = new Calc()
new Calc().increase()

console.log(calc.count)
Copy the code
  1. 0
  2. 1
  3. undefined
  4. ReferenceError
⏳ Click here to find out

Answer: 1.

We set the calc variable to a new instance of the calc class. We then initialize a new instance of Calc and call its increase method. Because the count attribute is inside Calc class constructor, the count attribute is not shared across Calc’s prototype chain. This means that the count value of the calc instance will not be updated; count will still be 0.

Question 14

What is the output?

function getFruit(fruits) {
	console.log(fruits? .1]? .1])
}

getFruit([['🍊'.'🍌'], ['🍍']])
getFruit()
getFruit([['🍍'], ['🍊'.'🍌']])
Copy the code
  1. 🍌, null, and undefined
  2. [], null, 🍌
  3. [], [], 🍌
  4. Undefined undefined, 🍌
⏳ Click here to find out

Answer: 4

? Allows us to selectively access deeper nested properties within an object. We try to print the element with index 1 in the fruit subarray whose index is 1. If there is no element in the fruits array whose index is 1, undefined is returned. If the fruits array has an element at index 1, but the subarray has no element at index 1, undefined is returned. First, we try to print the [[‘ 🍊 ‘, ‘🍌], [‘ 🍍]] of subarray [‘ 🍍] second element. This subarray contains only one element, which means that there is no element at index 1, so undefined is returned. Second, we call getFruits without passing in any parameters, which means that the default value of the parameter fruits is undefined. Because we have selectively linked fruits to the element with index value 1, because there is no element at index value 1, undefined is returned. Finally, we try to print [‘ 🍍], [‘ 🍊 ‘, ‘🍌] subarray [‘ 🍊’, ‘🍌] second element. The position where the subarray index is 1 is 🍌, so it is printed out.

Question 15

Output what?

let count = 0;
const nums = [0.1.2.3];

nums.forEach(num= > {
	if (num) count += 1
})

console.log(count)
Copy the code
  1. 1
  2. 2
  3. 3
  4. 4
⏳ Click here to find out

Answer: 3

The if inside the forEach loop determines whether num is truthy or falsy. Because the first numS number is 0, a Falsy value, the if statement code block is not executed. Count simply increments 1 when the other three digits in the NUMS array are 1, 2, and 3. Because count does three increments, it has a value of 3.

Number 16

When adding something to the object person, you can get something like [“Lydia Hallie”, 21] by executing […person]?

const person = {
  name: "Lydia Hallie".age: 21
}

[...person] // ["Lydia Hallie", 21]
Copy the code
  1. No, objects are iterable by default
  2. Symbol.iterator { for (let x in this) yield this[x] }
  3. Symbol.iterator { for (let x in this) yield Object.values(this) }
  4. *Symbol.iterator { for (let x in this) yield this }
⏳ Click here to find out

Answer: 3

Objects are not iterable by default. An object is iterable (An iterable is An iterable if the iterator protocol is present) if the iteration rule is defined. Iterator rules can be defined by adding the iterator symbol [symbol.iterator], which returns a generator object, such as building a generator function *[symbol.iterator]() {}. If we want to return the array [“Lydia Hallie”, 21]: yield* object. values(this), the generator function must yield the Object.

Question 17

Which option causes an error?

const emojis = ["🎄"."🎅 🏼"."🎁"."⭐"];

/ * 1 * / emojis.push("🦌");
/ * 2 * / emojis.splice(0.2);
/ * * / 3 emojis = [...emojis, "🥂"];
/ * * / 4 emojis.length = 0;
Copy the code
  1. 1
  2. 1 and 2
  3. 3 and 4
  4. 3
⏳ Click here to find out

Answer: 4

The const keyword means that we cannot redefine a value in a variable; it is only readable. However, the value itself cannot be modified. Values in the emojis array can be modified, such as pushing new values, concatenating, or setting the array length to 0.

18 the topic

Output what?

class Bird {
	constructor() {
		console.log("I 'm a bird. 🦢"); }}class Flamingo extends Bird {
	constructor() {
		console.log("I'm pink. 🌸");
		super();
	}
}

const pet = new Flamingo();
Copy the code
  1. I ‘m pink. 🌸
  2. I’m pink. 🌸 I’m a bird. 🦢
  3. I’m a bird. 🦢 I’m pink. 🌸
  4. Nothing, we didn’t call any method
⏳ Click here to find out

Answer: 2

We created an instance of the class Flamingo, PET. Flamingo constructor is called when we instantiate this instance. Prime Minister, print “I’m pink. 🌸”, and then we call super(). Super () calls the parent class’s constructor, Bird. Bird’s constructor is called and prints “I’m a bird.🦢 “.

Article 19 the topic

Output what?

const person = {
	name: "Lydia Hallie".hobbies: ["coding"]};function addHobby(hobby, hobbies = person.hobbies) {
	hobbies.push(hobby);
	return hobbies;
}

addHobby("running"[]); addHobby("dancing");
addHobby("baking", person.hobbies);

console.log(person.hobbies);
Copy the code
  1. [“coding”]
  2. [“coding”, “dancing”]
  3. [“coding”, “dancing”, “baking”]
  4. [“coding”, “running”, “dancing”, “baking”]
⏳ Click here to find out

Answer: 3

The addHobby function takes two arguments, Hobby and hobbies with a default value for the array hobbies in the person object. Prime Minister, we call addHobby and pass “running” to Hobby and an empty array to hobbies. Since we passed the empty array to hobbies, “running” was added to the empty array. We then call the function addHobby and pass “dancing” to Hobby. We don’t pass values to hobbies, so it gets its default value — the property hobbies of the object Person. We push dancing to the array Person.hobbies. Finally, we call the function addHobby, passing the value “bdaking” to Hobby, and passing Person.hobbies to hobbies. We push dancing to the array Person.hobbies. After pushing dancing and baking, person. Hobbies = [“coding”, “dancing”, “baking”]

Question 20

Which one to choose?

const teams = [
	{ name: "Team 1".members: ["Paul"."Lisa"] {},name: "Team 2".members: ["Laura"."Tim"]}];function* getMembers(members) {
	for (let i = 0; i < members.length; i++) {
		yieldmembers[i]; }}function* getTeams(teams) {
	for (let i = 0; i < teams.length; i++) {
		// ✨ SOMETHING IS MISSING HERE ✨}}const obj = getTeams(teams);
obj.next(); // { value: "Paul", done: false }
obj.next(); // { value: "Lisa", done: false }
Copy the code
  1. yield getMembers(teams[i].members)
  2. yield* getMembers(teams[i].members)
  3. return getMembers(teams[i].members)
  4. return yield getMembers(teams[i].members)
⏳ Click here to find out

Answer: 2

To iterate over each item in the attribute members of the Objects in the Teams array, we need to pass teams[I].members to the Generator function getMembers. The Generator function returns a Generator object. To iterate over each item in the Generator object, we need to use yield*. If we do not write yield, return yield, or return, the whole Generator will not return the first time we call the next method.

Question 21

Output what?

class Counter {
  #number = 10

  increment() {
    this.#number++
  }

  getNum() {
    return this.#number
  }
}

const counter = new Counter()
counter.increment()

console.log(counter.#number)
Copy the code
  1. 10
  2. 11
  3. undefined
  4. SyntaxError
⏳ Click here to find out

Answer: 4

In ES2020, we can add private variables to class with #. We can’t get this value outside of class. When we try to print counter.#number, a syntax error is thrown: we can’t get it outside of class counter!

Question 22

Output what?

const add = x= > x + x;

function myFunc(num = 2, value = add(num)) {
	console.log(num, value);
}

myFunc();
myFunc(3);
Copy the code
  1. 2 4 and 3 6
  2. 2 NaN and 3 NaN
  3. 2 Error and 3 6
  4. 2 4 and 3 Error
⏳ Click here to find out

Answer: 1.

First we call myFunc() without passing any arguments. Since we are not passing arguments, num and value get their respective defaults: num is 2, and value is the return value of add. For the function add, we pass num with a value of 2 as an argument. The function add returns 4 as the value of value. We then call myFunc(3) and pass in the value of the 3 argument num. We’re not passing a value to value. Since we are not passing a value to the parameter value, it takes the default value: the return value of the function add. For the function add, we pass num with a value of 3. The function add returns 6 as value.

Question 23

Which of the following will apply to the objectpersonSide effects?

const person = {
	name: "Lydia Hallie".address: {
		street: "100 Main St"}};Object.freeze(person);
Copy the code
  1. person.name = “Evan Bacon”
  2. delete person.address
  3. person.address.street = “101 Main St”
  4. person.pet = { name: “Mara” }
⏳ Click here to find out

Answer: 3

Freeze An Object using the object. freeze method. Attributes cannot be added, modified, or deleted. However, it only shallow freezes the object, meaning that only the immediate properties in the object are frozen. If the property is another object, as in the case of Address, the property in address is not frozen and can still be modified.

Question 24

Which of the following will apply to the objectpersonSide effects?

const person = { name: "Lydia Hallie" };

Object.seal(person);
Copy the code
  1. person.name = “Evan Bacon”
  2. person.age = 21
  3. delete person.name
  4. Object.assign(person, { age: 21 })
⏳ Click here to find out

Answer: 1.

Using Object.seal, we can prevent new attributes from being added or existing attributes from being removed. However, you can still make changes to existing properties.

Question 25

Output what?

const handler = {
	set: () = > console.log("Added a new property!"),
	get: () = > console.log("Accessed a property!")};const person = new Proxy({}, handler);

person.name = "Lydia";
person.name;
Copy the code
  1. Added a new property!
  2. Accessed a property!
  3. Added a new property! Accessed a property!
  4. There is no output
⏳ Click here to find out

Answer: 3

Using Proxy objects, we can add custom behavior to an object. In this case, we pass an object handler with the following properties: set and get. Set is called whenever we set the property value and GET is called whenever we get it. The first argument is an empty object {} as the value of person. For this object, the custom behavior is defined in the object handler. If we add attributes to the object Person, set will be called. If we get the property of Person, get will be called. First, we add an attribute name to the proxy object (person.name = “Lydia”). Set is called and prints “Added a new property!” . Then, we get a property of the Proxy object, and the object handler property GET is called. Email exchange with a property! .

Question 26

How can I call the sum method in sum.js from index.js?

// sum.js
export default function sum(x) {
	return x + x;
}

// index.js
import * as sum from "./sum";
Copy the code
  1. sum(4)
  2. sum.sum(4)
  3. sum.default(4)
  4. The default export does not use * to import, only named export
⏳ Click here to find out

Answer: 3

Using the symbol *, we introduce all values in the file, including default and named. If we have the following files:

// info.js
export const name = "Lydia";
export const age = 21;
export default "I love JavaScript";
// index.js
import * as info from "./info";
console.log(info);
Copy the code

The following will be printed:

{
  default: "I love JavaScript".name: "Lydia".age: 21
}
Copy the code

Taking sum as an example, it is equivalent to introducing the value sum in the following form:

{ default: function sum(x) { return x + x } }
Copy the code

We can call this function by calling sum.default

Question 27

Output what?

const myPromise = Promise.resolve(Promise.resolve("Promise!"));

function funcOne() {
	myPromise.then(res= > res).then(res= > console.log(res));
	setTimeout(() = > console.log("Timeout!"), 0);
	console.log("Last line!");
}

async function funcTwo() {
	const res = await myPromise;
	console.log(await res);
	setTimeout(() = > console.log("Timeout!"), 0);
	console.log("Last line!");
}

funcOne();
funcTwo();
Copy the code
  1. Promise! Last line! Promise! Last line! Last line! Promise!
  2. Last line! Timeout! Promise! Last line! Timeout! Promise!
  3. Promise! Last line! Last line! Promise! Timeout! Timeout!
  4. Last line! Promise! Promise! Last line! Timeout! Timeout!
⏳ Click here to find out

Answer: 4

First, we call funcOne. On the first line of the funcOne function, we call myPromise the Promise asynchronous operation. While the JS engine is busy executing the promise, it continues to execute the function funcOne. The next line of asynchronous operation setTimeout, whose callback function is called by the Web API. (See my event Loop article for details.) Both Promise and timeout are asynchronous operations, and the function continues to execute while the JS engine is busy executing promises and handling setTimeout callbacks. Equivalent to Last line! Is printed first because it is not an asynchronous operation. After executing the last line of funcOne, the Promise state changes to Resolved, Promise! Be printed. However, because funcTwo() is called, the call stack is not empty and the setTimeout callback still cannot be pushed. We are now in funcTwo, awaiting myPromise. With the await keyword, we suspend execution of the function until the Promise state changes to Resolved (or Rejected). Then, we print the VALUE of the RES’s commit (because the promise itself returns a promise). Then print Promise! . The next line is the asynchronous operation setTimeout, whose callback function is called by the Web API. We go to the Last line of function funcTwo and print Last line! . Now, because funcTwo is off the stack, the call stack is empty. The callback function waiting in the event queue (() => console.log(“Timeout!”) ) from funcOne, and () => console.log(“Timeout!” (from funcTwo). The first callback prints Timeout! And out of the stack. The second callback then prints Timeout! And out of the stack. Get the result Last line! Promise! Promise! Last line! Timeout! Timeout!

Question 28

Output what?

class Counter {
	constructor() {
		this.count = 0;
	}

	increment() {
		this.count++; }}const counterOne = new Counter();
counterOne.increment();
counterOne.increment();

const counterTwo = counterOne;
counterTwo.increment();

console.log(counterOne.count);
Copy the code
  1. 0
  2. 1
  3. 2
  4. 3
⏳ Click here to find out

Answer: 4

counterOneIs the classCounterAn instance of. The class Counter contains onecountProperty in its constructor, and aincrementMethods. First, we passcounterOne.increment()A method is calledincrementTwice a day. Now,counterOne.count2. Then, we create a new variablecounterTwoAnd will becounterOneAssigns the reference address to it. Because objects are affected by reference addresses, we have just created a new object with reference addresses andcounterOneThe equivalence. So they point to the same memory address, and any side effects to it will affect itcounterTwo. nowcounterTwo.count2. We callcounterTwo.increment()countThe value of the set3. Then, we printcounterOneCount in, and the result is zero3.

Question 29

Output what?

const emojis = ["🥑"["✨"."✨"["🍕"."🍕"]]];

console.log(emojis.flat(1));
Copy the code
  1. [‘🥑’, [‘✨’, ‘✨’, [‘🍕’, ‘✨’]]]
  2. [‘🥑’, ‘✨’, ‘✨’, [‘🍕’, ‘✨’]]
  3. [‘🥑’, [‘✨’, ‘✨’, ‘🍕’, ‘✨’]
  4. [‘🥑’, ‘✨’, ‘✨’, ‘🍕’, ‘✨’]
⏳ Click here to find out

Answer: 2

With the flat method, we can create a new array that has been flattened. The depth of flattening depends on the values we pass. In this case, we pass the value 1 (not necessary, which is the default), which means that only the first-level array will be joined. In this case [‘🥑’] and [‘✨’, ‘✨’, [‘🍕’, ‘✨’]]. Concatenating the two arrays yields the result [‘🥑’, ‘✨’, ‘✨’, [‘🍕’, ‘✨’]].

30 questions

Output what?

const myPromise = Promise.resolve("Woah some cool data");

(async() = > {try {
		console.log(await myPromise);
	} catch {
		throw new Error(`Oops didn't work`);
	} finally {
		console.log("Oh finally!");
	}
})();
Copy the code
  1. Woah some cool data
  2. Oh finally!
  3. Woah some cool data Oh finally!
  4. Oops didn’t work Oh finally!
⏳ Click here to find out

Answer: 3

In the try block, we print the undefined value of the myPromise variable: “Woah some cool data”. Because no errors are thrown in the try block, the code in the catch block does not execute. Finally block code always executes, “Oh finally!” Is the output.

Question 31

Output what?

const randomValue = 21;

function getInfo() {
	console.log(typeof randomValue);
	const randomValue = "Lydia Hallie";
}

getInfo();
Copy the code
  1. “number”
  2. “string”
  3. undefined
  4. ReferenceError
⏳ Click here to find out

Answer: 4

Variables declared with the const keyword cannot be referenced until they are initialized: this is called a temporary dead zone. In the function getInfo, the variable randomValue is declared in the method context of getInfo’s scope. The variable randomValue is still uninitialized before you want to log typeof randomValue: ReferenceError is thrown! The JS engine does not look for the variable in the scope chain because we have declared the randomValue variable in the getInfo function.

Question 32

Output what?

const name = "Lydia Hallie";
const age = 21;

console.log(Number.isNaN(name));
console.log(Number.isNaN(age));

console.log(isNaN(name));
console.log(isNaN(age));
Copy the code
  1. true false true false
  2. true false false false
  3. false false true false
  4. false true false true
⏳ Click here to find out

Answer: 3

With the number. isNaN method, you can detect whether the value you pass is numeric and equivalent to NaN. Name is not a numeric value, so number.isnan (name) returns false. Age is a numeric value, but it is not equivalent to NaN, so number.isnan (age) returns false. With the isNaN method, you can check if the value you pass is a number. Name is not a number, so isNaN(name) returns true. Age is a number, so isNaN(age) returns false.

Question 33

Output what?

const spookyItems = ["👻"."🎃"."🕸"];
({ item: spookyItems[3]} = {item: "💀" });

console.log(spookyItems);
Copy the code
  1. [” 👻 🎃 “, “”,” 🕸 “]
  2. [” 👻 🎃 “, “”,” 🕸 “, “💀”]
  3. [“👻”, “🎃”, “🕸”, {item: “💀”}]
  4. [“👻”, “🎃”, “🕸”, “[object Object]”]
⏳ Click here to find out

Answer: 2

By deconstructing the objects, we can split the values from the right-hand object and assign the detached values to the attributes of the left-hand object with the same name. In this case, we assign the value “💀” to spookyItems[3]. So we’re tampering with the array spookyItems and we’re adding the value “💀” to it. When spookyItems is output, the result is [“👻”, “🎃”, “🕸”, “💀”].

34 the topic

Output what?

function getFine(speed, amount) {
  const formattedSpeed = new Intl.NumberFormat({
    'en-US',
    { style: 'unit'.unit: 'mile-per-hour' }
  }).format(speed)

  const formattedAmount = new Intl.NumberFormat({
    'en-US',
    { style: 'currency'.currency: 'USD' }
  }).format(amount)

  return `The driver drove ${formattedSpeed} and has to pay ${formattedAmount}`
}

console.log(getFine(130.300))
Copy the code
  1. The driver drove 130 and has to pay 300
  2. The driver drove 130 mph and has to pay $300.00
  3. The driver drove undefined and has to pay undefined
  4. The driver drove 130.00 and has to pay 300.00
⏳ Click here to find out

Answer: 2

With the Intl.NumberFormat method, we can format numeric values for any region. We formatted the en-US field for the mile-per-hour unit of the number 130, and the result was 130 MPH. Formatting the numeric value 300 for USD as the EN-US field of CurrentCY results in $300.00.

Question 35

Output what?

const myFunc = ({ x, y, z }) = > {
	console.log(x, y, z);
};

myFunc(1.2.3);
Copy the code
  1. 1 2 3
  2. {1: 1} {2: 2} {3: 3}
  3. { 1: undefined } undefined undefined
  4. undefined undefined undefined
⏳ Click here to find out

Answer: 4

MyFunc expects to receive an object with attributes x, y, and z as its arguments. Because we are passing only three separate numeric values (1, 2, 3) rather than an object with attributes x, y, and z ({x: 1, y: 2, z: 3}), x, y, and z have their respective default values undefined.

36 the topic

Output what?

async function* range(start, end) {
	for (let i = start; i <= end; i++) {
		yield Promise.resolve(i); }} (async() = > {const gen = range(1.3);
	for await (const item of gen) {
		console.log(item);
	}
})();
Copy the code
  1. Promise {1} Promise {2} Promise {3}
  2. Promise {} Promise {} Promise {}
  3. 1 2 3
  4. undefined undefined undefined
⏳ Click here to find out

Answer: 3

We pass the function range: Promise{1}, Promise{2}, Promise{3}, Generator range returns an array full of Async Object Promise. We assign async Object to the variable gen, and then we use for await… Of loops through. We assign the returned Promise instances to item: the first returns Promise{1}, the second returns Promise{2}, and then Promise{3}. Because we’re awaiting the value of the item, the promsie in the resolved state, and the resolved value of the promise array are as follows: 1,2,3.

Question 37

Output what?

const add = x= > y= > z= > {
	console.log(x, y, z);
	return x + y + z;
};

add(4) (5) (6);
Copy the code
  1. 4 5 6
  2. 4 5 6
  3. 4 function function
  4. undefined undefined 6
⏳ Click here to find out

Answer: 1.

The function add is an arrow function that returns the arrow function of the return arrow function (still with me?). . The first function takes an argument x with a value of 4. We call the second function, which takes an argument y with a value of 5. Then we call the third function, which takes an argument z with a value of 6. When we try to get the values of x, y, and z in the last arrow function, the JS engine finds the values of x and y according to the scope chain. You get 4, 5, 6.

Question 38

Output what?

const name = "Lydia Hallie";

console.log(!typeof name === "object");
console.log(!typeof name === "string");
Copy the code
  1. false true
  2. true false
  3. false false
  4. true true
⏳ Click here to find out

Answer: 3

Typeof Name Returns “string”. The string” string” is a truthy value, therefore! Typeof Name returns a Boolean value false. False === “object” and false === “string” both return false. If we want to detect the type of a value, we should use! == instead of! Typeof)

Question 39

Output what?

const config = {
	languages: [].set language(lang) {
		return this.languages.push(lang); }};console.log(config.language);
Copy the code
  1. function language(lang) { this.languages.push(lang }
  2. 0
  3. []
  4. undefined
⏳ Click here to find out

Answer: 4

The method language is a setter. Setters do not hold an actual value; their job is to modify properties. When a setter is called, undefined is returned.

40 questions

Output what?

const groceries = ["banana"."apple"."peanuts"];

if (groceries.indexOf("banana")) {
	console.log("We have to buy bananas!");
} else {
	console.log(`We don't have to buy bananas! `);
}
Copy the code
  1. We have to buy bananas!
  2. We don’t have to buy bananas
  3. undefined
  4. 1
⏳ Click here to find out

Answer: 2

We pass a state on Saturday. IndexOf (“banana”) to the if condition. IndexOf (“banana”) returns 0, a value of falsy. Because the state of the if conditional statement is falsy, the else block executes, and We don’t have to buy bananas! Is the output.

Topic 41

Output what?

const person = {
	firstName: "Lydia".lastName: "Hallie".pet: {
		name: "Mara".breed: "Dutch Tulip Hound"
	},
	getFullName() {
		return `The ${this.firstName} The ${this.lastName}`; }};console.log(person.pet? .name);console.log(person.pet? .family? .name);console.log(person.getFullName? . ());console.log(member.getLastName? . ());Copy the code
  1. undefined undefined undefined undefined
  2. Mara undefined Lydia Hallie undefined
  3. Mara null Lydia Hallie null
  4. null ReferenceError null ReferenceError
⏳ Click here to find out

Answer: 2

Via ES10 or TS3.7+ optional chain operator? ., we no longer need to explicitly test whether deeper nested values are valid. If we try to get the value of undefined or null (nullish), the expression will short-circuit and return undefined. Person.pet? .name: person has a property named pet: Person. pet is not nullish. It has an attribute named name and returns the string Mara. person.pet? .family? .name: Person has a property named pet: Person. pet is not nullish. Pet does not have a property named family, person.pet.family is nullish. The expression returns undefined. person.getFullName? .() : Person has a property called getFullName: Person.getFullName () is not nullish and can be called, returning the string Lydia Hallie. member.getLastName? .(): member is not defined: member.getLastName() is nullish. The expression returns undefined.

Question 42

Output what?

let num = 1;
const list = ["🥳"."🤠"."🥰"."🤪"];

console.log(list[(num += 1)]);
Copy the code
  1. 🤠
  2. 🥰
  3. SyntaxError
  4. ReferenceError
⏳ Click here to find out

Answer: 2

We increment the value num by 1 with the += operator. Num has an initial value of 1, so the result of 1 + 1 is 2. The second entry of list is 🥰, console.log(list[2]) prints 🥰.

43 the topic

Output what?

const person = {
  name: "Lydia".age: 21
}

const changeAge = (x = { ... person }) = > x.age += 1
const changeAgeAndName = (x = { ... person }) = > {
  x.age += 1
  x.name = "Sarah"
}

changeAge(person)
changeAgeAndName()

console.log(person)
Copy the code
  1. {name: “Sarah”, age: 22}
  2. {name: “Sarah”, age: 23}
  3. {name: “Lydia”, age: 22}
  4. {name: “Lydia”, age: 23}
⏳ Click here to find out

Answer: 3

The changeAge and changeAgeAndName functions take different parameters and define a newly generated object {… The person}. This object has copies of all the K/V values in the Person object. First, we call the changeAge function and pass the Person object as its argument. This function increments the age attribute. Person is now {name: “Lydia”, age: 22}. Then, we call the function changeAgeAndName, but we pass no arguments. Instead, the value of x is equivalent to the object new generates: {… The person}. Because it is a newly generated object, it does not cause any side effects on the Object Person. Person is still equivalent to {name: “Lydia”, age: 22}.

Question 44

What will happen?

let config = {
  alert: setInterval(() = > {
    console.log('Alert! ')},1000)
}

config = null
Copy the code
  1. SetInterval’s callback will not be called
  2. The setInterval callback is called once
  3. SetInterval’s callback will still be called every second
  4. We never called config.alert(), config is null
⏳ Click here to find out

Answer: 3

In general, when objects are assigned a value of NULL, they are garbage collected because there are no more references to them. However, the argument to setInterval is an arrow function (so the context is bound to the object config), and the callback function still retains a reference to config. As long as there is a reference, the object is not garbage collected. Because it is not garbage collected, the setInterval callback is called every 1000ms (1s).

Question 45

Output what?

console.log(`${(x => x)('I love')} to program`)
Copy the code
  1. I love to program
  2. undefined to program
  3. ${(x => x)(‘I love’) to program
  4. TypeError
⏳ Click here to find out

Answer: 1.

Expressions with template literals are executed first. Equivalent to the string containing the expression, the immediate function (x => x)(‘I love’) returns the value. We pass ‘I love’ as an argument to the arrow function x => x. X is equivalent to returning ‘I love’. This is the result I love to program.

conclusion

This article comes from an experiment… I also want to verify something