Hoisting Flashcards

1
Q

What is hoisting?

A

It means that variable and function declarations are moved to the top of their scope. This allows you to use them before you actually write them in your code.

Variable declaration:

const x = 10

Function declaration: (they are hoisted)

function greet() { console.log("Hello, world!"); }

So, even if you write a variable or a function later in your code, JavaScript acts as if you wrote it at the beginning.

However, only the declarations are moved, not the assignments or values. Remember to still declare your variables and functions before using them to avoid any confusion or errors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the difference between variable hoisting and function hoisting?

A

Variables are initialized with the value undefined when they are hoisted

Functions are hoisted with their full definition.

This means that you can call a function before it is actually defined in the code, but you cannot use a variable before it is initialized.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the scope chain?

A

It’s a mechanism that determines the accessibility of variables and functions in nested functions.

When a function is called, JavaScript looks for variables and functions in the current function’s scope first, and then in the outer function’s scope, and so on, until it reaches the global scope.

This allows nested functions to access variables and functions in their parent functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the difference between var, let, and const with respect to hoisting?

A

var declarations are hoisted to the top of their scope and initialized with the value undefined
let and const declarations are not hoisted and cannot be accessed before they are declared.

Additionally, let and const declarations have block scope, while var declarations have function scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the best practices for avoiding hoisting-related issues?

A

Use strict mode, declaring variables at the top of their scope, avoiding var in favor of let and const, and using function expressions instead of function declarations when possible.

Additionally, it’s a good idea to follow a consistent coding style and to test your code thoroughly to catch any hoisting-related bugs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is hoisting?

A

the process of moving variable and function declarations to the top of their respective scopes

Example 1: Variable Hoisting
console.log(x); // Output: undefined
var x = 5;

Example 2: Function Hoisting
hello(); // Output: “Hello!”
function hello() {
console.log(“Hello!”);
}

Example 3: Function Expression Hoisting
hello(); // Error: hello is not a function
var hello = function() {
console.log(“Hello!”);
};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly