Variables
Variables
1. var Keyword
The var keyword is used to declare a variable. It has a function-scoped
or globally-scoped behaviour.
var n = 5;
console.log(n);
console.log(n);
Output
5
20
JavaScript Let
The let keyword was introduced in ES6 (2015)
The let keyword is introduced in ES6, has block scope and cannot be
re-declared in the same scope.
let n= 10;
n = 20; // Value can be updated
console.log(n)
Output
20
JavaScript Const
The let keyword was introduced in ES6 (2015)
const Keyword
The const keyword declares variables that cannot be reassigned. It’s
block-scoped as well.
const n = 100;
console.log(n)
Output
100
Cannot be Reassigned
A variable defined with the const keyword cannot be reassigned:
Example
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
Must be Assigned
JavaScript const variables must be assigned a value when they are
declared:
Correct
const PI = 3.14159265359;
Incorrect
const PI;
PI = 3.14159265359;
A new Array
A new Object
A new Function
A new RegExp
3. Always use const if the type should not be changed (Arrays and Objects)
Constant Arrays
You can change the elements of a constant array:
Example
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];
Example
const cars = ["Saab", "Volvo", "BMW"];
Example
// You can create a const object:
const car = {type:"Fiat", model:"500", color:"white"};
Example
const car = {type:"Fiat", model:"500", color:"white"};
Data Types
JavaScript supports various datatypes, which can be broadly
categorized into primitive and non-primitive types.
Primitive Datatypes
Primitive datatypes represent single values and are immutable.
1. Number: Represents numeric values (integers and decimals).
let n = 42;
let pi = 3.14;
console.log(notAssigned);
Output
undefined
Non-Primitive Datatypes
Non-primitive types are objects and can store collections of data or
more complex entities.
1. Object: Represents key-value pairs.
let obj = {
name: "Amit",
age: 25
};