Toolsnip

What is the difference between 'var', 'let', and 'const' in JavaScript?

Javascript Interview Questions and Answers

Short Answer

'var', 'let', and 'const' are used to declare variables in JavaScript, but they have some key differences.

Detailed Answer

'var' is function-scoped, which means that it is only available within the function in which it is declared, or globally if declared outside a function.

'let' and 'const' are block-scoped, which means that they are only available within the block in which they are declared, such as a loop or an if statement.

'var' allows variables to be redeclared within the same function or block, while 'let' and 'const' do not allow redeclaration.

'var' variables are hoisted to the top of their function or global scope, while 'let' and 'const' are not hoisted.

'let' variables can be reassigned to a new value, while 'const' variables cannot be reassigned once they have been initialized.

'const' variables must be initialized with a value when they are declared, while 'var' and 'let' variables can be declared without an initial value.

Overall, 'let' and 'const' are preferred over 'var' for declaring variables in modern JavaScript code due to their block scoping and immutability.