Share 10 common JavaScript interview questions

8d7c2f0f2f2794f4000156236c0517d0.jpeg

English | https://medium.com/@maria_laramie/10-common-javascript-interview-questions-and-how-to-answer-them-328b59806cf7

Are you preparing for your JavaScript interview? If so, you must not miss this article today, because I will share 10 common JavaScript interview questions and how to refer to the answers in the article to help you get a good score in the interview.

Now, let's get started.

1. What is Hoisting in JavaScript ?

Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their scope. This means that variables and functions can be used in the code before they are declared. However, it will only be declared, not assigned.

console.log(x); //undefined
var x = 5;

In this example, the variable x is hoisted to the top of the scope, but its assignment 5 is not, so when we try to record the value of x, it returns undefined.

2. What are closures in JavaScript?

A closure is a function that can access variables in its outer scope even after the outer function returns.

function outerFunction(x) {
  return function innerFunction() {
    return x;
  }
}


const myClosure = outerFunction(10);
console.log(myClosure()); //10

In this example, the inner function innerFunction can access the variable x from its outer scope, so it can return its value even after outerFunction returns.

3. Explain event bubbling and capture in JavaScript

Event bubbling and capturing are two ways of propagating events in the DOM.

Event bubbling means that the event is first captured and processed by the innermost element, and then propagated to the outer element.

Event capture is the opposite, the event is first handled by the outermost element and then propagated to the inner elements.

<div onclick="alert('div')">
  <p onclick="alert('p')">
    Click me!
  </p>
</div>

In this example, if the p element is clicked, the event will first be caught by the p element and the alert('p') function will be called.

The event will then propagate to the div element and call the alert('div') function. This is an example of event bubbling.

If we use the useCapture parameter in addEventListener and set it to true, the event will first be captured by the div element and then propagated to the p element. This is an example of event capture.

4. Interpreting "this" in JavaScript

In JavaScript, this refers to the object of which the function is a method.

const person = {
  name: "John",
  sayName: function() {
    console.log(this.name);
  }
}


person.sayName(); // "John"

In this example, this refers to the person object, so calling this.name returns "John". The value of this can change depending on how the function is called.

5. Explain how prototypal inheritance works in JavaScript 

In JavaScript, all objects have a prototype from which they inherit properties and methods. When a property or method is called on an object and cannot be found on that object, JavaScript looks for it on the object's prototype.

const animal = {
  type: "unknown"
}


const dog = Object.create(animal);
dog.breed = "Golden Retriever";


console.log(dog.type); // "unknown"
console.log(dog.breed); // "Golden Retriever"

In this example, the dog object is created using Object.create(), which sets the animal object as its prototype. When we try to access the type property of the dog object, it is not found on the dog object itself, so JavaScript looks for it on the prototype and finds it on the animal object.

6. Explain how setTimeout works in JavaScript

setTimeout is a function that allows you to execute a function after a certain amount of time has elapsed.

console.log("Started!");
setTimeout(() => {
  console.log("Hello!");
}, 2000);
console.log("Ended!");

In this example, console.log("Started!") is called immediately, then setTimeout is called, and the callback function logs "Hello!" and a time of 2000 milliseconds. Call console.log("Ended!") immediately afterwards. The callback function passed to setTimeout will be called after 2 seconds.

7. Explain how setInterval works in JavaScript

setInterval is like setTimeout, but it repeats the provided function at the specified interval.

let count = 0;
const intervalId = setInterval(() => {
  console.log(`Interval count: ${count}`);
  count++;
  if (count === 5) {
    clearInterval(intervalId);
  }
}, 1000);

In this example, the provided function will be executed every 1000 milliseconds (1 second), incrementing the count by 1 each time. The clearInterval function is used to stop the interval after 5 iterations.

8. Explain what promises are in JavaScript 

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its result value.

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Success!");
  }, 2000);
});


promise
  .then(result => console.log(result))
  .catch(error => console.log(error));

In this example, a promise is created using the setTimeout function that calls the resolve function after 2 seconds. The promise has two methods, then and catch, that can be used to handle the resolved value or any errors that occur.

9. Explain the difference between == and === in JavaScript

== (loose equality) compares two values ​​for equality after performing any necessary type conversions. === (strict equality) compares two values ​​for equality without performing any type conversions.

console.log(0 == false); // true
console.log(0 === false); // false

In this example, 0 and false are roughly equal because they are both false values, but they are not strictly equal because 0 is a number and false is a Boolean value.

Using === for comparisons in JavaScript is generally recommended because it helps prevent accidental type casts.

10. Explain the difference between let, var, and const in JavaScript

let and var are used to declare variables in JavaScript, but they behave slightly differently. let variables are block-scoped, which means they can only be accessed within the block in which they are declared.

var variables are function-scoped, which means they can be accessed within the entire function in which they are declared.

if (true) {
  let x = 5;
}
console.log(x); // ReferenceError: x is not definedCopy code
if (true) {
  var x = 5;
}
console.log(x); // 5

const is used to declare a constant variable, which means its value cannot be reassigned after declaration.

const x = 5;
x = 10; // TypeError: Assignment to constant variable

In general, it's best practice to default to const and only use let when you need to reassign the variable.

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/131447428