Menu Close

var,let,const-The difference between these keywords in javascript

keywords

JavaScript, a versatile programming language employed for both client-side and server-side development, provides three keywords for variable declaration: let, var, and const. These keywords play a vital role in defining variables, each possessing unique behaviors and scopes. In javascript we can declare the variables using var, let and const keyword. First of all we have to know the difference of these keywords .In this session we will share the difference.

Now you are just start using javascript you may hear few things about these keywords are,

  1. var and let create variables that can be reassigned the another value.
  2. const creates “constant” that cannot be reassigned the another value.
  3. The good developers shoudn’t use var anymore.it should use let or const instead.
  4. If you are don’t want to change the value of variable.it is best practice to use “const”.

Why we shouldn’t use var (or) when to use let vs const. Here we go through by this session. Hopefully this will all make sense to you

var vs let vs const-what is the difference?

Here we will be using three factors to analyze the difference between these keywords.

  • Scope of variable
  • Redeclaration and reassignment
  • Hoisting

Let’s start by looking at how these factors apply to variables declared with var.

How to declare variables with var in javascript?

Vaiables declared with var can have global or local global scope.

  • Variables declared with outside of the functions called global scope.
  • Variables declared with inside of the functions called local scope.

Let’s see an example of global scope:

var number = 50

function print() {
  var square = number * number
  console.log(square)
}

console.log(number) // 50

print() // 2500 

In above examble we declared the number variable outside functions in the global space – so we can access it everywhere (inside nd outside functions)

Let’s see an example of local scope:

function print() {
  var number = 50
  var square = number * number
  console.log(square)
}

print() // 2500

console.log(number)
// ReferenceError: number is not defined 

In above example we declared the number variable in function print, so it has local scope. This means that the variable can accessed only inside the function. Any attempt to access the variable at outside the where it was declared will result in a variable is not defined reference error.

How to redeclare and reassign variables declared with var

Variable declared with var can be redeclared and reassigned. I’ll explain with example.

Here’s how to declare the variable with var:

var number = 10; 

You have the keyword var, the name of the variable number, and an initial value 10. If an initial value is not provided, the default value will be undefined.

var number
console.log(number)
//undefined 

The var keyword allows for redeclaration. Here’s an example,

var number = 10
console.log(number) // 50

var number = 50
console.log(number) // 100 

Here, we have redeclared the variable using the keyword var  and value of 50

The var keyword allows for reassignment in the code var number=10, we assigned the 10 value to number. We can reassign another value anywhere in the code since it was declared with var,

Example:

var number = 10
console.log(number) // 10

number = 20
console.log(number) // 20

number = 50
console.log(number) // 50 

Here, we are redeclaring – rather we’re reassigning. After declaring the first time with an initial value 10, we reassign a new value of 20 and later on with a new value of 50.

How to hoist declared with var

Variables declared with var are hoisted to top of their global or local scope. Which makes them accessible before the line theyare declared.

console.log(number) // undefined

var number = 10

console.log(number) // 10 

The variable is hoisted with default value of undefined. So thats the value returned from the variable (until the line where the variable is declared with an initial value gets executed).

let’s see example for local scope: 

function print() {
  var square1 = number * number
  console.log(square1)

  var number = 50

  var square2 = number * number
  console.log(square2)
}

print()
// NaN
// 2500 

In the print function, number has a local scope. Due to hoisting, we can access the variable before the line declaration.

Here we see in square1, we assign number*number since number is hoisted with a default value of undefined, square1 will be undefined*undefined which result is NaN. 

After the line of declaration with an initial value is executed, number will have a  value of 50, so in square 2 number*number will be 50*50 which result is 2500.

Minimize var usage: In modern JavaScript developers, var should be avoided unless strictly necessory, due to its function scope and the potential for variable leakage.

How to declare variables with let in javascript

