DEV Community

Damith Samarasighe
Damith Samarasighe

Posted on

JavaScript var, let & const

JavaScript Variables

In programming we use variables for store data. Basically variables are like containers which we can store something init.

let name = "John";
Enter fullscreen mode Exit fullscreen mode

name is a variable which storing John as it's value

Declare Variables in JavaScript

We can declare variables with var or let keywords. For example,

var a;
let b;
Enter fullscreen mode Exit fullscreen mode

In here a and b are variables.

var Vs let

Both var and let are use to declare variables. However there are some differences.

1. Scope:

  • var is only available within the function where it is declared. which means var is "function-scoped". if declare outside any function, it becomes a global variable.

  • let is limited to the block where it declared. which means let is "block-scoped".

2. Hoisting:

  • Variables declared with var are hoisted to the top of their scope during the compilation phase. This means you can use the variable before it is declared in the code.

  • Variables declared with let are also hoisted, but they are not initialized until the interpreter reaches the line where the variable is declared. Accessing a let variable before its declaration results in a ReferenceError.

3. Re-declaration:

  • With var you can re-declare a variable within the same scope without any errors. The new declarations overrides the previous one.

  • With let when you re-declared a variable in the same scope, it will gives you SyntaxEror.

However, it is recommended we use let instead of var because var is used in the older versions of JavaScript and let is the new way of declaring variables starting ES6 (ES2015).

Initialize Variables

we can use the assignment operator = to assign a value to a variable

let a;
a = 5; 
Enter fullscreen mode Exit fullscreen mode

now variable a has the value of 5.

We can also initialize variables during its declaration. For example,

let a = 5;
let b = 6;
Enter fullscreen mode Exit fullscreen mode

We can also declare variables in a single statement.

let a = 5, b = 6, c = 7;
Enter fullscreen mode Exit fullscreen mode

JavaScript const

The const keyword was also introduce in the ES6(ES2015) version to create constants. For example,

const a = 6;
Enter fullscreen mode Exit fullscreen mode

Once a constant initialized, we cannot change its value.

const a = 6;
// a = 8; // Error: Assignment to constant variable (reassigning is not allowed)

console.log(a); // Output: 6
Enter fullscreen mode Exit fullscreen mode

Basically constant is a type of variable whose values cannot be change.
Also we cannot declare constant without initializing it.

In summary, understanding the nuances of var, let, and const allows developers to use the right tool for the job, developing cleaner and more maintainable JavaScript code.

Top comments (0)