var
was the original way to declare variables in JavaScript, but in recent versions of the language, let
and const
have been introduced as alternative ways to declare variables with different scoping and immutability behaviors.
Here are the main differences between let
, var
, and const
:
var
Variables declared with var
have function-level scope. This means that they are accessible within the function they are declared in, as well as any nested functions.
let
Variables declared with let
have block-level scope. This means that they are accessible only within the block they are declared in, including any nested blocks.
const
Variables declared with const
have block-level scope and are immutable. This means that they cannot be reassigned to a different value after they are initialized.
Here are some examples of var
, let
, and const
declarations without using functions:
// var example var x = 10; if (true) { var x = 20; } console.log(x); // Output: 20 // let example let y = 10; if (true) { let y = 20; } console.log(y); // Output: 10 // const example const z = 10; if (true) { const z = 20; } console.log(z); // Output: 10
Leave a Reply