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

senior

Can you describe the main difference between a .forEach loop and a .map() loop and why you would pick one versus the other?

middle

What is the difference between Anonymous and Named functions?

middle

Explain the differences on the usage of foo between function foo() {} and var
foo = function() {}

Bình luận

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

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