Câu hỏi phỏng vấn Javascript
Câu hỏi

What's the difference between using let and var to declare a variable in ES6?

Câu trả lời

In ES6 (ECMAScript 2015), both let and var are used for variable declaration in JavaScript, but they differ significantly in terms of scope, hoisting, and redeclaration.

Scope

  • var: The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you declare a variable with var inside a function, it is function-scoped, meaning it is available and can be accessed anywhere within that function, even if declared inside a block (e.g., within an if statement or a loop).
  • let: In contrast, let provides block scoping. Variables declared with let are only accessible within the block in which they are declared and any contained sub-blocks. This makes let useful for control structures like loops, where the variable is only needed for the duration of that loop and prevents its value from being accessed outside of that context[1][2][3][4][6].

Hoisting

  • var: Variables declared with var are hoisted to the top of their function or global context, but not initialized, which means they exist throughout the function but their values are not accessible until they have been declared. If you try to access a var-declared variable before its declaration, the result will be undefined.
  • let: Variables declared with let are also hoisted to the top of the block in which they are defined, but they are not initialized. Accessing a let variable before its declaration results in a ReferenceError, because JavaScript recognizes that the variable exists but won't allow it to be accessed until the declaration is evaluated at...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

junior

What does use strict do?

expert

In JavaScript, why is the this operator inconsistent?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào