JavaScript Variables and Constants with example

A variable is a container that holds value. A variable name is basically used for referring value. For example

 var n1=10 

Here, n1 is variable. it's storing value 10.

different ways to declare variables in javascript

In Javascript, there are 3 ways, you can declare a variable.

1) Var

2) let

3) const

1) var keyword

the var keyword is used in an older version of javascript. the var statement declares a global-scoped or functional-scoped.

if you redeclaring a variable inside a block. its value will also change from outside of the block

Example

var x = 5;
// Here x is 5

{
var x = 10;
// Here x is 10
}

// Here x is 10 

Run now

let Keyword

Let keyword was introduced in ES6(2015), before let variable, we have only two types of variable scope, global scope, and functional scope. now we have one more scope i.e block scope.

  • the variable which is declared with let has a block scope.
  • let variable must be declared before use.
  • once, you declare a variable with let, you cannot redeclare
  • the variable declared with let can only access inside a block, not from outside of the block.

Example

{
	let x = 10;
	// Here x is 10
}
// variable x can't use here

Run now

const JavaScript(js) with example

const keyword was also introduced in ES6(2015).

The variable which is declared with const has block scope.

once the const variable is initialized, you cannot change its value. for example

const a=10;
a=3; // TypeError: Assignment to constant variable.