What is a difference between var and let in JavaScript?
Experience Level: Junior
Tags: JavaScript
Answer
In JavaScript, var
and let
are both used for declaring variables, but they have some differences:
- Scope: Variables declared with
var
are function-scoped, whereas variables declared withlet
are block-scoped. - Hoisting: Variables declared with
var
are hoisted to the top of their scope and initialized with a value ofundefined
. - Reassignment: Both
var
andlet
variables can be reassigned a new value.
Here's an example to illustrate the difference between var
and let
:
function myFunction() { var x = 1; if (true) { var x = 2; // same variable as above console.log(x); // Output: 2 } console.log(x); // Output: 2 } function myOtherFunction() { let y = 1; if (true) { let y = 2; // different variable than above console.log(y); // Output: 2 } console.log(y); // Output: 1 }
Related JavaScript job interview questions
What types of loops exist in JavaScript?
JavaScript JuniorWhat are the ES6+ features you use?
JavaScript JuniorWhat is an event loop in JavaScript?
JavaScript JuniorHow are the 'async' and 'await' keywords used in JavaScript?
JavaScript JuniorWhat is 'this' keyword in JavaScript?
JavaScript Junior