Tuesday, March 9, 2021

What are variables and constants in Javascript?

JavaScript is cross-platform, object-oriented programming language used for making web pages interactive.

 (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';

var declaration is globally scoped where as let and const are block  scoped.

Let's declare var inside block and console it outside the block and see the result.

variables and constants in Javascript

Let's declare let inside block and console it outside the block and see the result.

variables and constants in Javascript

Let's declare let outside block and assign value to it inside block and console it outside the block and see the result.

variables and constants in Javascript


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.

Example:

num = 10;  // will work

Example:

"use strict";

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

6) The information can be of below type,

Number, String, Boolean, Date/Time, Objects etc.


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

4) const  must be initialized during declaration.

Example:

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 const can't be changed.

1 comment: