var, let and const in Java Script

This concept is very important to understand as a beginner. It makes the scope concept very clear. There are three ways by which variables are declared in JavaScript.

var name = "John";

let name = "John";

const name = "John";

var

var is the oldest way to declare a variable in JavaScript. var can be reassigned and updated. We will understand this with an example.

//declare
var weight = 70;
//Log it to the console
console.log(weight)
//returns
70

//Reassign the variable
var weight = 75;
//Log it to the console
console.log(weight)
//returns
75

As we can see in the above example when we re-declare weight it gets reassigned to 75.

Scope of var

var has a function scope. Now you will ask what does it mean? In simple words var is only available inside the function in which it is created. If var is defined inside a function and you try to call it outside the function, it won’t work. If they are declared outside a function then they have a 'global scope'.

function userHeight() {
  var height = 100;
  console.log(height);
}
height;

//Returns
Uncaught ReferenceError: height is not defined

TRIVIA

let and const were introduced in ES2016 to overcome the faults of var as it leaks data.

let

let has a block scope, it means it cannot be re-declared. block implies a pair of curly braces {}

let points = 50;

let points = 60;

//returns
Uncaught SyntaxError: Identifier 'points' has already been declared

Although you can update it.

let points = 50;
points = 60;
// In console:
points
// Returns:
60

Scope of let

If you declare a let variable at global scope, then redeclare it within a block as in the example below, you will not get an error in the console, but it will not actually redeclare let.

let points = 50;
let winner = false;
if(points > 40) {
  let winner = true;
}
// If I call:
winner
// It returns the first value: 
false

const

const variables once declared cannot be changed. const variables also have block scope.

//declare
const userName = 'johnDoe223'

//reassign
const userName = 'johndoe111'

//returns
Uncaught TypeError: Assignment to constant variable.

Although const variables cannot be redeclared, there is a catch.If you create a const variable that is an object, the attributes of that object can be updated.

const userProfile = {
  name: 'John Doe',
  age: 33
}
// Calling in the console:
person
// It returns:
{name: "John Doe", age: 33}
// redeclare the age attribute:
userProfile.age = 34
// call it:
person
// It returns:
{name: "John Doe", age: 34}

SUMMARY

var is function scope.
let and const are block scope.
Function scope is within the function.
Block scope is within curly brackets.