Skip to content Skip to sidebar Skip to footer

let, const, and var are three different ways of declaring variables in JavaScript.

  1. var: It is an old way of declaring a variable in JavaScript. It has a function-level scope and can be redeclared and reassigned. If we declare a variable with var in a block, it can still be accessed outside the block.

Example:

var name = "John";
var name = "Mike"; // redeclaring 'name' variable
name = "David"; // reassigning 'name' variable
console.log(name); // output: David
  1. let: It was introduced with ES6 and has a block-level scope. It can be reassigned but cannot be redeclared. A variable declared with the let keyword can be accessed only within the block it is defined in.

Example:

let name = "John";
let name = "Mike"; //SyntaxError: 'name' has already been declared
name = "David"; 
console.log(name); //output: David
  1. const: It also introduced with ES6 and has a block-level scope. Once declared, its value cannot be changed. It cannot be redeclared or reassigned.

Example:

const name = "John";
name = "Mike"; //TypeError: Assignment to constant variable.
const name = "David"; //SyntaxError: Identifier 'name' has already been declared
console.log(name); //output: John

Copyright © 2023. All rights reserved.

Copyright © 2023. All rights reserved.