cover-img

var, let and const in Javascript

1 March, 2023

11

11

0

Contributors

var, let, and const are used to declare variables in JavaScript, but they have some important differences in terms of scope, reassignment, and hoisting.

Scope:

var: When you declare a variable with var, it is function-scoped. This means that the variable is accessible within the function it is declared in, as well as any nested functions. If a variable is declared outside of a function, it becomes a global variable and is accessible throughout the entire program.

let and const: These variables are block-scoped, meaning that they are only accessible within the block of code they are declared in (usually within curly braces {}), including nested blocks. They are not accessible outside of their block.

Reassignment:

var and let: These variables can be reassigned a new value or reference at any time, as many times as needed.

const: Once you declare a variable with const, its value cannot be reassigned. This means that the variable is read-only and cannot be changed. However, it's important to note that if the variable is an object or an array, the properties of that object or array can still be modified.

Hoisting:

var: When a variable is declared with var, it is automatically hoisted to the top of its scope. This means that the variable can be accessed before it is declared in the code. However, its value will be undefined until it is assigned a value.

let and const: These variables are also hoisted, but they are not initialized until they are declared in the code. This means that if you try to access them before they are declared, you will get a ReferenceError.

In summary, var is function-scoped and can be redeclared and reassigned, while let and const are block-scoped, and const cannot be reassigned after declaration. Additionally, var is hoisted differently from let and const. It's important to choose the right type of variable declaration for your needs to avoid scope-related bugs in your code.

11

11

0

ozboware
PHP and Javascript app developer

More Articles