Learn JavaScript, I will start from Setting workspace to Advance Javascript
Master JavaScript
Table of contents
- What is JavaScript
- Compiler (JavaScript Run Time)
- Variables
- Data Types
- Type Conversion
- Operators In JavaScript
- Strings and there Methods
- Numbers and Math
- Date and Time
- Arrays
- Array Declaration
- Declaring an Array
- Accessing Elements
- 1. at(index)
- 2. includes(value)
- 3. indexOf(value)
- 4. lastIndexOf(value)
- 5. entries()
- 6. push(value1, value2, β¦)
- 7. pop()
- 8. shift()
- 9. unshift(value1, value2, β¦)
- 10. splice(start, deleteCount, item1, item2, β¦)
- 11. fill(value, start?, end?)
- 12. map(callback)
- 13. filter(callback)
- 14. reduce(callback, initialValue?)
- 15. find(callback)
- 16. findIndex(callback)
- 17. sort(compareFn?)
- 18. toSorted(compareFn?)
- 19. reverse()
- 20. toReversed()
- π’ Other Methods
- Objects
- Object Destructuring and JSON
- Functions
- π 1. Function Basics
- πΉ Arrow Function (ES6)
- π 3. Function Parameters
- πΉ Default Parameters
- πΉ Rest Parameters (...args)
- πΉ Spread Operator (...)
- π 4. Function Scope & Hoisting
- πΉ Local vs Global Scope
- πΉ Function Hoisting
- π 5. Closures
- π 6. Recursion (Function Calling Itself)
- πΉ Factorial Example
- πΉ Fibonacci Sequence
- π 7. Callbacks & Higher-Order Functions
- πΉ Callback Function
- πΉ Higher-Order Functions
- π 8. Immediately Invoked Function Expression (IIFE)
- π 9. Function Binding: call(), apply(), bind()
- πΉ call()
- πΉ apply()
- πΉ bind()
- Scope
- Understand how JavaScript works under the hood
- Control Flow (if, else,switch)
- JavaScript Control Flow & Conditional Statements
- Loops
- Break and Continue
Hey, I am Gopal, have 2 years of experience in web development. In this in depth Guide on JavaScript ,you will get the hands on experience, all terminologies, behind the scene how it works, and under wood who it is executed, and many more β¦ I can assure you after reading the blog you will definitely stand out from others
Impotent Note : This guide is structured in a way ,beginners, intermediates , and advanced developers can also will learn something new
There will be Three sections for each topic for each level developers, if you are beginner ,you just learn all the basic and you are good to go. else if you are pro/advanced developer you will learn most advanced concepts for each section
System Requirements : You are good to go , if you have 4-8GB ram , alteast 2 core processor
About My System:
MSI Modern 14 Laptop, it have 16gb ram, 512gb storage, and hexa(6) core processor Ryzen 5 7530U
OS : Linux Ubuntu 24.4.0
What is JavaScript
JavaScript is the language that turns static web pages into interactive experiences. JavaScript is a high-level, dynamic programming language thatβs primarily used to create interactive and dynamic content on websites.
Lets Brake down,
letβs say you wrote a code in JavaScript how to do you and computers know this is JavaScript . Using file Extinctions Denoted by .js
at the end of file
how will code will execute, Letβs compare JavaScript with C (compiled and low level ) language
JavaScript is Dynamic Typed Language , the Data types are defined on run time ex:
C Program: letβs write some code in C ,in order to run it should be compiled by compiler like GCC
int val = 13;
printf("%d",val);
β this will provide the executable code with file extension .exe
which can be run any ware
JavaScript : But in JS there is no code Compilation, the types will directly assigned in run time
let value = 10;
console.log(value)
In JavaScript There will be no Code compilation like c, c++, java where we need to explicitly need to define data types
Compiler (JavaScript Run Time)
JavaScript was once limited to browsers, but it was later separated and made open source, allowing anyone to run JavaScript code independently on their system using the runtime environment called "Node."
Node is one of the Run time Environment (where JavaScript code can be run) they are others ex: Bun and Deno
Each of them have there own Pros and Cons , with installing node we also get the Package Manager called npm
. which allow to install or get the other codes (library and others) to your code base
Letβs Install it now
Navigate to any of your browser and search for node js install. then download the LTS (long term support) version. after downloading to verify the downloads
open Terminal and type node βversion
, If you get the version number ,it is successfully installed
if You are using Linux use this bellow commands to install .Below are the installation commands you can run in your Linux terminal to install Node.js, Deno, and Bun.
1. Installing Node.js
One common method is to use the NodeSource binary distributions. For example, to install Node.js version 18 on a Debian/Ubuntu-based system, run:
# Update package index and install curl if needed
sudo apt update && sudo apt install -y curl
# Download and run the NodeSource setup script for Node.js 18.x
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
# Install Node.js
sudo apt-get install -y nodejs
2. Installing Deno
The easiest way to install Deno is by running its installation script. In your terminal, run:
curl -fsSL https://deno.land/install.sh | sh
After installation, ensure that the Deno binary (usually installed to ~/.deno/bin
) is in your PATH
. You might add the following line to your shell configuration file (e.g., ~/.bashrc
or ~/.zshrc
):
export DENO_INSTALL="$HOME/.deno"
export PATH="$DENO_INSTALL/bin:$PATH"
Then, reload your shell configuration:
source ~/.bashrc # or source ~/.zsh
3. Installing Bun
Bun provides its own installation script. Run the following command in your terminal:
curl -fsSL https://bun.sh/install | bash
This script installs Bun (typically under your home directory, e.g., ~/.bun
). Follow any post-installation instructions printed by the script, which may include adding Bunβs binary location to your PATH
. For example, you might add:
export BUN_INSTALL="$HOME/.bun"
export PATH="$BUN_INSTALL/bin:$PATH"
Then, reload your shell configuration:
source ~/.bashrc # or source ~/.zshrc
After installing to verify Installation Type this in terminal node -v
for node deno -v
for deno and bun -v
for bun
After Installing the JS runtime now its time to install the Code editor , Letβs Install VS code , go to the browser, search for vs code editor then download that
After You successfully installed the code editor , now it is time to write first Hello world code.
Open terminal
cd Desktop
mkdir JS-programming
cd JS-programming
then enter code .
it will open the file in vs code ,if it show the popup ,press on βI Trust the Authorβ
create a file in hello.js
and write the following code
console.log("Hello Javascript")
save the file now open terminal in vs code (vs code inbuilt terminal) use this short cut if you donβt know how to open β ctrl + ` β this will open terminal in vs code
now type node hello.js
or runtime <filename>
You will the output as Hello Javascript
in terminal
congratulation you just wrote your first code in JavaScript
Variables
In JavaScript we have Three type of Variables let
,const
and var
, but in recent years JavaScript Developers stopped using the var
because of its issue in block scope and functional scope ,so it proffered not to use var
What is a Variables? this are the special keywords that recognized by the nodejs to determine the actions that can be done on them
const Id = 1221 // id cannot be changes in future
let FirstName = "Gopal" // let allow to chage the value in future
// var LastName = "N D" // don't use var
console.log(Id)
console.table([Id,FirstName])
/*
> node main.js
1221
βββββ¬βββββββββ
β β Values β
βββββΌβββββββββ€
β 0 β 1221 β
β 1 β Gopal β
βββββ΄βββββββββ
*/
we can also initialize without any variable ,but it is not good practice to do
city = "Mycityname"
console.log(city) // Mycityname
if we declare a variable and not assigning any value to it
let planet;
console.log(planet) // undefined
so now we learned different way to declare a variable using let
, const
letβs see how can we do commentβs in JS there are two types inline and multi-line comment
// inline comment
/*
this is multiline comment
node js will ignore this lines
*/
Data Types
JavaScript can be treated as of two versions ,one is newer and another is old(which not had class, modules, es6+ features) all this is controlled by the ecma script standards , to use the newer version on the top of file we put a keyword βuse strictβ;
on top of file , now a days there is no need of using the key word
while dealing with JavaScript we need to be aware of where we are running our code,whether in node or browser
if you are using in browser you can use the browser api and window , global object
alert("hi");
if you run this i,browser environment you will get the alter popup but, if you do this in node it will throw error, In the same way node provide module that help to interact with the os, file system which cannot be found in browsers
Letβs see the JS DataTypes
There are two types Primitive and Non-Primitive types letβs see
Primitives
string β represeted in ββ , ββ, ``
number : max-number , min-number
Number.MAX_SAFE_INTEGER // 2^53 - 1 = 9007199254740991
Number.MAX_VALUE); // ~1.7976931348623157e+308
Number.MIN_SAFE_INTEGER); // -2^53 + 1 = -9007199254740991
Number.MIN_VALUE); // 5e-324
boolean β true , false
bigint
symbol
null
undefined
// undefined
let a;
console.log(a)
//null
let b = null
console.log(b) // output null
//boolean
let isAvailable = true;
console.log(isAvailable); // Output: true
//number
let count = 42;
let price = 9.99;
console.log(count, price); // Output: 42 9.99
//string
let message = "Hello, JavaScript!";
console.log(message); // Output: Hello, JavaScript!
//symbol
let sym = Symbol("unique");
console.log(sym); // Output: Symbol(unique)
let id = Symbol('12')
let anotherId = Symbol('12')
console.log(id===anotherId) //Output: false
//bigint
let bigNumber = 1234567890123456789012345678901234567890n;
console.log(bigNumber);
To what type of data type they are we can use typeof()
// undefined
let a;
console.log(typeof a); // Output: "undefined"
// null
let b = null;
console.log(typeof b); // Output: "object" (special case in JavaScript)
// boolean
let isAvailable = true;
console.log(typeof isAvailable); // Output: "boolean"
// number
let count = 42;
let price = 9.99;
console.log(typeof count, typeof price); // Output: "number number"
// string
let message = "Hello, JavaScript!";
console.log(typeof message); // Output: "string"
// symbol
let sym = Symbol("unique");
console.log(typeof sym); // Output: "symbol"
// bigint
let bigNumber = 1234567890123456789012345678901234567890n;
console.log(typeof bigNumber); // Output: "bigint"
Non-Primitive
Unlike primitive types (string, number, boolean, etc.), non-primitive types are reference types, meaning they store references (memory addresses) rather than actual values.
Object β A collection of key-value pairs where keys are strings or symbols.
let obj = { name: "Alice", age: 25 };
console.log(obj.name); // Output: Alice
Array β An ordered collection of elements indexed numerically.
let arr = [10, 20, 30];
console.log(arr[1]); // Output: 20
Function β A reusable block of code that can be executed when called.
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Bob")); // Output: Hello, Bob
Date β Represents a specific date and time.
let now = new Date();
console.log(now.toDateString()); // Output: (Current date in readable format)
Map β A key-value store where keys can be any data type.
let map = new Map();
map.set("name", "Charlie");
console.log(map.get("name")); // Output: Charlie
Set β A collection of unique values.
let set = new Set([1, 2, 2, 3]);
console.log(set); // Output: Set(3) { 1, 2, 3 }
Class β A blueprint for creating objects with properties and methods.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name}`;
}
}
let person1 = new Person("David", 30);
console.log(person1.greet()); // Output: Hello, my name is David
Lets see typeof()
them
let obj = { name: "Alice" }; let arr = [1, 2, 3]; function testFunc() {} let now = new Date(); let map = new Map(); let set = new Set(); class Person { constructor(name) { this.name = name; } } let person1 = new Person("John"); console.log(typeof obj); // Output: "object" console.log(typeof arr); // Output: "object" console.log(typeof testFunc);// Output: "function" console.log(typeof now); // Output: "object" console.log(typeof map); // Output: "object" console.log(typeof set); // Output: "object" console.log(typeof person1); // Output: "object" console.log(typeof Person); // Output: "function" (class is a special function)
typeof
returns"object"
for instances ofObject
,Array
,Date
,Map
,Set
, andClass
.typeof
a function (including class declarations) returns"function"
.
Among all this we mostly use :
Primitives β string, number ,boolean
Non-primitives βObject, array
If you this much your good to go
Type Conversion
conversion of other Data Type to β Number : In this we will learn all the way to convert other data types to number
In JavaScript, different data types can be converted to a Number
using various methods like Number()
, parseInt()
, parseFloat()
, and unary +
. Below is a detailed summary with examples.
Using Number()
Converts various data types into a
number
.Returns
NaN
(Not-a-Number) for values that cannot be converted.
console.log(Number("42")); // Output: 42 (string to number)
console.log(Number("42.99")); // Output: 42.99 (string to number)
console.log(Number("4ru99")); // Output: NaN (invalid string)
console.log(Number("abc")); // Output: NaN (invalid string)
console.log(Number(true)); // Output: 1 (true β 1)
console.log(Number(false)); // Output: 0 (false β 0)
console.log(Number(null)); // Output: 0 (null β 0)
console.log(Number(undefined)); // Output: NaN (undefined cannot be converted)
console.log(Number([])); // Output: 0 (empty array)
console.log(Number([10])); // Output: 10 (array with one number)
console.log(Number([1,2,3])); // Output: NaN (multiple elements in array)
console.log(Number({})); // Output: NaN (object cannot be converted)
while converting string to number, while it have any non - numeric number except e
char it will convert to nan
(not-A-Number)
Using parseInt()
:
Converts a string into an integer by extracting leading valid digits.
Ignores non-numeric characters after the number.
Returns
NaN
if no numeric characters are found.
console.log(parseInt("42px")); // Output: 42 (extracts leading number)
console.log(parseInt("42.99")); // Output: 42 (integer part only)
console.log(parseInt("abc42")); // Output: NaN (no leading number)
console.log(parseInt("100", 2)); // Output: 4 (binary "100" β decimal 4)
console.log(parseInt("F", 16)); // Output: 15 (hex "F" β decimal 15)
console.log(parseInt("010", 8)); // Output: 8 (octal "010" β decimal 8)
Using parseFloat()
:
Converts a string into a floating-point number.
Similar to
parseInt()
, but keeps decimal values.Stops at the first invalid character.
console.log(parseFloat("42.99px")); // Output: 42.99 (extracts valid float)
console.log(parseFloat("42.56.78")); // Output: 42.56 (stops at second `.`)
console.log(parseFloat("abc42")); // Output: NaN (invalid conversion)
console.log(parseFloat("3.14e2")); // Output: 314 (scientific notation)
console.log(parseFloat("0.1 + 0.2"));// Output: 0.1 (does not evaluate expressions)
Using Unary operator +
:
Works like
Number()
but is shorter.Converts booleans, strings,
null
, andundefined
.
console.log(+"42"); // Output: 42 (string β number)
console.log(+"42.99"); // Output: 42.99
console.log(+"abc"); // Output: NaN (invalid string)
console.log(+true); // Output: 1 (true β 1)
console.log(+false); // Output: 0 (false β 0)
console.log(+null); // Output: 0 (null β 0)
console.log(+undefined); // Output: NaN (undefined β NaN)
console.log(+[]); // Output: 0 (empty array)
console.log(+[10]); // Output: 10 (single number in array)
console.log(+{}); // Output: NaN (object cannot be converted)
**conversion of other Data Type to β Boolean :**JavaScript allows the conversion of different data types to Boolean (true
or false
). This is useful in conditional statements, logical operations, and truthy/falsy evaluations.
Using Boolean()
console.log(Boolean(42)); // true
console.log(Boolean(0)); // false
console.log(Boolean(-0)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean("Hello")); // true
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined));// false
console.log(Boolean([])); // true (empty array)
console.log(Boolean({})); // true (empty object)
console.log(Boolean(function(){})); // true (function)
console.log(Boolean(Symbol("test"))); // true (Symbol)
console.log(Boolean(10n)); // true (non-zero BigInt)
console.log(Boolean(0n)); // false (zero BigInt)
Using Not !! Operator :
Another way to convert values to Boolean is using !!
(double NOT operator).
The first
!
(NOT) converts the value to a Boolean and negates it.The second
!
negates it again, giving the actual Boolean equivalent.
console.log(!!42); // true
console.log(!!0); // false
console.log(!!"Hello"); // true
console.log(!!""); // false
console.log(!![]); // true
console.log(!!{}); // true
console.log(!!null); // false
console.log(!!undefined);// false
console.log(!!NaN); // false
Boolean Conversion in Logical Operations
Using
&&
operatorReturns the first falsy value or the last truthy value if all are truthy.
console.log(42 && "Hello"); // "Hello" (both truthy, returns last one)
console.log(0 && "Hello"); // 0 (first falsy)
console.log("" && 42); // "" (first falsy)
Using
||
operatorReturns the first truthy value or the last falsy value if all are falsy.
console.log(42 || "Hello"); // 42 (first truthy)
console.log(0 || "Hello"); // "Hello" (first truthy)
console.log("" || 0 || false);// false (last falsy)
**conversion of other Data Type to β Strings :**JavaScript allows the conversion of different data types to String. This is useful when displaying data, concatenating values, or formatting output.
There are three main ways to convert a value to a string:
Using
String()
β Explicit conversionUsing
.toString()
β Method available on objectsUsing String Concatenation (
+
) β Implicit conversion
Using String(value)
(explicit convertion)
console.log(String(42)); // "42"
console.log(String(true)); // "true"
console.log(String(false)); // "false"
console.log(String(null)); // "null"
console.log(String(undefined)); // "undefined"
console.log(String(NaN)); // "NaN"
console.log(String(10n)); // "10" (BigInt)
console.log(String([])); // "" (empty array β empty string)
console.log(String([1,2,3])); // "1,2,3" (array β comma-separated string)
console.log(String({})); // "[object Object]" (default object conversion)
console.log(String(Symbol("X"))); // Throws TypeError (Symbols cannot be converted)
Using .toString()
Method
Most objects and primitives (except null
and undefined
) have a .toString()
method.
console.log((42).toString()); // "42"
console.log((true).toString()); // "true"
console.log((false).toString()); // "false"
console.log((10n).toString()); // "10" (BigInt)
console.log([1,2,3].toString()); // "1,2,3"
console.log({}.toString()); // "[object Object]"
console.log(Symbol("X").toString());// "Symbol(X)"
Using Concatenation (+
)
console.log(42 + ""); // "42"
console.log(true + ""); // "true"
console.log(null + ""); // "null"
console.log(undefined + ""); // "undefined"
console.log([1,2,3] + ""); // "1,2,3"
console.log({} + ""); // "[object Object]"
console.log(Symbol("X") + ""); //Throws TypeError (Symbol cannot be converted)
Special Cases
Arrays convert to comma-separated strings.
console.log(String([1,2,3])); // "1,2,3"
console.log([1,2,3] + ""); // "1,2,3"
console.log([].toString()); // "" (empty string)
Objects convert to "[object Object]"
, unless they have a custom toString()
method.
console.log(String({})); // "[object Object]"
console.log(({}).toString()); // "[object Object]"
console.log({ name: "Alice" } + ""); // "[object Object]"
Custom toString()
method:
let person = {
name: "Alice",
toString: function() {
return `Person: ${this.name}`;
}
};
console.log(String(person)); // "Person: Alice"
Symbols cannot be converted to strings directly.
console.log(String(Symbol("test"))); // "Symbol(test)"
console.log(Symbol("test").toString()); // "Symbol(test)"
console.log(Symbol("test") + ""); // TypeError
Operators In JavaScript
Arithmetic Operators
let a = 10, b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.3333
console.log(a % b); // 1
console.log(a ** b); // 1000
Assignment Operators
let x = 10;
x += 5; // x = x + 5 (Now x = 15)
x -= 2; // x = x - 2 (Now x = 13)
x *= 2; // x = x * 2 (Now x = 26)
x /= 2; // x = x / 2 (Now x = 13)
console.log(x);
Comparison Operators
console.log(5 == "5"); // true (loose equality)
console.log(5 === "5"); // false (strict equality)
console.log(5 !== "5"); // true
console.log(10 > 5); // true
console.log(5 <= 3); // false
console.log(null > 0); // false
console.log(null == 0); // false
console.log(null >= 0); // true
The Equality check == and comparisons ><>=<= work differently, Comparisons convert null to a number , treating it as 0, Thatβs why null >= 0 is true , but null > 0 is false
Logical Operators
console.log(true && false); // false
console.log(true || false); // true
console.log(!true); // false
Bitwise Operators
// BITWISE OPERATORS IN JAVASCRIPT
// 1. Bitwise AND (&)
console.log(5 & 3); // 1 (0101 & 0011 = 0001)
console.log(12 & 5); // 4 (1100 & 0101 = 0100)
console.log(7 & 2); // 2 (0111 & 0010 = 0010)
console.log(9 & 3); // 1 (1001 & 0011 = 0001)
console.log(15 & 8); // 8 (1111 & 1000 = 1000)
// 2. Bitwise OR (|)
console.log(5 | 3); // 7 (0101 | 0011 = 0111)
console.log(12 | 5); // 13 (1100 | 0101 = 1101)
console.log(7 | 2); // 7 (0111 | 0010 = 0111)
console.log(9 | 3); // 11 (1001 | 0011 = 1011)
console.log(15 | 8); // 15 (1111 | 1000 = 1111)
// 3. Bitwise XOR (^)
console.log(5 ^ 3); // 6 (0101 ^ 0011 = 0110)
console.log(12 ^ 5); // 9 (1100 ^ 0101 = 1001)
console.log(7 ^ 2); // 5 (0111 ^ 0010 = 0101)
console.log(9 ^ 3); // 10 (1001 ^ 0011 = 1010)
console.log(15 ^ 8); // 7 (1111 ^ 1000 = 0111)
// 4. Bitwise NOT (~)
console.log(~5); // -6 (~0000 0101 = 1111 1010)
console.log(~12); // -13 (~0000 1100 = 1111 0011)
console.log(~7); // -8 (~0000 0111 = 1111 1000)
console.log(~9); // -10 (~0000 1001 = 1111 0110)
console.log(~15); // -16 (~0000 1111 = 1111 0000)
// 5. Left Shift (<<)
console.log(5 << 1); // 10 (0101 << 1 = 1010)
console.log(12 << 2); // 48 (1100 << 2 = 110000)
console.log(7 << 3); // 56 (0111 << 3 = 111000)
console.log(9 << 2); // 36 (1001 << 2 = 100100)
console.log(15 << 1); // 30 (1111 << 1 = 11110)
// 6. Right Shift (>>)
console.log(5 >> 1); // 2 (0101 >> 1 = 0010)
console.log(12 >> 2); // 3 (1100 >> 2 = 0011)
console.log(7 >> 1); // 3 (0111 >> 1 = 0011)
console.log(9 >> 2); // 2 (1001 >> 2 = 0010)
console.log(15 >> 3); // 1 (1111 >> 3 = 0001)
// 7. Unsigned Right Shift (>>>)
console.log(5 >>> 1); // 2 (0101 >>> 1 = 0010)
console.log(12 >>> 2); // 3 (1100 >>> 2 = 0011)
console.log(7 >>> 1); // 3 (0111 >>> 1 = 0011)
console.log(-9 >>> 2); // 1073741821 (Negative numbers become large positive)
console.log(-15 >>> 3); // 536870911
Ternary Operator
let age = 20;
let result = (age >= 18) ? "Adult" : "Minor";
console.log(result); // "Adult"
Type Operators
console.log(typeof "Hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof {}); // "object"
console.log(typeof null); // "object" (special case)
console.log(typeof undefined); // "undefined"
let arr = [1, 2, 3];
console.log(arr instanceof Array); // true
Spread and Rest Operators ...
let numbers = [1, 2, 3];
console.log(...numbers); // 1 2 3
let newArray = [...numbers, 4, 5];
console.log(newArray); // [1, 2, 3, 4, 5]
Nullish Coalescing (??
)
let name = null;
console.log(name ?? "Guest"); // "Guest"
let value = 0;
console.log(value ?? 10); // 0
Optional Chaining (?.
)
let user = { profile: { name: "Alice" } };
console.log(user.profile?.name); // "Alice"
console.log(user.address?.city); // undefined (no error)
Difference Between Heap (non-primitive) and stack (primitive)
Stack (Primitive Data Types)
Used for storing primitive values like
Number
,String
,Boolean
,null
,undefined
,Symbol
, andBigInt
.Stores data in a Last In, First Out (LIFO) manner.
Fast access (takes less memory).
Stored directly in memory, so values are copied when assigned to a new variable.
π Example:
javascriptCopyEditlet a = 10;
let b = a; // b gets a COPY of a
b = 20;
console.log(a); // Output: 10 (a remains unchanged)
Heap (Non-Primitive Data Types)
Used for storing objects, including
Object
,Array
,Function
,Map
,Set
, andClass
.Stored in a dynamic memory (Heap).
Slower access but can hold large data.
Stores references (memory addresses), so changing one variable affects others.
π Example:
javascriptCopyEditlet obj1 = { name: "John" };
let obj2 = obj1; // obj2 gets a REFERENCE to obj1
obj2.name = "Doe";
console.log(obj1.name); // Output: "Doe" (both point to the same memory)
Strings and there Methods
A String in JavaScript is a sequence of characters enclosed in single quotes (''), double quotes (""), or backticks (``).
let str1 = "Hello, World!"; // Double quotes
let str2 = 'JavaScript is fun!'; // Single quotes
let str3 = `Template Literal ${12 + 21}`; // Backticks (for multi-line & expressions)
Way to creating them
// Recommended
let name = "Alice";
console.log(name); // Output: Alice
//Less preferred
let name = new String("Alice");
console.log(name); // Output: [String: 'Alice']
To see all Methods that are available to perform we can in the Prototype chaining ,you can see them
you can see all the methods that are available with it, lets some of the practicality of some properties
Here are commonly used String methods
// ==========================
// πΉ JavaScript Strings Basics
// ==========================
let str1 = "Hello, World!"; // Double quotes
let str2 = 'JavaScript is fun!'; // Single quotes
let str3 = `Template Literal`; // Backticks
console.log(str1, str2, str3);
// ==========================
// πΉ String Properties
// ==========================
console.log(str1.length); // Get length of string
// ==========================
// πΉ Getting a Character
// ==========================
console.log(str1.charAt(1)); // "e"
console.log(str1.charCodeAt(1)); // 101 (Unicode)
console.log(str1[1]); // "e"
// ==========================
// πΉ String Case Conversion
// ==========================
console.log(str1.toUpperCase()); // "HELLO, WORLD!"
console.log(str1.toLowerCase()); // "hello, world!"
// ==========================
// πΉ Searching in Strings
// ==========================
console.log(str1.indexOf("World")); // 7
console.log(str1.lastIndexOf("o")); // 8
console.log(str1.includes("Hello")); // true
console.log(str1.startsWith("Hello")); // true
console.log(str1.endsWith("!")); // true
// ==========================
// πΉ Extracting Part of a String
// ==========================
console.log(str1.slice(0, 5)); // "Hello"
console.log(str1.substring(0, 5)); // "Hello"
console.log(str1.substr(0, 5)); // "Hello" (deprecated)
// ==========================
// πΉ Replacing & Modifying Strings
// ==========================
let msg = "Hello JavaScript!";
console.log(msg.replace("JavaScript", "World")); // "Hello World!"
console.log(msg.replaceAll("o", "0")); // "Hell0 JavaScript!"
console.log(msg.trim()); // Removes whitespace
console.log(msg.padStart(20, "-")); // "--Hello JavaScript!"
console.log(msg.padEnd(20, "-")); // "Hello JavaScript!--"
// ==========================
// πΉ Splitting & Joining Strings
// ==========================
let sentence = "JavaScript is fun";
let words = sentence.split(" ");
console.log(words); // ["JavaScript", "is", "fun"]
let newSentence = words.join(" - ");
console.log(newSentence); // "JavaScript - is - fun"
// ==========================
// πΉ String Comparisons
// ==========================
console.log("apple" === "apple"); // true
console.log("apple" === "Apple"); // false
console.log("banana".localeCompare("apple")); // 1 (banana > apple)
// ==========================
// πΉ Escape Characters
// ==========================
let text = "Hello\nJavaScript\tis fun!";
console.log(text);
// ==========================
// πΉ Template Literals (Backticks ``)
// ==========================
let name = "Alice";
let age = 25;
console.log(`My name is ${name} and I am ${age} years old.`);
// ==========================
// πΉ Full String Operations Example
// ==========================
let str = " JavaScript is awesome ";
console.log(str.toUpperCase());
console.log(str.includes("awesome"));
console.log(str.slice(0, 10));
console.log(str.replace("awesome", "great"));
console.log(str.trim());
console.log(str.split(" "));
All String Methods
// JavaScript String Methods - Comprehensive Guide
let str = "Hello, JavaScript!";
// 1. anchor() - Creates an HTML anchor
console.log(str.anchor("myAnchor")); // <a name="myAnchor">Hello, JavaScript!</a>
// 2. at() - Returns the character at a specified index
console.log(str.at(7)); // J
// 3. big() - Displays text in big font
console.log(str.big()); // <big>Hello, JavaScript!</big>
// 4. blink() - Displays blinking text (Deprecated)
console.log(str.blink());
// 5. bold() - Displays text in bold
console.log(str.bold()); // <b>Hello, JavaScript!</b>
// 6. charAt() - Returns the character at a specified index
console.log(str.charAt(0)); // H
// 7. charCodeAt() - Returns Unicode of a character at a specified index
console.log(str.charCodeAt(0)); // 72
// 8. codePointAt() - Returns Unicode of character at index
console.log(str.codePointAt(0)); // 72
// 9. concat() - Joins two or more strings
console.log(str.concat(" Welcome!")); // Hello, JavaScript! Welcome!
// 10. endsWith() - Checks if a string ends with a specific substring
console.log(str.endsWith("JavaScript!")); // true
// 11. fixed() - Displays text in fixed-width font
console.log(str.fixed());
// 12. fontcolor() - Changes text color
console.log(str.fontcolor("red"));
// 13. fontsize() - Changes text font size
console.log(str.fontsize(5));
// 14. includes() - Checks if string contains a specified value
console.log(str.includes("Java")); // true
// 15. indexOf() - Returns the index of the first occurrence of a specified value
console.log(str.indexOf("o")); // 4
// 16. isWellFormed() - Checks if the string is well-formed
console.log(str.isWellFormed()); // true
// 17. italics() - Displays text in italics
console.log(str.italics());
// 18. lastIndexOf() - Returns the last occurrence index of a specified value
console.log(str.lastIndexOf("o")); // 4
// 19. link() - Creates a hyperlink
console.log(str.link("https://example.com"));
// 20. localeCompare() - Compares two strings in the current locale
console.log(str.localeCompare("Hello, JavaScript!")); // 0
// 21. match() - Searches for a match in a string
console.log(str.match(/JavaScript/)); // ["JavaScript"]
// 22. matchAll() - Returns all matches
console.log([...str.matchAll(/a/g)]);
// 23. normalize() - Normalizes Unicode characters
console.log(str.normalize());
// 24. padEnd() - Pads the end of the string
console.log(str.padEnd(25, "*"));
// 25. padStart() - Pads the start of the string
console.log(str.padStart(25, "*"));
// 26. repeat() - Repeats the string
console.log(str.repeat(2));
// 27. replace() - Replaces a substring
console.log(str.replace("JavaScript", "JS"));
// 28. replaceAll() - Replaces all occurrences of a substring
console.log(str.replaceAll("o", "0"));
// 29. search() - Searches for a substring
console.log(str.search("Java")); // 7
// 30. slice() - Extracts part of a string
console.log(str.slice(0, 5)); // Hello
// 31. small() - Displays text in small font
console.log(str.small());
// 32. split() - Splits string into an array
console.log(str.split(","));
// 33. startsWith() - Checks if a string starts with a specific substring
console.log(str.startsWith("Hello")); // true
// 34. strike() - Creates strikethrough text
console.log(str.strike());
// 35. sub() - Displays text as subscript
console.log(str.sub());
// 36. substr() - Extracts a substring (Deprecated)
console.log(str.substr(0, 5)); // Hello
// 37. substring() - Extracts a substring
console.log(str.substring(0, 5)); // Hello
// 38. sup() - Displays text as superscript
console.log(str.sup());
// 39. toLocaleLowerCase() - Converts string to lowercase (locale-specific)
console.log(str.toLocaleLowerCase());
// 40. toLocaleUpperCase() - Converts string to uppercase (locale-specific)
console.log(str.toLocaleUpperCase());
// 41. toLowerCase() - Converts string to lowercase
console.log(str.toLowerCase());
// 42. toString() - Converts string object to string
console.log(str.toString());
// 43. toUpperCase() - Converts string to uppercase
console.log(str.toUpperCase());
// 44. toWellFormed() - Returns a well-formed version of the string
console.log(str.toWellFormed());
// 45. trim() - Removes whitespace from both sides
console.log(" Hello ".trim());
// 46. trimEnd() - Removes whitespace from end
console.log(" Hello ".trimEnd());
// 47. trimStart() - Removes whitespace from start
console.log(" Hello ".trimStart());
// 48. valueOf() - Returns primitive string value
console.log(str.valueOf());
Numbers and Math
n JavaScript, numbers are a fundamental data type that represents both integers and floating-point values. Although numbers are primitives (meaning they arenβt objects), JavaScript automatically βwrapsβ them in a Number object when you call methods on them
Declaration
Number Primitives:
Most of the time, youβll work with numbers as simple values. For example:let a = 42; let b = 3.14;
These are primitive numeric values.
Number Objects:
When you call a method on a numeric literal, JavaScript internally converts it into a Number object. You can also create a Number object explicitly (though itβs rarely needed):let numObj = new Number(42); console.log(typeof numObj); // "object"
However, using the object wrapper is generally discouraged because it can lead to unexpected behavior. Instead, use number primitives.
Below are the functions you can use on a number
// numberExamples.js
// This file demonstrates various JavaScript Number methods and constructors using the value 22.
// 1. Using the Number constructor as a function
// Returns a number primitive.
console.log(Number("22")); // Output: 22 (type: number)
// 2. Using the Number constructor with new
// Returns a Number object wrapping the primitive value.
console.log(new Number(22)); // Output: [Number: 22] (type: object)
// 3. toExponential() Method
// Returns a string representing the number in exponential notation.
console.log((22).toExponential(2)); // Output: "2.20e+1" (type: string)
// 4. toFixed() Method
// Returns a string representing the number in fixed-point notation.
console.log((22).toFixed(2)); // Output: "22.00" (type: string)
// 5. toLocaleString() Method
// Returns a string with a language-sensitive representation of the number.
console.log((22).toLocaleString()); // Output: "22" (type: string)
// 6. toPrecision() Method
// Returns a string representing the number to the specified precision.
console.log((22).toPrecision(3)); // Output: "22.0" (type: string)
// 7. toString() Method
// Returns a string representing the number (optionally with a specified radix).
console.log((22).toString()); // Output: "22" (type: string)
// 8. valueOf() Method
// Returns the primitive number value of a Number object.
console.log((new Number(22)).valueOf()); // Output: 22 (type: number)
To see More functions That can be made use Number
keyword and add .
to see all options
Another And most useful is Math
. It is in Build library , have more useful methods / functions. it can be accessed using .
// mathExamples.js
// This file demonstrates various Math methods (excluding trigonometric functions).
// Constants
console.log(Math.E); // Euler's number (2.718281828459045)
console.log(Math.LN2); // Natural logarithm of 2 (0.693147...)
console.log(Math.LN10); // Natural logarithm of 10 (2.30258...)
console.log(Math.LOG2E); // Base-2 logarithm of E (1.44269...)
console.log(Math.LOG10E); // Base-10 logarithm of E (0.43429...)
console.log(Math.PI); // PI (3.14159...)
console.log(Math.SQRT1_2); // Square root of 1/2 (0.70710...)
console.log(Math.SQRT2); // Square root of 2 (1.41421...)
// Absolute value
console.log(Math.abs(-42)); // 42
// Cube root
console.log(Math.cbrt(27)); // 3
//
// Rounding functions
console.log(Math.ceil(4.2)); // 5 (rounds up)
console.log(Math.floor(4.9)); // 4 (rounds down)
console.log(Math.round(4.5)); // 5 (rounds to nearest)
console.log(Math.trunc(4.9)); // 4 (removes decimal part)
// Clz32 (count leading zeros in 32-bit integer)
console.log(Math.clz32(1)); // 31
// Exponential and logarithmic functions
console.log(Math.exp(1)); // e^1
console.log(Math.expm1(1)); // e^1 - 1
console.log(Math.log(10)); // Natural log (ln 10)
console.log(Math.log1p(9)); // ln(1 + 9)
console.log(Math.log2(8)); // Log base 2 (logβ8)
console.log(Math.log10(100)); // Log base 10 (logββ100)
// Maximum and minimum values
console.log(Math.max(1, 5, 10, -3)); // 10
console.log(Math.min(1, 5, 10, -3)); // -3
// Power and square root
console.log(Math.pow(2, 3)); // 2^3 = 8
console.log(Math.sqrt(16)); // Square root of 16 = 4
// Random number generation
console.log(Math.random()); // Random number between 0 and 1
// to get Random number between two range
const min = 12
const max = 99
console.log(Math.floor(Math.random()*(max-min+1)+min)
Date and Time
The Date
object in JavaScript is used to work with dates and times. It provides various methods to get, set, and manipulate date and time values.
Creating a Date Object
// 1. Create a new Date object with the current date and time
console.log(new Date());
// 2. Create a Date object with a specific date and time (YYYY, MM (0-based), DD, HH, MM, SS, MS)
console.log(new Date(2024, 1, 9, 10, 30, 0));
// 3. Create a Date object from a timestamp (milliseconds since Jan 1, 1970)
console.log(new Date(1707475200000));
// 4. Create a Date object from an ISO date string
console.log(new Date("2024-02-09T10:30:00Z"));
To see the current time in milliseconds
console.log(Date.now()) //1707475200000
Get the Date Methods
let now = new Date();
console.log(now.getFullYear()); // Get full year (e.g., 2024)
console.log(now.getMonth()); // Get month (0-based, Jan = 0)
console.log(now.getDate()); // Get day of the month (1-31)
console.log(now.getDay()); // Get day of the week (0 = Sunday, 6 = Saturday)
console.log(now.getHours()); // Get hours (0-23)
console.log(now.getMinutes()); // Get minutes (0-59)
console.log(now.getSeconds()); // Get seconds (0-59)
console.log(now.getMilliseconds()); // Get milliseconds (0-999)
console.log(now.getTime()); // Get timestamp (milliseconds since Jan 1, 1970)
console.log(now.getTimezoneOffset()); // Get timezone difference in minutes
Set the Date Methods
let date = new Date();
date.setFullYear(2025);
date.setMonth(6); // Set month to July (0-based)
date.setDate(15); // Set day of the month
date.setHours(14); // Set hours (2 PM)
date.setMinutes(45); // Set minutes
date.setSeconds(30); // Set seconds
date.setMilliseconds(500); // Set milliseconds
date.setTime(1710000000000); // Set timestamp (in milliseconds)
console.log(date);
Date formatting Methods
let d = new Date();
console.log(d.toDateString()); // Short date format (e.g., "Fri Feb 09 2024")
console.log(d.toTimeString()); // Time format (e.g., "10:30:00 GMT+0000")
console.log(d.toLocaleDateString()); // Localized date (e.g., "2/9/2024")
console.log(d.toLocaleTimeString()); // Localized time (e.g., "10:30:00 AM")
console.log(d.toISOString()); // ISO format (e.g., "2024-02-09T10:30:00.000Z")
console.log(d.toUTCString()); // UTC format (e.g., "Fri, 09 Feb 2024 10:30:00 GMT")
console.log(d.toJSON()); // JSON format (ISO string)
Working with Time Differences
let start = new Date("2024-02-01");
let end = new Date("2024-02-10");
let diff = end - start; // Difference in milliseconds
console.log(diff / (1000 * 60 * 60 * 24)); // Convert to days (Output: 9)
Arrays
an array is a special type of object used to store multiple values in a single variable. It is ordered, zero-indexed, and can contain elements of different data types (numbers, strings, objects, or even other arrays).
Array Declaration
Array literal (Recommended)
let fruits = ["Apple", "Banana", "Cherry"];
Using the
new Array()
constructorlet numbers = new Array(1, 2, 3, 4);
In JavaScript, an array is a special type of object used to store multiple values in a single variable. It is ordered, zero-indexed, and can contain elements of different data types (numbers, strings, objects, or even other arrays).
Declaring an Array
You can create an array using:
Array literal (Recommended)
let fruits = ["Apple", "Banana", "Cherry"];
Using the
new Array()
constructorlet numbers = new Array(1, 2, 3, 4);
Accessing Elements
Each element in an array has an index, starting from 0.
console.log(fruits[0]); // Output: Apple
console.log(fruits[1]); // Output: Banana
Common Array Methods
push()
β Adds element(s) to the endfruits.push("Orange"); // ["Apple", "Banana", "Cherry", "Orange"]
pop()
β Removes the last elementfruits.pop(); // ["Apple", "Banana", "Cherry"]
shift()
β Removes the first elementfruits.shift(); // ["Banana", "Cherry"]
unshift()
β Adds element(s) to the beginningfruits.unshift("Mango"); // ["Mango", "Banana", "Cherry"]
length
β Returns the number of elementsconsole.log(fruits.length); // Output: 3
forEach()
β Loops through elementsfruits.forEach((fruit) => console.log(fruit));
map()
β Creates a new array by applying a functionlet upperCaseFruits = fruits.map(fruit => fruit.toUpperCase());
filter()
β Returns elements that match a conditionlet filteredFruits = fruits.filter(fruit => fruit.length > 5);
find()
β Finds the first matching elementlet result = fruits.find(fruit => fruit.startsWith("B")); // "Banana"
includes()
β Checks if an element existsconsole.log(fruits.includes("Apple")); // true
Multidimensional Array
JavaScript also supports arrays within arrays.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][2]); // Output: 6
To see all methods that can be implemented with array you can see the prototype of it.
π’ Access & Information Methods
These methods donβt modify the original array.
1. at(index)
- Returns: Element (or
undefined
if out of bounds)
let arr = [10, 20, 30];
console.log(arr.at(1)); // 20
console.log(arr.at(-1)); // 30 (supports negative index)
2. includes(value)
- Returns:
Boolean
(true if value exists, false otherwise)
let arr = [10, 20, 30];
console.log(arr.includes(20)); // true
console.log(arr.includes(50)); // false
3. indexOf(value)
- Returns:
Number
(index of first match, or-1
if not found)
let arr = [10, 20, 30];
console.log(arr.indexOf(20)); // 1
console.log(arr.indexOf(50)); // -1
4. lastIndexOf(value)
- Returns:
Number
(last occurrence index, or-1
if not found)
let arr = [10, 20, 30, 20];
console.log(arr.lastIndexOf(20)); // 3
5. entries()
- Returns:
Iterator<[index, value]>
let arr = ["a", "b", "c"];
for (let [index, value] of arr.entries()) {
console.log(index, value);
}
// 0 "a"
// 1 "b"
// 2 "c"
π‘ Array Modification Methods
These methods change the original array.
6. push(value1, value2, β¦)
Modifies Original? β Yes
Returns:
Number
(new array length)
let arr = [10, 20];
console.log(arr.push(30)); // 3
console.log(arr); // [10, 20, 30]
7. pop()
Modifies Original? β Yes
Returns: Removed element (or
undefined
if empty)
let arr = [10, 20, 30];
console.log(arr.pop()); // 30
console.log(arr); // [10, 20]
8. shift()
Modifies Original? β Yes
Returns: Removed first element (or
undefined
if empty)
let arr = [10, 20, 30];
console.log(arr.shift()); // 10
console.log(arr); // [20, 30]
9. unshift(value1, value2, β¦)
Modifies Original? β Yes
Returns:
Number
(new array length)
let arr = [20, 30];
console.log(arr.unshift(10)); // 3
console.log(arr); // [10, 20, 30]
10. splice(start, deleteCount, item1, item2, β¦)
Modifies Original? β Yes
Returns:
Array
(removed elements)
let arr = [10, 20, 30, 40];
console.log(arr.splice(1, 2, 99, 100)); // [20, 30] (removed elements)
console.log(arr); // [10, 99, 100, 40]
11. fill(value, start?, end?)
Modifies Original? β Yes
Returns:
Array
(mutated)
let arr = [1, 2, 3, 4];
console.log(arr.fill(0, 1, 3)); // [1, 0, 0, 4]
π’ Functional Programming Methods
These methods donβt modify the original array.
12. map(callback)
- Returns:
Array
let arr = [1, 2, 3];
console.log(arr.map(n => n * 2)); // [2, 4, 6]
13. filter(callback)
- Returns:
Array
(elements that pass test)
let arr = [10, 20, 30];
console.log(arr.filter(n => n > 15)); // [20, 30]
14. reduce(callback, initialValue?)
- Returns: Accumulated value
let arr = [1, 2, 3, 4];
console.log(arr.reduce((sum, n) => sum + n, 0)); // 10
15. find(callback)
- Returns: First matched element (or
undefined
if none found)
let arr = [10, 20, 30];
console.log(arr.find(n => n > 15)); // 20
16. findIndex(callback)
- Returns:
Number
(index of first match, or-1
)
let arr = [10, 20, 30];
console.log(arr.findIndex(n => n > 15)); // 1
Chaining
- Returns: The number after the computation on each level
let arr=[1,2,3,4,5,6,7,8,9,10];
consat newNumbers = arr.map((a)=> a*10)
.map((a)=>a+1)
.filter((a)=>a>50)
console.log(newNumbers) // 51,61,71,81,91,101
π‘ Sorting & Reordering Methods
These methods change the array, except toSorted()
.
17. sort(compareFn?)
Modifies Original? β Yes
Returns:
Array
(sorted)
let arr = [30, 10, 20];
console.log(arr.sort((a, b) => a - b)); // [10, 20, 30]
18. toSorted(compareFn?)
- Returns:
Array
(sorted copy)
let arr = [30, 10, 20];
console.log(arr.toSorted((a, b) => a - b)); // [10, 20, 30]
console.log(arr); // [30, 10, 20] (original remains unchanged)
19. reverse()
Modifies Original? β Yes
Returns:
Array
(reversed)
let arr = [10, 20, 30];
console.log(arr.reverse()); // [30, 20, 10]
20. toReversed()
- Returns:
Array
(reversed copy)
let arr = [10, 20, 30];
console.log(arr.toReversed()); // [30, 20, 10]
console.log(arr); // [10, 20, 30] (original remains unchanged)
π’ Other Methods
21. join(separator?)
- Returns:
String
let arr = ["a", "b", "c"];
console.log(arr.join("-")); // "a-b-c"
22. slice(start?, end?)
- Returns:
Array
(copy of selected portion)
let arr = [10, 20, 30, 40];
console.log(arr.slice(1, 3)); // [20, 30]
π― Summary
Method | Returns | Mutates? |
pop(), shift() | Removed item | β Yes |
push(), unshift() | New length | β Yes |
slice() | New array | β No |
map(), filter() | New array | β No |
find(), findIndex() | Element / Index | β No |
sort(), reverse() | Sorted / Reversed Array | β Yes |
JavaScript provides two special methods, Array.from()
and Array.of()
, for creating arrays in different ways.
Array.from()
and Array.of()
in JavaScript
JavaScript provides two special methods, Array.from()
and Array.of()
, for creating arrays in different ways.
1. Array.from()
The Array.from()
method creates a new array from an iterable (like a string, Set, Map, or NodeList) or an array-like object (like arguments
).
Syntax
Array.from(iterable, mapFunction, thisArg)
iterable β The object to convert into an array.
mapFunction (optional) β Function to apply to each element.
thisArg (optional) β Value to use as
this
inmapFunction
.
Examples
Convert a string into an array
let str = "hello"; let arr = Array.from(str); console.log(arr); // ["h", "e", "l", "l", "o"]
Convert a Set into an array
let set = new Set([1, 2, 3, 4]); let arr = Array.from(set); console.log(arr); // [1, 2, 3, 4]
Convert
arguments
into an arrayfunction example() { let arr = Array.from(arguments); console.log(arr); } example(1, 2, 3); // [1, 2, 3]
Using
mapFunction
let doubled = Array.from([1, 2, 3], x => x * 2); console.log(doubled); // [2, 4, 6]
2. Array.of()
The Array.of()
method creates a new array from a given set of values.
Syntax
Array.of(element1, element2, ..., elementN)
- Creates an array with the specified elements.
Examples
Create an array from individual values
let arr = Array.of(1, 2, 3, 4); console.log(arr); // [1, 2, 3, 4]
Difference between
Array.of()
andnew Array()
let arr1 = Array.of(5); // [5] (creates an array with a single element) let arr2 = new Array(5); // [empty Γ 5] (creates an empty array with length 5) console.log(arr1); // [5] console.log(arr2); // [empty Γ 5]
Key Differences
Feature | Array.from() | Array.of() |
Converts an iterable or array-like object into an array | β | β |
Creates an array from individual values | β | β |
Accepts a mapping function | β | β |
Handles special cases differently than new Array() | β | β |
Objects
At its core, a JavaScript object is a collection of properties. Each property is defined as a key (also called a βproperty nameβ) paired with a value. The keys are typically strings (or symbols), and the values can be any data type including numbers, strings, functions, or even other objects.
let person = {
name: "Alice",
age: 30,
isStudent: false
};
Objects can be Nested and contain array, other datatypes and functions
const company = {
name: "TechCorp",
location: "San Francisco",
// Nested object for departments
departments: {
engineering: {
head: "Alice",
// Array of team objects inside the engineering department
teams: [
{
name: "Backend",
lead: "Bob",
projects: ["API Development", "Database Optimization"]
},
{
name: "Frontend",
lead: "Charlie",
projects: ["UI Revamp", "Performance Enhancement"]
}
]
},
sales: {
head: "Diana",
// Array of team objects inside the sales department
teams: [
{
name: "Domestic",
lead: "Eve",
region: "USA"
},
{
name: "International",
lead: "Frank",
region: "Global"
}
]
}
},
// Array of employee objects at the company level
employees: [
{ id: 1, name: "Alice", department: "engineering" },
{ id: 2, name: "Bob", department: "engineering" },
{ id: 3, name: "Charlie", department: "engineering" },
{ id: 4, name: "Diana", department: "sales" },
{ id: 5, name: "Eve", department: "sales" },
{ id: 6, name: "Frank", department: "sales" }
],
// A method that returns a brief company description
getCompanyInfo() {
return `${this.name} is located in ${this.location} and has multiple departments including Engineering and Sales.`;
},
// A method to get department details by name
getDepartmentDetails(deptName) {
const dept = this.departments[deptName];
if (dept) {
return dept;
} else {
return `Department ${deptName} does not exist.`;
}
}
};
// Accessing top-level properties
console.log(company.name); // "TechCorp"
console.log(company.location); // "San Francisco"
// Calling a method on the object
console.log(company.getCompanyInfo());
// Output: "TechCorp is located in San Francisco and has multiple departments including Engineering and Sales."
// Accessing nested objects: Get engineering department details
console.log(company.departments.engineering.head); // "Alice"
Accessing of Objects ,we can access them using the .
and objectName[βkeyβ]
,for the special case of symbols we declare they with brackets [id]
let CarId = new Symbol('mySymbol')
let car ={
name:"BMW x7",
"boot space":"400L",
[id]:CarId
}
console.log(car.name) // BMW x7
console.log(car["boot space"]) //400l
console.log(car[id]) // mySymbol
// combaining two objects
let obj1 = {one:1,two:2}
let obj2 = {three:3,four:4}
// option 1
let obj3 = {...obj1,...obj2}
// option 2
obj3 = Object.assign({},obj1,obj2)
console.log(obj3)
CRUD Operation on Objects
// objectOperations.js
// 1. Creating a Simple Object
let person = {
name: "Alice",
age: 30
};
console.log("Initial person:", person);
// Output: { name: 'Alice', age: 30 }
// 2. Adding and Updating Properties
// Using Dot Notation:
// Add a new property 'email'
person.email = "alice@example.com";
// Update an existing property 'age'
person.age = 31;
// Using Bracket Notation:
// Add a new property 'isStudent'
person["isStudent"] = false;
// Update an existing property 'name'
person["name"] = "Alicia";
console.log("After adding/updating properties:", person);
// Output: { name: 'Alicia', age: 31, email: 'alice@example.com', isStudent: false }
// 3. Deleting a Property
delete person.isStudent;
console.log("After deleting 'isStudent':", person);
// Output: { name: 'Alicia', age: 31, email: 'alice@example.com' }
// 4. Adding Multiple Properties with Object.assign()
Object.assign(person, { occupation: "Developer", city: "New York" });
console.log("After merging additional properties:", person);
// Output: { name: 'Alicia', age: 31, email: 'alice@example.com', occupation: 'Developer', city: 'New York' }
// 5. Iterating Over Object Properties
// Using for...in Loop (with hasOwnProperty check)
console.log("Iterating using for...in loop:");
for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(`${key}: ${person[key]}`);
}
}
// Using Object.keys(), Object.values(), and Object.entries()
console.log("Object.keys():", Object.keys(person));
// e.g., [ 'name', 'age', 'email', 'occupation', 'city' ]
console.log("Object.values():", Object.values(person));
// e.g., [ 'Alicia', 31, 'alice@example.com', 'Developer', 'New York' ]
console.log("Object.entries():", Object.entries(person));
// e.g., [ ['name', 'Alicia'], ['age', 31], ['email', 'alice@example.com'], ['occupation', 'Developer'], ['city', 'New York'] ]
// 6. Freezing an Object with Object.freeze()
// Freeze the person object to make it immutable
Object.freeze(person);
// to UnFreze use deepcopy or shallow copy
// Attempt to modify a property (this change will be ignored in non-strict mode,
// or throw an error in strict mode)
person.age = 40;
console.log("After freeze, attempting to modify 'age':", person.age);
// Output: 31 (remains unchanged)
// 7. Sealing an Object with Object.seal()
// Create a new object 'car'
let car = {
make: "Toyota",
model: "Corolla"
};
Object.seal(car);
// Update an existing property (allowed)
car.model = "Camry";
// Attempt to add a new property (won't work)
car.year = 2020;
// Attempt to delete a property (won't work)
delete car.make;
console.log("Sealed car object:", car);
// Output: { make: 'Toyota', model: 'Camry' }
// Note: With a sealed object, you can modify existing properties if they're writable,
// but you cannot add or remove properties.
Copy of Objects Deep and Shallow copy
Shallow Copy Methods:
Using
Object.assign()
Using the spread operator (
...
)
Deep Copy Methods:
Using
JSON.parse(JSON.stringify(obj))
(with limitations)Using a custom deep-clone function that handles nested objects (and arrays, dates, etc
// copyObjectMethods.js
// Example object with nested objects and arrays
const original = {
name: "Alice",
age: 30,
address: {
city: "New York",
zip: "10001"
},
hobbies: ["reading", "coding"],
createdAt: new Date("2025-01-01")
};
console.log("Original object:", original);
// ==========================================
// 1. Shallow Copy Methods
// ==========================================
// Method 1: Using Object.assign()
// This creates a new object and copies all enumerable own properties.
// Note: Nested objects are still referenced, not copied.
const copyUsingAssign = Object.assign({}, original);
// Method 2: Using the Spread Operator
// Similar to Object.assign, it copies top-level properties only.
const copyUsingSpread = { ...original };
// ==========================================
// 2. Deep Copy Methods
// ==========================================
// Method 3: Using JSON.parse(JSON.stringify(obj))
// This works well for objects that contain JSON-safe values (no functions, Dates, etc.).
// Note: Dates become strings, functions are lost, and special objects are not handled.
const deepCopyUsingJSON = JSON.parse(JSON.stringify(original));
// Method 4: Custom Deep Clone Function
// This function recursively copies all nested properties.
function deepClone(obj) {
// Return the value if obj is not an object
if (obj === null || typeof obj !== 'object') {
return obj;
}
// Handle Date objects
if (obj instanceof Date) {
return new Date(obj.getTime());
}
// Handle Arrays
if (Array.isArray(obj)) {
return obj.map(item => deepClone(item));
}
// Handle plain objects
const clonedObj = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
clonedObj[key] = deepClone(obj[key]);
}
}
return clonedObj;
}
const deepCopyCustom = deepClone(original);
// ==========================================
// 3. Demonstrate the Differences
// ==========================================
// Modify the original object to see the impact on the copies
original.name = "Bob";
original.address.city = "Los Angeles";
original.hobbies.push("gaming");
original.createdAt.setFullYear(2030);
console.log("\nAfter modifying the original object:");
console.log("Modified Original:", original);
console.log("\nShallow copy using Object.assign():", copyUsingAssign);
console.log("Shallow copy using Spread Operator:", copyUsingSpread);
console.log("Deep copy using JSON:", deepCopyUsingJSON);
console.log("Deep copy using custom deepClone():", deepCopyCustom);
/*
Expected Observations:
- Shallow copies (copyUsingAssign and copyUsingSpread):
* The top-level properties are copied at the time of copying.
* However, nested objects (like address) and arrays (like hobbies) are still references.
Changing original.address.city or original.hobbies affects these shallow copies.
- Deep copy using JSON:
* It creates a completely new copy of the object.
* Limitations: The 'createdAt' Date property becomes a string instead of a Date object.
- Deep copy using custom deepClone():
* It creates a completely new copy, preserving nested structures.
* It handles Date objects correctly, so original.createdAt remains a Date in the copy.
*/
We can use the following methods on Objects
// 1. hasOwnProperty()
console.log("1. hasOwnProperty()");
const obj1 = { name: "Alice", age: 30 };
console.log(obj1.hasOwnProperty("name")); // true
console.log(obj1.hasOwnProperty("toString")); // false (inherited)
console.log("----------------------------------------------------------");
// 2. isPrototypeOf()
console.log("2. isPrototypeOf()");
function Person() {}
const p1 = new Person();
console.log(Person.prototype.isPrototypeOf(p1)); // true
console.log("----------------------------------------------------------");
// 3. propertyIsEnumerable()
console.log("3. propertyIsEnumerable()");
console.log(obj1.propertyIsEnumerable("name")); // true
console.log(Object.prototype.propertyIsEnumerable("toString")); // false
console.log("----------------------------------------------------------");
// 4. toLocaleString()
console.log("4. toLocaleString()");
const date = new Date();
console.log(date.toLocaleString()); // Example output: "2/10/2025, 10:34:21 AM"
console.log("----------------------------------------------------------");
// 5. toString()
console.log("5. toString()");
const arr = [1, 2, 3];
console.log(arr.toString()); // "1,2,3"
const obj2 = {};
console.log(obj2.toString()); // "[object Object]"
console.log("----------------------------------------------------------");
// 6. valueOf()
console.log("6. valueOf()");
const num = new Number(100);
console.log(num.valueOf()); // 100
console.log("----------------------------------------------------------");
// 7. __defineGetter__() (Deprecated)
console.log("7. __defineGetter__() (Deprecated)");
const obj3 = {};
obj3.__defineGetter__("name", function () {
return "Alice";
});
console.log(obj3.name); // "Alice"
console.log("----------------------------------------------------------");
// 8. __defineSetter__() (Deprecated)
console.log("8. __defineSetter__() (Deprecated)");
const obj4 = {};
obj4.__defineSetter__("age", function (val) {
this._age = val * 2;
});
obj4.age = 10;
console.log(obj4._age); // 20
console.log("----------------------------------------------------------");
// 9. __lookupGetter__() (Deprecated)
console.log("9. __lookupGetter__() (Deprecated)");
const obj5 = {
get name() {
return "Alice";
},
};
console.log(obj5.__lookupGetter__("name")); // Function reference
console.log("----------------------------------------------------------");
// 10. __lookupSetter__() (Deprecated)
console.log("10. __lookupSetter__() (Deprecated)");
const obj6 = {
set age(val) {
this._age = val * 2;
},
};
console.log(obj6.__lookupSetter__("age")); // Function reference
console.log("----------------------------------------------------------");
// 11. __proto__ (Getter & Setter)
console.log("11. __proto__ (Getter & Setter)");
const obj7 = {};
const protoObj = { greet: "Hello" };
obj7.__proto__ = protoObj;
console.log(obj7.greet); // "Hello"
console.log("----------------------------------------------------------");
console.log("===== End of Examples =====");
Object Destructuring and JSON
Object destructuring allows extracting properties from objects into variables easily.
// Example Object
const user = {
name: "Alice",
age: 25,
address: {
city: "New York",
zip: "10001"
}
};
// Basic Destructuring
const { name, age } = user;
console.log(name); // "Alice"
console.log(age); // 25
// Nested Destructuring
const { address: { city, zip } } = user;
console.log(city); // "New York"
console.log(zip); // "10001"
// Destructuring with Default Values
const { country = "USA" } = user;
console.log(country); // "USA"
// Renaming Variables
const { name: userName, age: userAge } = user;
console.log(userName, userAge); // "Alice", 25
JSON is a format used to store and exchange data.
Converting Object to JSON (JSON.stringify
)
const jsonString = JSON.stringify(user);
console.log(jsonString);
// Output: '{"name":"Alice","age":25,"address":{"city":"New York","zip":"10001"}}'
Converting JSON to Object (JSON.parse
)
const parsedData = JSON.parse(jsonString);
console.log(parsedData.name); // "Alice"
console.log(parsedData.address.city); // "New York"
Complete Example
const product = {
id: 101,
name: "Laptop",
price: 999,
specs: {
processor: "Intel i7",
ram: "16GB"
}
};
// Destructuring
const { id, name: productName, specs: { processor, ram } } = product;
console.log(productName, processor, ram); // "Laptop Intel i7 16GB"
// Convert to JSON and back
const productJSON = JSON.stringify(product);
console.log("JSON String:", productJSON);
const parsedProduct = JSON.parse(productJSON);
console.log("Parsed Object:", parsedProduct);
Functions
π 1. Function Basics
A function is a reusable block of code that performs a task.
function greet() {
console.log("Hello, world!");
}
greet(); // "Hello, world!"
πΉ Function with Parameters
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Alice"); // "Hello, Alice!"
πΉ Function with Return Value
function add(a, b) {
return a + b;
}
const sum = add(5, 3);
console.log(sum); // 8
π 2. Function Types
πΉ Function Declaration (Named Function)
function multiply(a, b) {
return a * b;
}
console.log(multiply(4, 2)); // 8
πΉ Function Expression (Anonymous Function)
const divide = function (a, b) {
return a / b;
};
console.log(divide(10, 2)); // 5
πΉ Arrow Function (ES6)
const square = (n) => n * n;
console.log(square(5)); // 25
Single-line arrow functions implicitly return values.
For multiple statements, use
{}
andreturn
.
const power = (base, exponent) => {
return base ** exponent;
};
console.log(power(2, 3)); // 8
π 3. Function Parameters
πΉ Default Parameters
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // "Hello, Guest!"
greet("Bob"); // "Hello, Bob!"
πΉ Rest Parameters (...args
)
Used to accept multiple arguments as an array.
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
πΉ Spread Operator (...
)
Used to pass array elements as function arguments.
const numbers = [5, 6, 7];
console.log(Math.max(...numbers)); // 7
π 4. Function Scope & Hoisting
πΉ Local vs Global Scope
let globalVar = "I am global";
function testScope() {
let localVar = "I am local";
console.log(globalVar); // Accessible
console.log(localVar); // Accessible
}
testScope();
console.log(globalVar); // Accessible
// console.log(localVar); // β Error: localVar is not defined
πΉ Function Hoisting
Function declarations are hoisted (can be called before definition), but function expressions are not.
hoistedFunction(); // Works!
function hoistedFunction() {
console.log("This function is hoisted!");
}
// notHoistedFunction(); // β Error
const notHoistedFunction = function () {
console.log("This is not hoisted.");
};
π 5. Closures
A closure is when a function retains access to its outer scope even after the outer function has finished execution.
function outerFunction(outerValue) {
return function innerFunction(innerValue) {
console.log(`Outer: ${outerValue}, Inner: ${innerValue}`);
};
}
const closureExample = outerFunction("Hello");
closureExample("World"); // "Outer: Hello, Inner: World"
Practical example
<!DOCTYPE html>
<html lang="en">
<body>
<h1 id="header" style="font-size:12px">Hello people</h1>
<button class="btn">Click me</button>
<script src="closure.js">
let hi = document.getElementById("header")
function setSize(size) {
return function sizeofthe() {
hi.style.fontSize = `${size}px`;
}
}
const btn = document.querySelector('.btn');
let size50 = setSize(50)
btn.addEventListener('click', () => size())
</script>
</body>
</html>
const counter = (function () {
let privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment() {
changeBy(1);
},
decrement() {
changeBy(-1);
},
value() {
return privateCounter;
},
};
})();
console.log(counter.value()); // 0.
counter.increment();
counter.increment();
console.log(counter.value()); // 2.
counter.decrement();
console.log(counter.value()); // 1.
Closures are useful for data encapsulation and function factories.
π 6. Recursion (Function Calling Itself)
Recursion is when a function calls itself.
πΉ Factorial Example
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
πΉ Fibonacci Sequence
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(6)); // 8
π 7. Callbacks & Higher-Order Functions
πΉ Callback Function
A function passed as an argument to another function.
function processData(data, callback) {
console.log("Processing:", data);
callback();
}
function done() {
console.log("Finished!");
}
processData("Task 1", done);
// "Processing: Task 1"
// "Finished!"
πΉ Higher-Order Functions
A function that takes another function as an argument or returns a function.
function multiplier(factor) {
return function (num) {
return num * factor;
};
}
const double = multiplier(2);
console.log(double(5)); // 10
// A higher-order function that processes an array of numbers using a callback.
function processNumbers(numbers, operation) {
const result = [];
for (let number of numbers) {
result.push(operation(number));
}
return result;
}
// Callback functions for different operations
function double(num) {
return num * 2;
}
function square(num) {
return num * num;
}
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = processNumbers(numbers, double);
console.log("Doubled Numbers:", doubledNumbers); // [2, 4, 6, 8, 10]
const squaredNumbers = processNumbers(numbers, square);
console.log("Squared Numbers:", squaredNumbers); // [1, 4, 9, 16, 25]
π 8. Immediately Invoked Function Expression (IIFE)
An IIFE runs immediately when defined.
(function () {
console.log("IIFE executed!");
})();
With parameters:
((name) => {
console.log(`Hello, ${name}!`);
})("Alice");
Practical Example
// Simulated asynchronous function using an error-first callback.
function fetchData(callback) {
setTimeout(() => {
// Simulate an error 50% of the time.
const error = Math.random() > 0.5 ? null : "Error: Data not found";
const data = error ? null : { id: 1, name: "Alice" };
// Call the callback with the error and data.
callback(error, data);
}, 1000);
}
// Using the asynchronous function with an error-first callback.
fetchData((error, data) => {
if (error) {
console.error("Callback received an error:", error);
} else {
console.log("Callback received data:", data);
}
});
π 9. Function Binding: call()
, apply()
, bind()
πΉ call()
function introduce() {
console.log(`Hello, I am ${this.name}`);
}
const person = { name: "Alice" };
introduce.call(person); // "Hello, I am Alice"
πΉ apply()
Same as call()
, but arguments are passed as an array.
function sum(a, b) {
console.log(a + b);
}
sum.apply(null, [3, 7]); // 10
πΉ bind()
Returns a new function with this
permanently set.
const boundFunc = introduce.bind(person);
boundFunc(); // "Hello, I am Alice"
π 10. Generator Functions (function*
)
Generator functions return an iterator and use yield
to pause execution.
function* count() {
yield 1;
yield 2;
yield 3;
}
const iterator = count();
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
console.log(iterator.next().value); // 3
π 11. Asynchronous Functions (async/await
)
πΉ Simulating an API Request
async function fetchData() {
return new Promise((resolve) => {
setTimeout(() => resolve("Data loaded"), 2000);
});
}
async function getData() {
console.log("Fetching...");
const result = await fetchData();
console.log(result);
}
getData();
// "Fetching..."
// (after 2s) "Data loaded"
Scope
In JavaScript, scope defines the accessibility (visibility) of variables, functions, and objects in some particular part of your code at runtime.
1. Global Scope
Variables declared outside of any function or block are in the global scope. They can be accessed anywhere in your code.
// Global Scope
const globalVar = "I am global";
function showGlobal() {
console.log("Inside function:", globalVar);
}
showGlobal(); // "Inside function: I am global"
console.log("Outside function:", globalVar); // "Outside function: I am global"
2. Block Scope
Variables declared with let
or const
are block-scoped. This means they only exist within the block (i.e., between {}
) where they are defined.
if (true) {
const blockVar = "I am block-scoped";
console.log("Inside block:", blockVar); // "I am block-scoped"
}
// console.log(blockVar); // Error: blockVar is not defined
3. Function Scope & Lexical Scope
Functions create their own scope. Variables declared inside a function are not accessible outside of it. Additionally, inner functions have access to variables in their outer (enclosing) functionsβthis is called lexical scope and is the basis for closures.
function outerFunction() {
const outerVar = "I am in the outer function";
function innerFunction() {
// innerFunction can access outerVar due to lexical scoping
console.log("Inside inner function:", outerVar);
}
innerFunction();
}
outerFunction(); // "Inside inner function: I am in the outer function"
// console.log(outerVar); // Error: outerVar is not defined
4. Closures
A closure occurs when an inner function continues to have access to the variables of its outer function, even after the outer function has finished executing.
function createGreeting(greeting) {
// 'greeting' is captured by the closure
return function (name) {
console.log(`${greeting}, ${name}!`);
};
}
const sayHello = createGreeting("Hello");
sayHello("Alice"); // "Hello, Alice!"
Summary
Global Scope: Variables declared outside any block or function. Accessible everywhere.
Block Scope: Variables declared with
let
orconst
inside{}
. Limited to that block.Function & Lexical Scope: Functions create their own scope, and inner functions can access variables from their outer scope.
Closures: Functions retain access to their defining scope even after that scope has finished execution.
Understand how JavaScript works under the hood
There is a Process called JavaScript Execution Context ,Watch below video to get In depth Knowledge about it
https://youtu.be/ByhtOgF6uYM?si=8c1HGf8ptJ7rAkUp&t=129
Control Flow (if, else,switch)
Control flow determines the order in which statements are executed in a JavaScript program. Conditional statements like if-else
, switch
, and logical operators help in decision-making.
JavaScript Control Flow & Conditional Statements
Control flow determines the order in which statements are executed in a JavaScript program. Conditional statements like if-else
, switch
, and logical operators help in decision-making.
1.1 if-else Statement
The if-else
statement is used to execute code based on a condition.
Syntax:
if (condition) {
// Code runs if condition is true
} else {
// Code runs if condition is false
}
Example:
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote.");
} else {
console.log("You are not eligible to vote.");
}
If
age
is18
or more, the first block runs.Otherwise, the
else
block runs.
1.2 Nested if-else
If multiple conditions need to be checked, if-else
blocks can be nested.
let marks = 85;
if (marks >= 90) {
console.log("Grade: A");
} else if (marks >= 80) {
console.log("Grade: B");
} else if (marks >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
- Checks conditions in sequence, executing the first one that is
true
.
1.3 switch Statement
A switch
statement is used when a variable is compared against multiple values.
Syntax:
switch (expression) {
case value1:
// Code runs if expression === value1
break;
case value2:
// Code runs if expression === value2
break;
default:
// Code runs if no case matches
}
Example:
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}
The
break
statement prevents fall-through (executing all cases after a match).If no cases match, the
default
case executes.
2. Truthy & Falsy Values
In JavaScript, values are categorized as truthy or falsy when used in a condition.
2.1 Falsy Values (Evaluates to false
in Boolean Context)
false
0
(zero)-0
0n
(Big int)""
(empty string)null
undefined
NaN
Example:
if (0) {
console.log("This will not execute.");
} else {
console.log("Falsy value detected!"); // Output
}
2.2 Truthy Values (Everything else)
Any non-zero number (
1, -1, 100
)Any non-empty string (
"hello"
)Objects (
{}
)Arrays (
[]
)
Example:
if ("Hello") {
console.log("Truthy value detected!"); // Output
}
For actual validation of array and object we use this
// for array
arr = []
if (arr.length === 0) {
console.log("Array is empty");
}
// for Objects
const emptyObj = {}
if (Object.keys(emptyObj).length === 0) {
console.log("Object is empty");
}
3. Ternary Operator (? :
)
A ternary operator is a shorthand for if-else
.
Syntax:
condition ? expr1 : expr2;
Example:
let age = 20;
let message = age >= 18 ? "You can vote" : "You cannot vote";
console.log(message); // Output: You can vote
4. Nullish Coalescing Operator (??
)
The ??
operator returns the first defined (non-null, non-undefined) value.
Example:
let name = null;
let defaultName = name ?? "Guest";
console.log(defaultName); // Output: Guest
If
name
isnull
orundefined
,defaultName
is"Guest"
.Unlike
||
, it doesn't consider""
or0
as falsy.
5. Logical Operators with if-else
Logical operators help in evaluating multiple conditions.
5.1 AND (&&
) Operator
Returns
true
if both conditions are true.Otherwise, returns
false
.
Example:
let age = 25;
let hasID = true;
if (age >= 18 && hasID) {
console.log("Allowed to enter"); // Output
} else {
console.log("Access denied");
}
5.2 OR (||
) Operator
Returns
true
if at least one condition is true.Otherwise, returns
false
.
Example:
let isWeekend = false;
let isHoliday = true;
if (isWeekend || isHoliday) {
console.log("You can relax!"); // Output
} else {
console.log("Go to work");
}
5.3 NOT (!
) Operator
- Negates a Boolean value.
Example:
let isRaining = false;
if (!isRaining) {
console.log("Go outside!"); // Output
}
!isRaining
convertsfalse
totrue
.
6. Combining Logical Operators
You can combine &&
, ||
, and !
in conditions.
Example:
let hasLicense = true;
let isSober = false;
if (hasLicense && !isSober) {
console.log("You can drive");
} else {
console.log("You cannot drive"); // Output
}
!isSober
turnsfalse
intotrue
, so the condition fails.
7. Summary
Feature | Description | Example |
if-else | Executes based on condition | if (age > 18) { ... } else { ... } |
switch | Matches a value to multiple cases | switch(day) { case 1: ... } |
Falsy Values | Values treated as false | false, 0, "", null, undefined, NaN |
Truthy Values | Everything else | "hello", 1, [], {} |
Ternary (? : ) | Short if-else | age > 18 ? "Adult" : "Minor" |
Nullish (?? ) | Returns first non-null value | let name = userInput ?? "Guest" |
&& (AND) | Both conditions must be true | if (x > 0 && y > 0) |
` | ` (OR) | |
! (NOT) | Negates a Boolean | if (!isRaining) |
8. Practice Exercise
Try these exercises to reinforce your learning:
// 1. Use a ternary operator to check if a number is positive or negative.
let num = -5;
let result = num >= 0 ? "Positive" : "Negative";
console.log(result);
// 2. Use the `??` operator to assign a default value.
let username = null;
let displayName = username ?? "Guest";
console.log(displayName);
// 3. Write a switch statement to print days of the week.
let day = 5;
switch (day) {
case 1: console.log("Monday"); break;
case 2: console.log("Tuesday"); break;
case 5: console.log("Friday"); break;
default: console.log("Invalid day");
}
Loops
Below is an in-depth guide to loops in JavaScript, complete with practical examples. Loops allow you to repeat a block of code until a certain condition is met or to iterate over the elements of an object or array. We'll cover the following types of loops:
For Loop
While Loop
Do-While Loop
For-In Loop
For-Of Loop
Each section includes explanations and practical examples that you can run and experiment with.
1. For Loop
The for loop is one of the most common loops in JavaScript. It is used when you know in advance how many times you want to iterate.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute on each iteration
}
Practical Example:
// Print numbers from 0 to 4
for (let i = 0; i < 5; i++) {
console.log("For loop iteration:", i);
}
Explanation:
Initialization:
let i = 0
β initializes the loop counter.Condition:
i < 5
β loop continues as long as this condition is true.Increment:
i++
β increasesi
by 1 after each iteration.
2. While Loop
The while loop repeatedly executes its block of code as long as a specified condition is true. Itβs useful when the number of iterations is not known in advance.
Syntax:
while (condition) {
// Code to execute while the condition is true
}
Practical Example:
// Print numbers from 0 to 4 using a while loop
let i = 0;
while (i < 5) {
console.log("While loop iteration:", i);
i++; // Remember to update the counter, or the loop will run indefinitely
}
Explanation:
The loop checks the condition
i < 5
at the beginning of each iteration.Inside the loop, the counter
i
is incremented.If you forget to update
i
, the loop becomes infinite.
3. Do-While Loop
The do-while loop is similar to the while loop, but it guarantees that the code inside the loop is executed at least once because the condition is checked after the code runs.
Syntax:
do {
// Code to execute
} while (condition);
Practical Example:
// Print numbers from 0 to 4 using a do-while loop
let j = 0;
do {
console.log("Do-while loop iteration:", j);
j++;
} while (j < 5);
Explanation:
The code inside the
do
block runs first.After executing the block, the condition
j < 5
is evaluated.This loop is particularly useful when you need the code to run at least once regardless of the condition.
4. For-In Loop
The for-in loop is used to iterate over the enumerable properties (keys) of an object. It is best used for objects, not arrays (though it can be used with arrays, it may produce unexpected results with inherited properties).
Syntax:
for (let key in object) {
// Code to execute for each key
}
Practical Example:
const person = {
name: "Alice",
age: 30,
city: "New York"
};
for (let key in person) {
console.log(key + ": " + person[key]);
}
Explanation:
The loop iterates over each property (key) in the
person
object.Inside the loop, you can access the key and its corresponding value (
person[key]
).
5. For-Of Loop
The for-of loop is used to iterate over iterable objects such as arrays, strings, maps, and sets. It gives you direct access to the values of the iterable.
Syntax:
for (let value of iterable) {
// Code to execute for each value
}
Practical Example:
const fruits = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {
console.log("For-of loop fruit:", fruit);
}
// for map
const map = new Map();
map.set('IN', 'India');
map.set('USA', 'United States of America');
map.set('Fr', 'France');
map.set('IN', 'India');
for (const [key, value] of map) {
console.log(key);
}
//output
'IN'
'USA'
'Fr'
for (const key of map) {
console.log(key);
}
// output
[ 'IN', 'India' ]
[ 'USA', 'United States of America' ]
[ 'Fr', 'France' ]
Explanation:
The loop iterates over the
fruits
array.In each iteration,
fruit
holds the value of the current array element.
Summary
For Loop: Best when you know how many times to iterate.
While Loop: Best when the number of iterations isnβt known beforehand.
Do-While Loop: Executes at least once, then checks the condition.
For-In Loop: Iterates over the properties of an object.
For-Of Loop: Iterates over values in iterable objects (arrays, strings, etc.).
Break and Continue
Below is an in-depth explanation of the break
and continue
statements in JavaScript, along with practical examples demonstrating their usage in loops.
1. The break
Statement
The break
statement is used to exit from a loop immediately. When encountered, it terminates the loop entirely, and control is passed to the first statement following the loop. Itβs commonly used when a certain condition is met and you no longer need to continue iterating.
Example: Using break
in a For Loop
// We want to loop through numbers and exit the loop when a number greater than 3 is found.
for (let i = 0; i < 10; i++) {
if (i > 3) {
break; // Exit the loop entirely when i > 3
}
console.log("Break Example, i =", i);
}
// Output:
// Break Example, i = 0
// Break Example, i = 1
// Break Example, i = 2
// Break Example, i = 3
Use Cases for break
:
Exiting a loop early when a target value is found.
Stopping an infinite loop when a certain condition becomes true.
Breaking out of a
switch
statement to prevent fall-through (more on that below).
2. The continue
Statement
The continue
statement is used to skip the rest of the code inside the loop for the current iteration and proceed with the next iteration. It doesn't exit the loop entirelyβit only skips to the next cycle.
Example: Using continue
in a For Loop
// We want to loop through numbers and skip printing even numbers.
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip the rest of the loop body for even numbers.
}
console.log("Continue Example, odd number =", i);
}
// Output:
// Continue Example, odd number = 1
// Continue Example, odd number = 3
// Continue Example, odd number = 5
// Continue Example, odd number = 7
// Continue Example, odd number = 9
Use Cases for continue
:
Skipping specific iterations based on a condition.
Filtering out unwanted values during a loop without terminating the loop.