Introduced in ECMAScript 6 (ES6), the let keyword introduces block-level scoping for variables. Variables declared with let are exclusively accessible within the block they are defined in, whether it is a function, an if statement, or a loop. This restricts variable conflicts and ensures more predictable behavior. Unlike var, let variables cannot be redeclared within the same scope, promoting early error detection.

A block level in javascript  involves opening and closing curly braces.

let number = 30

function print() {
  let square = number * number

  if (number < 60) {
    var largerNumber = 50
    let anotherLargerNumber = 80

    console.log(square)
  }

  console.log(largerNumber)
  console.log(anotherLargerNumber)
}

print()
// 900
// 50
// ReferenceError: anotherLargerNumber is not defined 

In this example, we have a global scope variable number and a local scope variable square. There’s also block scope variable anotherLargerNumber because it is declared with let in a block.

largernumber, on the other hand – though declared in a block – does not have a block scope because it is declared with  var. So largernumber has a local scope as it is declared in the function print.

We can access number everywhere. We can only access square and largernumber in the function because they have local scope. But accessing anotherLargerNumber outside the block throws an anotherLargerNumber is not defined error.  

How to redeclare and reassign the variables with let

var, variables declared with let can be reassigned to other values, but they cannot be redeclared. Let’s see an example:

 let number = 10
console.log(number) // 10

  number = 50
console.log(number) // 50 

In this example, we reassigned another value 50 after the initial declaration of 100. But redeclaring a variable with let will throw an error.

 let number = 10

  let number = 50
// SyntaxError: Identifier 'number' has already been declared 

How to hoist variables declared with let

Variables declared with let are hoisted to the top of their global, local, or block scope, but their hoisting is a little different from the one with var.

var variables are hoisted with a default value of undefined, which makes them accessible before their line of declaration (as we’ve seen above).

But, let variables are hoisted without a default initialization. So when you try to access such variables, instead of getting undefined, or variable is not defined error, you get cannot access variable before initialization

Example:

console.log(number)
// ReferenceError: Cannot access 'number' before initialization

let number = 10 

In above example,  we have a global variable, number declared with let. By trying to access this variable before the line of declaration, we get ReferenceError: Cannot access ‘number’ before initialization.

let’s see an example for localscope variable:

function print() {
  let square = number * number

  let number = 10
}

print()
// ReferenceError: Cannot access 'number' before initialization 

We have a local scope variable, number, declared with let. By accessing it before the line of declaration again, we get the cannot access ‘number’ before initialization reference error.

How to declare the variable with const

The const keyword enables the declaration of variables as constants. Once assigned a value, constants cannot be reassigned or modified. This immutability characteristic guarantees that const variables maintain a fixed value throughout the program.

Similar to let, const variables adhere to block-scoping rules and cannot be redeclared within the same scope. 

Their properties or elements can be modified, but the variable assignment cannot be changed.Variables declared with const are similar to let in regards to scope.

How to redeclare and reassign the variable with const

Here, const is different from var and let. const is used for declaring constant variables – which are variables with values that cannot be changed. So such variables cannot be redeclared, and also not can they be reassigned to other values. Attempting such would create an error.

How to hoist the variable declare with const

Variables declared with const, just like let, are hoisted to the top of their global, local, or block scope – but without a default initialization.

var variables, as you’ve seen earlier, are hoisted with a default value of undefined so they can be accessed before declaration without errors. Accessing a variable declared with const before the line of declaration will throw a cannot access variable before initialization error.

Let’s see an example:

console.log(num)
// ReferenceError: Cannot access 'number' before initialization

const num = 10 

In above example, num is a globally scoped variable declared with const. By trying to access this variable before the line of declaration, we get ReferenceError: Cannot access ‘number’ before initialization. The same will occur if it was a locally scoped variable.

WRAP UP:

KEYWORDSCOPEREDECLARATION & REASSIGNMENTHOISTING
    varGlobal, Local      yes & yesyes, with default value
    letGlobal, Local, Block      no & yesyes, without default value
   constGlobal, Local, Block      no & noyes, without default value

Share

Posted in JavaScript, Web Technologies

You can also read...