var, let & const in JavaScript

  • With ES6, a version of JavaScript, two new keywords, let & const, were introduced to create variables.
  • var is still used to declare variables, but let & const are recommended.
  • Use let if you want to create a variable and use const if you want to create a variable that holds a constant value (a value that you assign once and never change).

var

  • We use var to declare variables in JavaScript.
  • It is function or globally scoped.
  • Can be re-declared in the same scope
var name="David";
// can use name here
function getName(){
// can use name here as well
}

var name="Mike"; // can be easily re-declared

function myFunc(){
var address="US";
// address can be used anywhere within this function, but not outside this function.
}

let

  • It is used to declare variables.
  • These variables are block scoped.
  • They cannot be re-declared
for(let i=1;i<=10;i++){
console.log(i); // i is used here
}
// i cannot be used here, throws an error: i not defined

let i=100; // cannot be re-declared, throws an error: i is already declared

function newFunction(){
let phone=78989879;
// phone can be used anywhere within the function, but NOT outside the function.
}

const

  • It is used to declare constant variables.
  • They cannot be re-assigned.
  • We generally use const variables for defining settings like URL link, database settings etc.
const PI = 3.1416;
PI = 3.14; // This will throw an error
const PI=45.23; // This will also throw an error: Assignment to constant variable
Unknown's avatar

Author: Akanksha Gupta

I am a developer and working on SharePoint and Project Server in an MNC. I have more than 10 years of experience in the same field.

Leave a comment

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started