Variables in JavaScript

A variable is the storage area used to store any value in memory. Consider variable as a container to store data. To create a variable in javascript, var keyword, let or const are used. var keyword, let or const are reserved keywords in javascript, used to create variables. We can also create a variable without using var in javascript, but it is not recommended as per strict mode.

JavaScript variables are loosely typed. This is also knows as dynamic typed. Means a variable x (var x) can store any type of data, like String, number, function, boolean, undefined, null, array or Objects. Usually in all scripting programming languages, variables are loosely typed. But in Java, C or C++, they are strictly typed or statically typed.

Earlier JavaScript was a scripting language, but now its a general purpose programming language with Runtime or JIT Compilation, but still variables are loosely typed.

JavaScript Variables
JavaScript Variables

Variables are always initialized first with var, let or const keyword.
For exp var x means a variable named x is initialized.
To assign a value in variable, = or assignment operator is used, followed by value.


How to declare variables in JavaScript

Variables Declaration is JavaScript is very easy. We can directly declare variables without class or function.


<script>

var x="Tech Altum";    // value of x is "Tech Altum" 

let y=9;               // value of y is 9

const pi=3.14;               // value of pi is 3.14

let a=2, b=3, c=5;     // multiple variables in single line

let u;                 // u is undefined

</script>

Change variable's value

To change the value of a variable, assign a new value to the same variable without using var, let or const. Do not repeat var for existing variable.


var x="hello";
console.log(x);        //  "hello"  
    
x="hola";
console.log(x);        // "hola"      

var keyword is used to declare a variable. To change value of variable, there is no need to use var keyword again, only variable name is enough.


Variable naming convention in JavaScript

To declare a variable in javascript, there are some rules. Here are some rules used to declare variables names in javascript.

  1. variables names cannot include javascript reserved keywords, like var, let, const, for, in, while, true, false, null, class, let, const, function etc.
  2. variables cannot starts with numbers and hyphen, use alphabets, underscore(_) or dollar ($).
  3. variables can have strings followed by numbers, like x1 and x2 are allowed but 1x, 2x is not allowed.
  4. For separation in variable names, use underscore (_) or camel casing, do not use hyphen (-) separation and white space, i.e, user_name is valid, username is also valid, but user-name is invalid.
  5. variables names are case sensitive, i.e, x1 and X1 are different.


Strict Mode

ECMAScript 5 includes strict mode in javascript. "use strict" string is used to follow strict mode. In strict mode, var is compulsory, but in sloppy mode, we can also create variables without var keyword.

It is recommended to use strict mode for faster Compilation and to avoid runtime errors.

How to use strict mode?

To use strict mode in javascript, type "use strict"; just after script opening tag. The remaining code will be after "use strict", like variables declaration, print etc.


<script>
"use strict";

</script>    

Strict Vs Sloppy javascript

Strict mode


var x=3; 
var y=10;   
  1. var compulsory
  2. octal literal not allowed

Sloppy mode


x=3;
y=010;
  1. var optional
  2. octal literal allowed

Always preferred strict mode in javascript.


Sloppy Mode

By default javascript is written in sloppy mode. Sloppy mode allow us to create a variable with or without var keyword.


<script>			
    var x1="tech altum";       	 // allowed 
    x2="javascript";        	 // also allowed 
</script> 
			

Sloppy Mode is not preferred now. It can create runtime errors and perform slow.



Variable Hoisting

JavaScript Hoisting is the process to move all variables and functions expressions to the top of code block or scope before execution. Variable Declaration is hoisted, but variable assignment is not hoisted. This means, a variable x declared at any point can have undefined value before assignment, but after assignment, variable value can be string or number defined.

When we declare a variable says x, the name of variable is stored in memory. That's why its loaded at top of code block. We can even print variable before initialization, but it will print undefined.

During execution of code, variable x will get its value. So we can print value only after execution.

This rule is not same for let and const. They have temporal dead zone.

undefined

hello js

<script> 
console.log(x);       // return undefined

var x="hello js";       

console.log(x);        // return "hello js" 
</script>    

Reason for variable declaration? 🤔

The assignment operator (=) is responsible for variable hoisting in javascript. Before code execution, variable names are stored in memory. The left-hand side of equal to (=) stored variable name before execution. During code execution, variable value on right hand side is assigned. That's why we can only check variable name before assignment. But after assignment only, we can get the value of variable.

It is recommended to declare variables and assign values at the top to avoid variable hoisting issue. This issue is not with let and const as they are strict.


Local Vs Global Variables

A variable in javascript can be local or global variable based on its scope. Variables declared outside function are global variables and variable declared inside function are local variables.

Global Variables

Variables declared outside function are global variable. Global variables have global scope. This means, a variable in <script> tag is by default global. Global Variable once declared can be used anywhere, even inside a function.

Global Variables Example

hello js

88


var x="hello js";        // global variable
var y=88;                // global variable
       
function myFunction(){
    console.log(x)           // returns "hello js"
    console.log(y);          // returns 88
}

myFunction();

Local Variables

Variables declared inside functions are local variables. Local Variables have local scope. This means they are accessible only within their function block, not outside.

Local Variables Example

local variable

local variable

Error

Error


function myFunction(){
        
var x="local variable";
var y="local variable";    
             
console.log(x); // valid 
console.log(y); // valid 
}
    
myFunction()       
         
console.log(x); // invalid 
console.log(y); // invalid 

global Variables in function

recommended way

local

global

Error

global


var y;
function myFunction(){                    
var x="local";
y="global ";    
                             
console.log(x); // valid 
console.log(y); // valid 
}
                    
myFunction()        
                         
console.log(x); // invalid 
console.log(y); // valid 

not recommended

local

global

Error

global



function myFunction(){             
var x="local";          
    y="global ";            
                     
console.log(x);// valid 
console.log(y);// valid 
}
            
myFunction()        
                 
console.log(x); // invalid 
console.log(y); // valid 


let and Const block scope

let and const were introduced in ECMA 6. let is used to declare temporary values within block scope, inside {} . Whereas const is used to declare permanent values, which can't be change. Like value of pi, e, G and other constants.

Scope of var is global or local.

JavaScript let

JavaScript let is used to declare variable in block scope. The value of let is only accessible inside block. Also let naming is not hoisted like var. So let can be used only after declaration.

let if used before initialization throw error because of temporal dead zone.


<script>	
{
    let x="user";  // block scope
}
</script>

let vs var

<script>			
var i=2;            // global scope

if(i==2){
    let i=3;            // block scope
    console.log(i);     // 3
}

console.log(i);         // 2
</script>

JavaScript const

JavaScript const is used to declared immutable values within a block. const value is not changeable. Use const for values li pi which is a constant.


<script>		   	
    const pi=Math.PI;    // pi is a const
</script> 		
			

<script>			
const user="avi";

user="xyz";  //Assignment to constant variable.

</script> 		
			

var vs let vs const

var is function scoped, but let and const are block scoped. let and const are replacement of var in JS ES6 and onwards. Here is table of comparison of var, let and const.

Property var let const
hoisting declaration temporal dead zone temporal dead zone
Reinitializeyesnono
reassign valueyesyesno
ScopeFunctionblockblock
Create Global propertyyesnono
  1. Although it is not compulsory, but its always recommended to use strict mode.
  2. let and const are supported in IE 11 and above, edge, firefox 36 and above, chrome 21 and above, safari 5.1 and above.
  3. For IE 10 and below, use var.