Variables in javaScript

Variables in javaScript

In JavaScript, a variable is a container that stores data values. Variables are declared using the var, let, or const keyword followed by a variable name. Here’s a brief overview of each type of variable declaration in JavaScript:

1. var :

var is the oldest way to declare variables in JavaScript. Variables declared with var are function-scoped, which means that their scope is limited to the function in which they are defined, or the global scope if they are defined outside of a function.
Example:

var x = 5;

function myFunction() {

  var y = 10

console.log(x);   // 5

console.log(y);  // 10 

}

2. let :

let was introduced in ECMAScript 6 (ES6) as a replacement for var. Variables declared with let are block-scoped, which means that their scope is limited to the block in which they are defined.
Example:

let x = 5;

if (true) {

let y = 10;

console.log(x); // 5

console.log(y); // 10

}

console.log(y); 

// ReferenceError: y is not defined

3. const :

const is also introduced in ECMAScript 6 (ES6) and is used to declare constants in JavaScript. Variables declared with const cannot be reassigned to a new value, but their properties can be modified if they are objects or arrays. const variables are also block-scoped.
Example:

const x = 5;

x = 10;

// TypeError: Assignment to constant

 variable.

const myObj = { name: ‘John’, age: 30 };

myObj.name = ‘Jane’; // OK

myObj = {}; 

// TypeError: Assignment to constant

 variable.

click here to learn more