Introduction
Do your webpages feel boring without an interactivity ? It may feel and you may wonder how can we add interactivity to webpages , Javascript does the job of adding intractivity to webpage thereby it is also called as The Language of Web , We will dive into Javascript fundamentals in this blog , we will discuss different datatypes and everything you need to know about variables in fun way .
Variables
What is Variable?
Consider Example of Cricket team , it will have 11 Players they can be classified as batsmen,bowler and allrounders lets consider 5 are batsman, 3 are bowler, 2 are allrounder . How will you distinguish between different batsman,bowlers and allrounders they need to have unique identity in this case they have their name as unique property , similiarly Variables are there in programming which provides unique identity to different data element.
Variables can be declared in various ways in Javascript . Variables can be declared in Implicit way or Explicit way.
1.Explicit Declaration
What do you understand by word Explicit ? Explicit means clearly stated , leaving no space for unclearity . Explicit Declaration you can understand with above sentence , it is manual declaration of variable. Variables can be Explicitly declared using three keywords var, let and const.Let’s understand each one in detail.
1.var
var declaration was used in all Javascript code from 1995 to 2015. Now it is been rarely used in modern javascript with arrival of let and const declaration.
The var declaration is used to create variable and it defines scope of variable within function which means once the variable is declared inside function ,it can be used anywhere in function . Variables declared using var keyword can update their values later (mutable). Let’s understand it through an simple example.
function example() {
var a = "Virat Kohli"; //String that is name of player is declared using var keyword
console.log(a);
}
example();
//output
//Virat Kohli
2.let
let declaration is most used declaration way in modern javascript .let declaration has block level scope , it cannot be accesed throughout function or outside of function if declared inside certain block. Variables declared using let keyword can update their values later (mutable).
function example() {
if(true){
let a = "Virat Kohli"; //String that is name of player is declared using let keyword
console.log(a);// output will be Virat Kohli
}
console.log(a); // Reference Error: a is not defined (it is a block scoped)
}
example();
3.const
const declaration is also block scopic , once value of variable is declared using const keyword it cannot be modified later(immutable) , we use it when we want constant variable which will not change its value in program.
function example() {
if(true){
const a = "Virat Kohli"; // const declaration
console.log(a);// output will be Virat Kohli
a = "Rohit Sharma";// TypeError cannot reassigned value to constant keyword
}
console.log(a); //Reference Error
}
example();
4.Variable Scope
Global Scope: Variables declared outside any function or block are globally scoped. They are accessible throughout the entire program.
Local Scope: Variables declared inside a function or block (using let or const) are limited to that function or block.
Block Scope: With let and const, variables are scoped to the block ({}) where they are declared.
5..Hoisting
Hoisting refers to behaviour of javascript where variable declaration and function declaration are moved to top of their containing scope during compiling phase. It is different in var, let , const , only declaration of variable gets hoisted not the initialisation of variable .
// Hoisting with var
console.log(a); // Output: undefined (because 'a' is hoisted but not initialized yet)
var a = 5;
console.log(a); // Output: 5 (after the initialization line is executed)
// Hoisting with let
console.log(b); // Error: Cannot access 'b' before initialization
let b = 10;
//Hoisting with const
console.log(c); // Error: Cannot access 'c' before initialization
const c = 20;
Let’s understand above code Hoisting with var: variable declaration will be moved to the top but not the initialization so variable will not contain any value so it will return output as undefined. Hoisting with let and const : With let and const, the variables are hoisted but remain in the temporal dead zone(tdz) until the actual line where they are declared is reached. If you try to access them before that, It throws an error.
6.Summary
Feature | var | let | const |
Scope | Function Scope | Block Scope | Block Scope |
Hoisting | Yes (initialized as undefined) | Yes (in Temporal Dead Zone) | Yes (in Temporal Dead Zone) |
Reassignment | Allowed | Allowed | Not Allowed |
Redeclaration | Allowed | Not Allowed | Not Allowed |
Block Scope | No (escapes block) | Yes (stays within {}) | Yes (stays within {}) |
Initialization Required? | No | No | Yes (must be initialized) |
2.Implicit (Automatic) Declaration
In this type of declaration we assign value to variable without first declaring it , variable’s declaration is done automitically by Javascript. Implicit declaration creates global variable while declaring variable.
function test() {
x = "Hello Coders"; // Implicitly creates a global variable
}
test();
console.log(x); // Output: Hello Coders as x becomes global variable.
When we assign value to variable without declaring it , Javascript automitically creates it as global variable even if it is in function it will be accessible outside function now. This method is not used as it can lead to name conflicts and unexpected behaviour in large databases.
Datatypes
What are datatypes?
Let’s revisit cricket example ,11 players are classified into three different categories as batsman, bowler and allrounder , so what are this categories they are datatype of players. Datatypes tells us what type of data is present in variable. It is of two type :
1.Primitive Datatypes
1.String
let color = "Yellow";// Declaration of string
console.log(typeof(color));// Output: string
There is no char datatype in Javascript even single character is there in double quotes it will be string. We can check datatype of variable using typeof() function.
2.Number
Number contains numeric values ( integer or floating point) but values are stored as floating point values in memory.
// With decimals:
let x1 = 25.00;
// Without decimals:
let x2 = 25;
console.log(typeof(x1));// output: number
console.log(typeof(x2));// output: number
3.Boolean
Boolean datatypes represent values as true or false.
let bool = true; // Boolean
let bool2 = false;
4.Null
Datatype where variable is declared but it has null as a value .
let empty = null;
console.log(typeof(empty));// output: object
empty will show object as its datatype instead of null ,it is bug of Javascript . Every variable has object as its datatype in javascript.
5.Undefined
The datatype of variable is undefined when variable is declared but not initialised as was in the case of var hoisting. Undefined datatype in simple term means Javascript does not know what data is going to come in variable.
let a;
console.log(typeof(a)); // output :undefined
6.BigInt
All JavaScript numbers are stored in a 64-bit floating-point format.
JavaScript BigInt is a new datatype (ES2020) that can be used to store integer values that are too big to be represented by a normal JavaScript Number. It will give bigint as it’s type.
let x = BigInt("123456789012345678901234567890");
7.Symbol
Symbol in JavaScript is a unique and immutable value. It is mainly used to create unique object keys to avoid naming conflicts.
let id = Symbol("userID");
console.log(id); // Output: Symbol(userID)
2.Non Primitive Datatypes
Non Primitive Datatypes are objects or derived datatypes which can store collections of values. Two key Non Primitive Datatypes are :
1.Objects
An object in Javascript is an entity having properties and methods. Everything is an object in javascript. It stores values in key : value format.
let person = {
name: "Coder",
age: 20,
isStudent: true
};
console.log(person.name); // "Code0"
console.log(person["age"]); // 25
We can easily access values from object by using . function or passing objectname[“key”]. It will show object as its datatype when checked using typeof function.
2.Arrays
An array is a special object that stores ordered collections of data.
Each value is assigned an index (starting from 0 and ending on size-1 ) .**Arrays in JavaScript can store multiple data types in the same array.**Unlike some other programming languages (like Java or C++), where arrays are type-specific, JavaScript arrays are dynamic and can hold different types of values.
let numbers = [10, 20, 30, 40];
console.log(numbers[0]); // 10 (Access by index)
console.log(numbers.length); // 4 (Array size)
numbers.push(50); // Add element
console.log(numbers); // [10, 20, 30, 40, 50]
Type Coercion
Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers). Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit.
const value1 = "5";
const value2 = 9;
let sum = value1 + value2;
console.log(sum);
In the above example Javascript will implicitly convert either value1 as number or value2 as string to perform operation.We can not control type coercion.If we want to have control over what datatype it is converting to we can use Type Conversion.
Conclusion
Now you have understood the fundamentals of Javascript that is how to declare variables and what are different datatypes , there is more in non primitive datatypes as they are defined by programmers now you have the basic understanding of data types to explore them . I hope you understood fundamentals and throughly enjoyed reading this ,if you have any suggestion please let me know in comments . Happy Coding!