javascript

Variables


 

Variables are used to store and manipulate data. They are containers for holding values, and the values can be of various types such as numbers, strings, Boolean values, arrays, functions, etc.

There are 3 ways of declaring variables:

  • Var
  • Let
  • Const

 

1. var:

Var is the oldest way to declare variables. It has function-scope or globally scoped . They are accessible throughout the function in which they are defined or globally if declared outside of any function.

 

 Note: Var can be redeclared

 

Syntax:

var variable_name = variable_value;

 

Example:

var num1 = 5;
var num2 = 6;
var product = num1 * num2;

 

2. let:

Let is a keyword used to declare variables which has block-scope and it was introduced in ECMAScript 6, 2015. They are accessible only within the block in which they are defined, whether it's a loop, conditional statement, or any other block
 

Syntax:

let variable_name = variable_value;

 

Example:

let num1 = 5;
let num2 = 6;
let product = num1 * num2;

 

3. Const:

The const keyword is used to declare variables whose value cannot be changed and it has a block-scope.
It was introduced in ECMAScript 6, 2015.
 

Syntax:

const variable_name = variable_value;

Example:

const num = 1;

 

Values:

 

In JavaScript there are total 8 Values:

  • Numbers:
let age = 23;

 

  • Strings:
let str = "Coder";

 

  • Booleans:
let boolValue = false;

 

  • Null:
let nullValue = null;

 

  • Undefined:
let undefinedValue = undefined;

 

  • Symbols:
let symb = Symbol("unique");

 

  • Objects:
let userObject = { name: "Wasif", age: 23 };

 

  • Arrays:
let arraysValue = [1, 2, 3, 4];