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.

Author

Recent Posts

Apple is developing a doorbell camera equipped with Face ID technology.

Apple is reportedly developing a new smart doorbell camera with Face ID technology to unlock…

5 hours ago

Google Launches Its Own ‘Reasoning’ AI Model to Compete with OpenAI

This month has been packed for Google as it ramps up efforts to outshine OpenAI…

2 days ago

You can now use your phone line to call ChatGPT when cellular data is unavailable.

OpenAI has been rolling out a series of exciting updates and features for ChatGPT, and…

4 days ago

Phishers use fake Google Calendar invites to target victims

A financially motivated phishing campaign has targeted around 300 organizations, with over 4,000 spoofed emails…

4 days ago

Hackers Exploiting Microsoft Teams to Remotely Access Users’ Systems

Hackers are exploiting Microsoft Teams to deceive users into installing remote access tools, granting attackers…

6 days ago

Ethical Hacking Essentials

Data plays an essential role in our lives.  We each consume and produce huge amounts…

7 days ago