javascript

Differences Between var, let and const.

Var Declaration

Before the introduction of ES6 in 2015, var was the go-to way to declare variables in Javascript.

Example:

var a;
a = 5;
console.log(a) //5

But because variable declarations are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top.

This also means that a variable can appear to be used before it is declared.

This behaviour is called “hoisting.”

Example

console.log(bar); //undefined
var bar = 22;
console.log(bar) //22
bar = 33;
console.log(bar) //33

Let Declaration

“let” is one of the ES6 additions to Javascript.

When you use this type of declaration, you are saying you want the variable to be reassigned but not to be redeclared.

Example:

let a = 3;
console.log(a) //3
let a = 5;
console.log(a) //Identifier 'a' has already been declared

//But if we reassign like so
a = 6;
console.log(a) //6

Const Declaration

‘const’ is also an ES6 addition.

When you use const to declare a variable, you are saying that you don’t want that variable to be reassigned or be redeclared.

Example:

const a = 33;
console.log(a) //33
const a = 34;
console.log(a) //Identifier 'a' has already been declared

//Even if we reassign
a = 35;
console.log(a) //Assignment to constant variable

In Summary …

  1. A var type variable declaration can be both be redeclared and reassigned.
  2. A let type declaration can only be reassigned but not redeclared.
  3. A const type declaration can neither be redeclared or reassigned.

Recent Posts

South Korea bans downloads of DeepSeek AI until further notice

The South Korean government announced on Monday that it had temporarily halted new downloads of…

5 days ago

Which programming language is best for software development?

As a software developer, choosing the right programming language for software development can be a…

1 week ago

What is a server farm?

A server farm, also known as a server cluster or data center, is a collection…

1 week ago

Elon Musk’s Starlink satellite internet service is awaiting authorization to begin operations in Pakistan.

Pakistan's mobile and broadband internet speeds rank in the bottom 10 percent globally, according to…

2 weeks ago

React Native Styling Guide

React Native is a popular framework for building cross-platform mobile applications using JavaScript and React.…

2 weeks ago

You can now customize your Android home screen shortcut with any widget of your choice

Google is not only passionate about developing innovative apps and services but also about finding…

2 weeks ago