Tuesday, March 9, 2021

What are variables and constants in Javascript?

 (A) Variables:


1) Variable are used to store data values. 


2) Variable name contains only letters, digits or the symbol $ and _.


3) Variable name must begins with letter, $ and _ and not with digits.


4) To create variable we use let as shown below,


let name = 'Test';


In older scripts keyword "var" is used.


var name = 'Test';


5) We can also declare a variable as shown below without using let, this was mainly possible during old times and this still works unless we don't put "use strict" in our script.


Ex:


num = 10;  // will work


Ex:


"use strict";


num = 10; // error: num is not defined



(B) Constants:


1) Constants are unchanging variables.


2) Declare a constant with const keyword.


3) If we are sure that variable will never change its values use const keyword before variable.



Ex:


const tDay = '01.01.2000';



Summary:


1) let is a modern variable declaration.


2) var is old school variable declaration.


3) const is similar to let but value of variable can't be changed.

1 comment: