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.

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.

let x = 5;

if (true) {

let y = 10;

console.log(x); // 5

console.log(y); // 10



// 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.

const x = 5;

x = 10;

// TypeError: Assignment to constant


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

myObj = {}; 

// TypeError: Assignment to constant


click here to learn more