var , let & const

What are variables?

Variables are used to temporarily store values that are needed for a specific purpose in the program. For example, you might use a variable to store the user's name when they enter it into a form, or to keep track of the score in a game.

var x = 5; // declare a variable x and assign it the value 5
let y = "Hello"; // declare a variable y and assign it the value "Hello"
const PI = 3.14159; // declare a constant variable PI and assign it the value 3.14159

Difference between var, let & const?

The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.

var was the original way to declare variables in JavaScript, but it has been largely replaced by let and const in modern code.

let is used to declare a block-scoped variable, which means that the variable is only accessible within the block of code where it was defined. For example:

function myFunc(){
    let x = 5 // this x is only accessible within this block of code 
    console.log("x")
}

const is used to declare a constant variable, which cannot be reassigned to a different value once it has been set. For example:

const PI = 3.14159; // PI cannot be reassigned to a different value

It's important to note that const does not make the value itself unchanging - it only prevents reassignment of the variable. If the value is an object or array, its properties or elements can still be modified.

In general, it's recommended to use let and const instead of var, because they provide more control over variable scoping and help prevent accidental reassignments.

Template Literal

Template literal is a string literal that allows us to embed expressions inside it using placeholders. These were introduced in ES6 (ECMAScript 2015) and provide a more concise and expressive way of creating strings that contain dynamic values.

const name = "Dev";
const age = 23;
const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting);

// Hello, my name is Dev and I am 23 years old.

Temporal Dead Zone

Temporal Dead Zone is the period of time during which the let and const declarations cannot be accessed. Temporal Dead Zone starts when the code execution enters the block which contains the let or const declaration and continues until the declaration has executed.