JavaScript 101: The Basic Concepts Explained

NishantNishant
35 min read

JavaScript is a high-level, interpreted, dynamically typed, event-driven, prototype-based, single-threaded programming language.

TermMeaning
High-levelYou don’t manage memory or hardware directly—JS handles it for you.
InterpretedCode is run line by line, not compiled ahead of time.
Dynamically TypedVariable types are determined at runtime.
Event-drivenJS reacts to user events like clicks, scrolls, etc.
Prototype-basedJS uses prototypes instead of classical classes for inheritance.
Single-threadedOnly one command is executed at a time via a single call stack.

JavaScript is like a personal assistant who handles different tasks one-by-one (single-threaded), responds when called (event-driven), and doesn't ask you to label every item you give them (dynamically typed).

Why Was JavaScript Created?

🕰️ In 1995, Brendan Eich developed JavaScript in just 10 days at Netscape

Purpose:

  • Before JS, web pages were just digital flyers. No interactivity.

  • JS brought life to the web—validating forms, triggering animations, responding to clicks, etc.

Today, JavaScript Powers:

AreaExample Tech
Front-endReact, Vue, Angular
Back-endNode.js
Mobile AppsReact Native, Ionic
DatabasesMongoDB (via Node.js drivers)
AI & MLTensorFlow.js

What is an Interpreter?

JavaScript is interpreted, meaning code is executed line by line.

Compiler (e.g. C++)Interpreter (JavaScript)
Translates entire code before executionTranslates and runs line-by-line
Faster after compilationSlower initially, but faster with JIT
Strict with typesDynamic typing allowed

But modern JS engines like V8 use JIT (Just-In-Time) Compilation:

  • JS is partially compiled at runtime for better performance.

JavaScript Engine – The Brain Behind JS

A JavaScript Engine is the software component that reads, compiles, and executes JS code.

EngineBrowser/Environment
V8Chrome, Edge, Node.js
Spider MonkeyFirefox
JavaScript CoreSafari

Internal Working:

  1. Parsing → Code is broken into tokens

  2. JIT Compilation → Tokens compiled into bytecode

  3. Execution → Code runs inside the Execution Context and Call Stack


JavaScript is Dynamically Typed

In JS, you don’t need to define variable types—they’re inferred at runtime.

let x = 10;     // number
x = "hello";    // now a string!

Caveat:

This flexibility can cause bugs if types are misused.


JavaScript Execution Context (How JS Runs Internally)

Every time JS runs, it creates an Execution Context.


Global Execution Context (GEC)

JS starts with one Global Execution Context, which creates:

ComponentRole
Memory (Variable Env)Stores variables and function declarations
Call StackManages function execution order

Code Example:

let x = 10;

function sayHello() {
  console.log("Hello!");
}
sayHello();

Internally:

  1. JS stores x = 10 in memory.

  2. Stores sayHello function.

  3. Adds sayHello() to the Call Stack and runs it.

  4. Prints "Hello!" and removes it from the stack.


Call Stack Analogy:

Think of the Call Stack like a stack of dishes—when a new function is called, it’s placed on top.
When it finishes, it's removed.
Only the top dish (function) can be accessed at any time.




Deep Dive into JavaScript Variables

Variables are the building blocks of every program. But how does JavaScript actually handle variables under the hood?


What is a Variable

A variable is like a labeled box in a warehouse 🏷📦.
You store something inside it and later refer to it using the label.

let x = 10;
console.log(x); // 10
ElementReal-World Analogy
letTells the warehouse manager to create a box
xLabel on the box
10Item inside the box
console.log(x)Look inside the box labeled x

How JavaScript Handles Variables in Memory

JavaScript splits memory into two parts:

Memory TypePurposeWhat Goes Here
Call StackKeeps track of function callsPrimitives (number, string...)
Memory HeapStores large or reference dataObjects, arrays, functions

Visual:

Call Stack
-----------
x → 10
y → 20

Memory Heap
------------
obj1 → { name: "Alice" }
obj2 → (points to obj1)

Variable Declaration Keywords: var, let, and const

KeywordScopeCan ReassignHoisted?Temporal Dead Zone
varFunction✅ Yes✅ Yes (as undefined)❌ No
letBlock ({}-scoped)✅ Yes✅ Yes (in TDZ)✅ Yes
constBlock❌ No✅ Yes (in TDZ)✅ Yes

1. var: The Old Guard (Function Scope)

console.log(x); // undefined (NOT error!)
var x = 5;

JavaScript hoists var declarations to the top of the scope.

jsCopyEdit// Internally
var x;
console.log(x); // undefined
x = 5;

Avoid using var—it leads to bugs due to hoisting and loose scoping.


2. let: The Modern Choice (Block Scope)

console.log(y); // ❌ ReferenceError
let y = 10;

let is hoisted but sits in the Temporal Dead Zone (TDZ)—you can’t access it before it's defined.

Use let when the value is supposed to change.


3. const: The Immutable Guard

const pi = 3.14;
pi = 4.2; // ❌ TypeError
  • You must initialize a const immediately.

  • It can't be reassigned, but object content can change:

const obj = { name: "Alice" };
obj.name = "Bob"; // ✅ Allowed
obj = { name: "Charlie" }; // ❌ Not allowed

Memory Model: Primitives vs Reference Types

Primitives (Stored in Call Stack):

let a = 10;
let b = a;
b = 20;

console.log(a); // 10
console.log(b); // 20

Each variable has its own memory location.


Reference Types (Stored in Heap):

let obj1 = { name: "Alice" };
let obj2 = obj1;
obj2.name = "BOB";

console.log(obj1.name); // "BOB"

Both obj1 and obj2 point to the same object in the heap.

Diagram:


Execution Context Recap (Where Variables Live)

Whenever JS runs a program, it sets up:

  1. Memory (Variable Environment)

    • let, const, and var declarations go here
  2. Call Stack

    • Keeps track of "who called whom" (function execution order)

Variables declared:

  • With let/constLexical Environment

  • With varHoisted to the top of scope


Summary:

ConceptDetails
VariableA labeled storage in memory
varFunction scoped, hoisted with value undefined, avoid using
letBlock scoped, hoisted but in TDZ, best for changing values
constBlock scoped, immutable binding, best for constants
PrimitivesStored in Call Stack, copied by value
Reference TypesStored in Heap, copied by reference (same address)
Hoistingvar is hoisted and initialized to undefined, let/const are not accessible before declaration (TDZ)
Best PracticePrefer const, use let only when needed, avoid var



JavaScript Data Types (With Internal Workings)

Every programming language deals with data—but how does JavaScript internally store, manage, and differentiate between various types of data?
Let’s break it down step by step with internal mechanisms and examples.


What is a Data Type?

A data type defines the kind of value a variable holds and how it behaves during operations.

Example:

let num = 10;        // Number
let name = "Alice";  // String
let isHappy = true;  // Boolean

Here:

  • num is a number,

  • name is a string,

  • isHappy is a boolean.


JavaScript Data Types: Two Main Categories

JavaScript categorizes data into primitive and reference types:

CategoryData TypesStored In
PrimitiveNumber, String, Boolean, null, undefined, Symbol, BigIntCall Stack (stored by value)
ReferenceObject, Array, FunctionHeap (stored by reference)

Key Difference:

  • Primitive types are stored by value directly in the call stack.

  • Reference types are stored in the heap, and the variable holds a reference (pointer) to the actual data.


Primitive Data Types (Stored in Call Stack)

Primitive values are immutable and are copied by value when assigned or passed.


1️⃣ Number (Numeric Data)

let x = 42;
let y = 3.14;

Internal Mechanics:

  • Uses IEEE-754 64-bit floating-point format.

  • Can represent both integers and decimals.

  • Supports special values like Infinity, -Infinity, and NaN (Not a Number).

console.log(10 / 0);        // Infinity
console.log("abc" * 2);     // NaN

2️⃣ String (Textual Data)

let greeting = "Hello";
let msg = `Template Literals`;

Internal Mechanics:

  • Stored as UTF-16 encoded sequences.

  • Strings are immutable—any operation creates a new string.

let name = "John";
name[0] = "D";         // ❌ No effect
console.log(name);     // "John"

let newName = name.replace("J", "D");
console.log(newName);  // "Dohn"

3️⃣ Boolean (Logical True/False)

let isLoggedIn = true;
let hasAccess = false;

Used for:

  • Conditional statements.

  • Logical operations (&&, ||, !).

  • JS treats these as 1 bit, but memory alignment may use 4+ bytes.

🔍 Falsy Values in JavaScript:
false, 0, "", null, undefined, NaN


4️⃣ Undefined (Declared but Not Assigned)

let a;
console.log(a); // undefined

Internals:

  • JS assigns undefined by default to uninitialized variables.

  • Functions return undefined if no return statement is given.

function doNothing() {}
console.log(doNothing()); // undefined

5️⃣ Null (Intentional Absence of Value)

let data = null;
Comparisonnullundefined
MeaningIntentional absence of valueVariable declared but not assigned
Type (typeof)"object" (bug)"undefined"
Use CaseExplicitly cleared valueJS assigns automatically
console.log(typeof null);      // "object" ❌ (known JS bug)
console.log(typeof undefined); // "undefined"

6️⃣ Symbol (Unique Identifiers)

let sym = Symbol("id");

Internals:

  • Each symbol is completely unique, even with the same description.

  • Mostly used for private object keys.

const sym1 = Symbol("x");
const sym2 = Symbol("x");
console.log(sym1 === sym2); // false

7️⃣ BigInt (Arbitrary-Precision Integers)

let bigNum = 987654321987654321n;

Internals:

  • Used for numbers larger than Number.MAX_SAFE_INTEGER.

  • Appending n indicates it's a BigInt.

console.log(typeof 123456789n); // "bigint"

🔵 Reference Data Types (Stored in Heap)

Reference types store a pointer in the stack, pointing to the actual value in the heap.


1️⃣ Object (Key-Value Data Structures)

let user = {
  name: "Alice",
  age: 30
};

Memory Behavior:

  • Objects live in the heap.

  • Variables hold a reference (address) to the heap memory.

let obj1 = { name: "John" };
let obj2 = obj1;
obj2.name = "Doe";

console.log(obj1.name); // "Doe" — both refer to same object!

2️⃣ Array (Indexed Collection)

let numbers = [1, 2, 3];

📌 Internally:

  • Arrays are objects with numeric keys.

  • typeof [] === "object"

🔁 Reference Copy Issue:

let arr1 = [1, 2, 3];
let arr2 = arr1;
arr2.push(4);

console.log(arr1); // [1, 2, 3, 4]

Fix: Use Spread / Slice:

let arr2 = [...arr1]; // OR arr1.slice()

3️⃣ Function (First-Class Objects)

function greet() {
  console.log("Hello!");
}

Internals:

  • Functions are objects with executable code and properties.

  • Stored in the heap like any object.

  • Can be assigned, passed, or returned like values.

let sayHi = greet;
sayHi(); // "Hello!"

Summary:

FeaturePrimitive TypesReference Types
Stored InCall StackHeap (pointer in Call Stack)
Copied ByValueReference
MutabilityImmutableMutable
ExamplesNumber, String, Boolean, nullObject, Array, Function

Additional Notes:

  • null is intentional nothing, undefined is auto-assigned nothing.

  • Use Symbol for unique keys, BigInt for very large integers.

  • Use spread/cloning to avoid unwanted reference mutations.




JavaScript Type Conversion (Implicit & Explicit)

JavaScript is a dynamically typed language — variables can change types on the fly.
But how and why does JavaScript automatically convert types behind the scenes? Let’s explore the internals of type conversion.


What is Type Conversion?

Type conversion is the process of changing one data type into another.

Think of it like packing things into containers of different shapes:

  • 🧃 String = Text Container

  • 🔢 Number = Numeric Container

  • 🔘 Boolean = True/False Switch


Types of Conversion

TypeWho Performs It?ExampleReal-World Analogy
ImplicitJavaScript (auto/coercion)"5" + 2 → "52"Like auto-switching between metric/imperial units
ExplicitDeveloper (manual casting)Number("5") → 5Manually converting a .jpg to .png

1️⃣ Implicit Type Conversion (Type Coercion)

JavaScript automatically coerces (converts) data when it thinks it should — especially in arithmetic and comparison operations.

🔹 String Conversion with + (Concatenation Wins)

If either operand is a string, JS will convert the other to a string.

console.log("5" + 2);        // "52"
console.log("Hello" + null); // "Hellonull"

Why?
The + operator works for both addition and string concatenation — JS picks string mode if any operand is a string.


🔹 Number Conversion with -, *, /

console.log("5" - 2);      // 3
console.log("10" * "2");   // 20
console.log("6" / "3");    // 2
console.log("5" - true);   // 4 (true → 1)
console.log("5" - false);  // 5 (false → 0)

JS prefers math mode in -, *, / — so it tries to convert all values to numbers.


Boolean Conversion (Truthy/Falsy Logic)

Used in if, while, &&, ||, and logical NOT !.

Truthy Values

Everything that's "not empty" or "not zero":

  • "Hello", 123, [], {}

Falsy Values

Empty or invalid:

  • "", 0, null, undefined, NaN
console.log(Boolean([]));        // true
console.log(Boolean(""));        // false
console.log(Boolean(undefined)); // false

Arrays and objects are always truthy, even if empty.


2️⃣ Explicit Type Conversion (Type Casting)

This is when you convert values manually using functions like Number(), String(), and Boolean().


Convert to String (String() or .toString())

console.log(String(123));      // "123"
console.log((true).toString()); // "true"

Use .toString() only when you're sure the value isn’t null or undefined (they throw errors).


Convert to Number (Number(), parseInt(), parseFloat())

console.log(Number("42"));        // 42
console.log(Number(true));        // 1
console.log(Number(""));          // 0
console.log(Number("hello"));     // NaN

parseInt() and parseFloat() — looser, stop at invalid characters:

console.log(parseInt("42px"));     // 42
console.log(parseFloat("3.14kg")); // 3.14

Use Number() for strict parsing, parseInt() for extracting leading digits.


Convert to Boolean (Boolean())

console.log(Boolean(0));         // false
console.log(Boolean("Hello"));  // true
console.log(Boolean([]));       // true
console.log(Boolean(null));     // false

Even empty arrays and objects are true — because they are references.


3️⃣ Special Cases You Must Know

null vs undefined

ValueNumber()String()Boolean()
null0"null"false
undefinedNaN"undefined"false

null means "intentional empty", undefined means "not initialized".


NaN (Not a Number)

console.log(Number("abc"));    // NaN
console.log(10 / "hello");     // NaN

NaN is Not Equal to Itself!

console.log(NaN === NaN); // false

Use Number.isNaN() to check:

console.log(Number.isNaN(NaN)); // true

Summary Cheat Sheet

ConceptDescription
Implicit ConversionAuto by JS in expressions like "5" + 1"51"
Explicit ConversionYou use Number(), String(), Boolean()
Falsy Values0, "", null, undefined, NaN
Truthy ValuesEverything else: "text", 1, [], {}
+ OperatorTriggers string coercion if one is a string
-, *, / OperatorsTriggers number coercion
NaN CheckUse Number.isNaN(value)
Safe String ConversionString(value) (better than .toString() on null)

Pro Tip:
When in doubt, log the type and value using:

console.log(typeof value, value);

Use Strict Equality (===) to avoid surprises with coercion:

console.log("5" == 5);  // true (coerced)
console.log("5" === 5); // false (type matters)



JavaScript Operators & Expressions

What are Operators?

Operators are special symbols used to perform operations like addition, comparison, logic, and more.

Types of Operators in JavaScript

TypeExamples
Arithmetic+, -, *, /, %, **
Assignment=, +=, -=, *=, /=, %=
Comparison==, ===, !=, !==, >, <, >=, <=
Logical&&, `
Bitwise&, `
Ternarycondition ? value1 : value2

1️⃣ Arithmetic Operators (Basic Math)

OperatorNameExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication6 * 212
/Division10 / 25
%Modulus (Remainder)10 % 31
**Exponentiation2 ** 38
console.log(10 + 5);  // 15
console.log(10 % 3);  // 1
console.log(2 ** 4);  // 16

2️⃣ Assignment Operators

OperatorDescriptionExampleEquivalent
=Assignx = 10
+=Add & assignx += 5x = x + 5
-=Subtract & assignx -= 2x = x - 2
*=Multiply & assignx *= 3x = x * 3
/=Divide & assignx /= 4x = x / 4
%=Modulo & assignx %= 2x = x % 2
let x = 10;
x += 5;
console.log(x); // 15

3️⃣ Comparison Operators

OperatorNameExampleResult
==Loose equality5 == "5"true
===Strict equality5 === "5"false
!=Loose inequality10 != 5true
!==Strict inequality10 !== "10"true
>Greater than10 > 5true
<Less than3 < 7true
>=Greater or equal5 >= 5true
<=Less or equal4 <= 6true

Strict vs Loose Comparison

  • == converts types before comparing

  • === checks both type and value

console.log(5 == "5");   // true
console.log(5 === "5");  // false

🔵 4️⃣ Logical Operators

OperatorNameExampleResult
&&ANDtrue && falsefalse
OR`falsetrue`true
!NOT!truefalse

Short-circuit behavior:

console.log(0 && "Hello");  // 0 (first falsy)
console.log(1 || "World");  // 1 (first truthy)

5️⃣ Bitwise Operators (Binary Level)

OperatorDescriptionExampleBinaryResult
&AND5 & 30101 & 00110001 (1)
OR`53``01010011`0111 (7)
^XOR5 ^ 30101 ^ 00110110 (6)
~NOT~5~0000000000000101-6
<<Left shift5 << 10101 << 11010 (10)
>>Right shift5 >> 10101 >> 10010 (2)
console.log(5 & 3);  // 1
console.log(5 | 3);  // 7
console.log(5 << 1); // 10
console.log(~5);     // -6

Why is ~5 equal to -6?
It flips bits and applies 2's complement, so:

~5 = -(5 + 1) = -6

6️⃣ Ternary Operator (Short If-Else)

let age = 18;
let result = (age >= 18) ? "Adult" : "Minor";
console.log(result); // "Adult"

Real-world analogy:
“If you’re hungry, eat pizza, else drink water.”

let hungry = true;
let action = hungry ? "Eat Pizza" : "Drink Water";

7️⃣ Expressions in JavaScript

An expression is any valid set of literals, variables, and operators that evaluates to a value.

Examples:

5 + 2              // Arithmetic Expression → 7
x = 10             // Assignment Expression
x > 5              // Comparison Expression → true/false
true || false      // Logical Expression
age > 18 ? "A" : "B"  // Ternary Expression

Summary

Arithmetic Operators+, -, *, /, %, **
Assignment Operators=, +=, -=, etc.
Comparison Operators==, ===, >, <
Logical Operators&&, ||, ! (with short-circuiting)
Bitwise Operators → Work on binary (&, |, ^, ~, <<, >>)
Ternary Operatorcondition ? trueVal : falseVal
Expressions → Any combo that returns a value




JavaScript Strings

1️⃣ What is a String?

A string is a sequence of characters enclosed in:

  • Single quotes (')

  • Double quotes (")

  • Backticks (``) → Used for template literals

Examples:

let str1 = "Hello, World!";
let str2 = 'JavaScript';
let str3 = `I am learning JS`; // Template Literal

Backticks are powerful — they allow multi-line strings and embedded expressions.


2️⃣ How Strings Are Stored (Stack vs Heap)

  • Primitive strings are stored in the Stack if they are unchanged (immutable).

  • When you modify a string, a new string is created in the Heap.

Example:

let name1 = "Alice";
let name2 = name1;
name2 = "Bob";

console.log(name1); // Alice
console.log(name2); // Bob

Why?
Strings are immutable. Unlike objects, modifying a string doesn’t change it in place—it creates a new one.


3️⃣ String Properties

PropertyDescription
.lengthReturns the number of characters

Example:

let text = "Hello";
console.log(text.length); // 5

4️⃣ Accessing Characters in a String

  • Use bracket notation ([])

  • Or use .charAt(index)

Example:

let message = "JavaScript";

console.log(message[0]);        // J
console.log(message.charAt(2)); // v

❌ Strings are immutable → message[0] = 'X' won’t work.


5️⃣ Useful String Methods

MethodDescription
.toUpperCase()Converts to uppercase
.toLowerCase()Converts to lowercase
.trim()Removes spaces from both ends
.slice(start, end)Extracts part of a string
.substring()Like slice() but doesn't accept negatives
.replace()Replaces first match
.replaceAll()Replaces all matches
.split(separator)Converts string to array

Examples:

let text = "  JavaScript is Awesome!  ";

console.log(text.toUpperCase()); // "  JAVASCRIPT IS AWESOME!  "
console.log(text.toLowerCase()); // "  javascript is awesome!  "
console.log(text.trim());        // "JavaScript is Awesome!"
console.log(text.slice(2, 11));  // "JavaScript"
console.log(text.replace("Awesome", "Great")); // "  JavaScript is Great!  "
console.log(text.split(" "));    // ["", "", "JavaScript", "is", "Awesome!", "", ""]

6️⃣ Template Literals (Backticks `\)

Allows:

  • Multi-line strings

  • Embedded expressions using ${}

Example:

let name = "Alice";
let age = 25;

let message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message);

Real-world analogy:
Instead of saying:
"Hi, my name is" + name + " and I’m " + age + " years old"
Use backticks:
`Hi, my name is ${name} and I’m ${age} years old`


7️⃣ String Comparison

Use === for strict case-sensitive comparison
Use .localeCompare() for flexible sorting

Example:

console.log("apple" === "Apple"); // false

console.log("apple".localeCompare("Apple", undefined, { sensitivity: 'base' }));
// 0 → means equal ignoring case

8️⃣ Checking Substrings

MethodPurpose
.includes()Checks if string contains value
.startsWith()Checks prefix
.endsWith()Checks suffix

Example:

let sentence = "JavaScript is fun";

console.log(sentence.includes("fun"));      // true
console.log(sentence.startsWith("Java"));   // true
console.log(sentence.endsWith("fun"));      // true

9️⃣ Converting to String

MethodUse Case
String(value)Safely convert to string
value.toString()Common for primitives
Template Literal${value} forces string

Example:

let num = 42;

console.log(String(num));    // "42"
console.log(num.toString()); // "42"
console.log(`${num}`);       // "42"

🔟 Escape Characters in Strings

SequenceMeaning
\'Single quote
\"Double quote
\\Backslash
\nNew line
\tTab

Example:

let quote = "She said, \"JavaScript is cool!\"";
console.log(quote);

Summary:

  • Strings are immutable

  • Stored in stack if unchanged; heap if modified

  • Access using [] or .charAt()

  • Use powerful methods like .slice(), .replace(), .split()

  • Template literals make dynamic strings easier

  • .includes(), .startsWith(), .endsWith() = useful checks

  • Use String() / .toString() / ${} to convert types

  • Escape characters help with quotes, tabs, and newlines




JavaScript Numbers & Math

1️⃣ JavaScript Number System

JavaScript has only one number type: a 64-bit floating-point (IEEE 754) number.
That means integers and decimals are stored in the same format.

Examples:

let num1 = 42;       // Integer
let num2 = 3.14;     // Floating-point (decimal)
let num3 = 2e5;      // Exponential notation = 200000

⚠ JavaScript doesn't have separate "int" or "float" types.


2️⃣ Special Number Values

JavaScript includes a few special values for numbers:

ValueDescription
InfinityNumber too large to represent
-InfinityNumber too small (negative) to represent
NaN"Not a Number" (invalid mathematical result)

Examples:

console.log(1 / 0);        // Infinity
console.log(-1 / 0);       // -Infinity
console.log("hello" * 3);  // NaN

3️⃣ Number Properties & Methods

Here are useful ways to test and convert numbers:

MethodDescription
Number.isFinite(x)Checks if x is a finite number
Number.isInteger(x)Checks if x is an integer
Number.isNaN(x)Checks if x is NaN
Number.parseFloat(x)Parses float from string
Number.parseInt(x)Parses integer from string

Examples:

console.log(Number.isFinite(100));    // true
console.log(Number.isInteger(4.5));   // false
console.log(Number.isNaN(NaN));       // true

console.log(Number.parseFloat("3.14"));  // 3.14
console.log(Number.parseInt("42px"));    // 42

4️⃣ Arithmetic Operations

Basic arithmetic in JavaScript works just as expected:

OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
%Remainder (Modulus)
**Exponentiation

Examples:

console.log(5 + 3);   // 8
console.log(10 - 4);  // 6
console.log(6 * 2);   // 12
console.log(8 / 2);   // 4
console.log(10 % 3);  // 1
console.log(2 ** 3);  // 8 (2 raised to 3)

5️⃣ Rounding Numbers

JavaScript offers several built-in methods for rounding:

MethodDescription
Math.round(x)Round to nearest integer
Math.floor(x)Round down
Math.ceil(x)Round up
Math.trunc(x)Remove decimal part
.toFixed(n)Round to n decimals (returns string)

Examples:

console.log(Math.round(4.7));    // 5
console.log(Math.floor(4.7));    // 4
console.log(Math.ceil(4.3));     // 5
console.log(Math.trunc(4.7));    // 4
console.log(3.14159.toFixed(2)); // "3.14"

6️⃣ Math Methods

The built-in Math object provides helpful mathematical tools:

MethodDescription
Math.abs(x)Absolute value
Math.sqrt(x)Square root
Math.pow(x, y)x raised to the power y
Math.max(...)Largest of given values
Math.min(...)Smallest of given values
Math.random()Random number (0 ≤ x < 1)

Examples:

console.log(Math.abs(-10));       // 10
console.log(Math.sqrt(25));       // 5
console.log(Math.pow(2, 3));      // 8
console.log(Math.max(10, 20, 30)); // 30
console.log(Math.min(10, 20, 30)); // 10
console.log(Math.random());       // Random number between 0 and 1

7️⃣ Generating Random Numbers in a Range

Want a random number between any min and max?

Example:

function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(getRandom(1, 10)); // Random number from 1 to 10

8️⃣ Type Conversion with Numbers

Easily convert between numbers and strings:

ConversionMethod
String → NumberNumber(str), parseInt(str)
Number → StringString(num), num.toString()

Examples:

console.log(Number("42"));      // 42
console.log(parseInt("42.5"));  // 42
console.log(parseFloat("42.5"));// 42.5
console.log((42).toString());   // "42"

9️⃣ Dealing with Precision Issues

JavaScript uses binary floating-point, which can cause rounding errors.

Problem:

console.log(0.1 + 0.2); // 0.30000000000000004 ❌

Fixes:

console.log((0.1 + 0.2).toFixed(2));            // "0.30"
console.log((0.1 * 10 + 0.2 * 10) / 10);        // 0.3

Summary

JavaScript uses only one number type (64-bit float).
Special values: NaN, Infinity, -Infinity.
Use Math methods for common operations.
Rounding: round, floor, ceil, trunc, toFixed.
Use Math.random() for randomness.
Be cautious with precision issues in decimals.




JavaScript Date & Time

1️⃣ Creating a Date Object

In real life, when you check your phone or calendar app, you’re seeing a snapshot of time. JavaScript's Date object works similarly — it captures a moment in time.

Different Ways to Create a Date:

let now = new Date();  // Current date & time
let specificDate = new Date("2023-12-25");  // Using ISO format
let withTime = new Date("2023-12-25T10:30:00"); // Specific time
let customDate = new Date(2023, 11, 25); // Year, Month (0-based), Day
let customDateTime = new Date(2023, 11, 25, 10, 30, 15); // Full date-time

Key Notes:

  • Months are 0-based: 0 = January, 11 = December.

  • Time is in 24-hour format.

  • The ISO format (YYYY-MM-DDTHH:mm:ss) is safest for cross-browser parsing.


2️⃣ Getting Date Components

Once you create a date, you can extract various parts — like checking what day it is, what time, etc.

Example:

let date = new Date();

console.log(date.getFullYear());    // 2025
console.log(date.getMonth());       // 0 (January)
console.log(date.getDate());        // Day of the month
console.log(date.getDay());         // Day of week (0 = Sunday)
console.log(date.getHours());       // Hour (0–23)
console.log(date.getMinutes());     // Minutes
console.log(date.getSeconds());     // Seconds
console.log(date.getMilliseconds());// Milliseconds
console.log(date.getTime());        // Timestamp in ms since Jan 1, 1970

Analogy:
Think of getTime() as a global stopwatch counting milliseconds from January 1, 1970 UTC — a date known as the Unix Epoch.


3️⃣ Setting Date Components

Just like setting the time on an alarm clock, you can set parts of the date manually.

Example:

let date = new Date();

date.setFullYear(2030);
date.setMonth(5);     // June (months are 0-based)
date.setDate(15);
date.setHours(10);
date.setMinutes(45);

console.log(date);

Auto-correction Behavior:

let date = new Date();
date.setDate(32);  // Automatically rolls to next month
console.log(date);

JavaScript auto-fixes invalid values like the 32nd day by pushing it into the next month.


4️⃣ Date Formatting

Raw dates aren’t always readable — JavaScript offers formatted output methods.

Example:

let date = new Date();

console.log(date.toDateString());     // "Thu Mar 27 2025"
console.log(date.toTimeString());     // "14:35:45 GMT+0530 (India Standard Time)"
console.log(date.toISOString());      // "2025-03-27T09:05:45.123Z"
console.log(date.toUTCString());      // "Thu, 27 Mar 2025 09:05:45 GMT"
console.log(date.toLocaleDateString()); // Based on browser locale
console.log(date.toLocaleTimeString()); // Localized time string
console.log(date.toLocaleString());     // Combined local format

Best Practice:

  • Use toISOString() to store dates in standardized database-friendly format (UTC).

5️⃣ Date Comparisons

Example:

let date1 = new Date("2025-03-27");
let date2 = new Date("2025-04-01");

console.log(date1.getTime() < date2.getTime());  // true
console.log(date1 > date2);                      // false

Why use getTime()?

  • Direct date comparisons rely on internal valueOf conversions (which return timestamps), but using getTime() makes the logic explicit and avoids confusion.

6️⃣ Working with Timezones

JavaScript internally stores all dates in UTC, but when you display them, it's shown in local time (based on the user's system settings).

Get Timezone Info:

let date = new Date();
console.log(date.getTimezoneOffset());  // Difference from UTC in minutes

Convert to UTC:

console.log(date.toUTCString());      // Shows UTC date string
console.log(date.toISOString());      // Standard UTC format

Tip:

  • Timezone offset is negative for locations ahead of UTC (like India), and positive for behind (like the US).

7️⃣ Getting Time Difference

You can calculate durations — like how many days are left until an event.

Example:

let start = new Date("2025-01-01");
let end = new Date("2025-12-31");

let diffMs = end.getTime() - start.getTime();
let diffDays = diffMs / (1000 * 60 * 60 * 24);  // Convert ms to days

console.log(`Days between: ${diffDays}`);

Conversion Table:

UnitMultiplier
Seconds1000
Minutes1000 × 60
Hours1000 × 60 × 60
Days1000 × 60 × 60 × 24

8️⃣ Using Date.now() for Performance

Date.now() gives you the current timestamp instantly — no object creation needed!

Example:

console.log(Date.now()); // Current timestamp in ms

Measure Execution Time:

let start = Date.now();

for (let i = 0; i < 1e6; i++) {
  // Simulated task
}

let end = Date.now();
console.log(`Time taken: ${end - start} ms`);

Analogy:
Imagine starting and stopping a stopwatch — that's what Date.now() simulates.


9️⃣ Generating a Timestamp for Logging

Logging with consistent timestamps helps trace application behavior.

Example:

function getTimestamp() {
  return new Date().toISOString();
}

console.log(getTimestamp());  // "2025-03-27T09:05:45.123Z"

Best Practice:

  • Always log events using toISOString() for timezone-safe logs (especially on servers or logs shared globally).

Bonus: Real-World Use Cases

Use CaseHow to Use
Show local date/timetoLocaleString()
Store date in DBtoISOString()
Compare datesdate1.getTime() < date2.getTime()
Measure execution timeDate.now()
Calculate remaining daysdiff / (1000 * 60 * 60 * 24)
Log timestampsnew Date().toISOString()

Summary

JavaScript Date is essential for working with any time-based logic.
Create dates with new Date() — use ISO or individual components.
Extract parts using get methods, and update with set methods.
Compare and calculate differences using timestamps (getTime() or Date.now()).
Format using toDateString(), toLocaleString(), or toISOString().
Always be mindful of timezone differences in global apps.




JavaScript Arrays

1️⃣ What is an Array?

An array is a special type of object in JavaScript used to store multiple values in a single variable.

Real-world analogy:
Think of an array like a train — each coach (index) holds a passenger (value).
Each coach is uniquely identified by a number (starting from 0).

Example:

let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits); // ["Apple", "Banana", "Cherry"]

2️⃣ Creating an Array

MethodSyntaxUse CaseNotes
Literallet arr = [1, 2, 3];Most commonly usedRecommended
Constructorlet arr = new Array(1, 2, 3);Less common❌ Can be confusing
let nums = [10, 20, 30];

Constructor Caveat:

let arr = new Array(5);
console.log(arr); // [empty × 5] (creates empty array with length 5)

Avoid using new Array() with a single number — it creates empty space instead of storing the number.


3️⃣ Accessing Array Elements

OperationSyntaxDescription
Get elementarr[0]Gets value at index 0
Out-of-boundsarr[99]Returns undefined
let colors = ["Red", "Green", "Blue"];
console.log(colors[0]); // Red
console.log(colors[3]); // undefined

4️⃣ Modifying Array Elements

Arrays are mutable, so you can change individual elements using their index.

let fruits = ["Apple", "Banana", "Cherry"];
fruits[1] = "Mango";
console.log(fruits); // ["Apple", "Mango", "Cherry"]

5️⃣ Array Properties

PropertyDescription
lengthTotal number of elements
Array.isArray()Checks if a variable is an array
let nums = [10, 20, 30];
console.log(nums.length);         // 3
console.log(Array.isArray(nums)); // true

6️⃣ Adding & Removing Elements

MethodActionAdds/RemovesPosition
push()Add✔️End
pop()Remove✔️End
unshift()Add✔️Start
shift()Remove✔️Start
let arr = [1, 2, 3];
arr.push(4);      // [1, 2, 3, 4]
arr.unshift(0);   // [0, 1, 2, 3, 4]
arr.pop();        // [0, 1, 2, 3]
arr.shift();      // [1, 2, 3]

7️⃣ Iterating Over Arrays

MethodUse CaseReturns
forGeneral loopN/A
forEach()Loop without returnundefined
map()Transform each elementNew array

for Loop:

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

forEach():

arr.forEach(item => console.log(item));

map():

let squares = arr.map(num => num * num);

Use map() when you need to transform and return a new array.


8️⃣ Searching & Filtering

MethodPurposeReturns
includes()Checks existenceBoolean
find()Finds first matchSingle element
filter()Filters matching itemsArray

Examples:

let arr = [10, 20, 30, 40];
console.log(arr.includes(20)); // true
console.log(arr.find(num => num > 25)); // 30
console.log(arr.filter(num => num > 25)); // [30, 40]

9️⃣ Sorting & Reversing

sort()

  • Converts elements to strings by default!
let nums = [40, 10, 30, 20];
nums.sort();  // Incorrect for numbers: [10, 20, 30, 40] only if strings

// ✅ Correct way for numbers:
nums.sort((a, b) => a - b);

reverse()

let arr = [1, 2, 3];
arr.reverse(); // [3, 2, 1]

Sort is destructive (modifies original array).


🔟 Joining & Splitting

TaskMethodDescription
Join array → stringjoin()Takes a separator
String → arraysplit()Breaks string using a separator
let arr = ["Hello", "World"];
let str = arr.join(" ");  // "Hello World"

let newArr = str.split(" "); // ["Hello", "World"]

How JavaScript Arrays Work Internally

JavaScript arrays are objects with special behaviors:

  • Indexes (0, 1, 2, ...) are actually property keys (like '0', '1')

  • Arrays are sparse, meaning holes are allowed:

let arr = [];
arr[5] = 42;
console.log(arr); // [ <5 empty items>, 42 ]
console.log(arr.length); // 6

Internally, JavaScript tries to optimize arrays using fast-element storage (like contiguous C-style arrays), but if too many holes or non-integer keys are added, the engine deoptimizes the array.


Summary Table

FeatureMethodPurpose
Add elementspush(), unshift()Add at end/start
Remove elementspop(), shift()Remove from end/start
Check typeArray.isArray()Check if variable is an array
Iteratefor, forEach(), map()Loop through elements
Searchincludes(), find(), filter()Search/filter values
Transformmap(), sort(), reverse()Modify structure
Combine/splitjoin(), split()String ↔ Array conversion

Real-World Use Cases

  • Shopping cart: Store product items in an array

  • Calendar: Hold all events/dates as array of objects

  • Chat app: Messages stored in an array for display

Pro Tip:

Use modern array methods like map(), filter(), and reduce() for clean, functional-style JavaScript.




JavaScript Objects

1️⃣ What is an Object?

An object is a collection of properties, where each property is a key-value pair.

Real-World Analogy:
Think of an object as a person’s profile card:

  • The name (key) is like the label: "name", "age", "city".

  • The value is the actual info: "Alice", 25, "New York".

let person = {
    name: "Alice",
    age: 25,
    city: "New York"
};

📌 Behind the scenes, JavaScript stores keys as strings (or Symbols) in a special hash table, optimized for quick lookup.


🔵 2️⃣ Creating an Object

MethodSyntaxUse Case
Object Literal{}Recommended
Constructornew Object()❌ Verbose, rarely used

Object Literal (Preferred)

let car = {
    brand: "Toyota",
    model: "Corolla",
    year: 2022
};

Using new Object() (Avoid unless necessary)

let car = new Object();
car.brand = "Toyota";
car.model = "Corolla";
car.year = 2022;

3️⃣ Accessing Properties

MethodSyntaxWhen to Use
Dot Notationobj.key✅ Default and readable
Bracket Notationobj["key"]When key has spaces or is a variable
console.log(person.name);       // Alice
console.log(person["age"]);     // 25

let key = "city";
console.log(person[key]);       // New York

Internally, person.name is interpreted as person["name"].


4️⃣ Modifying Properties

Update Existing

person.age = 30;

Add New

person.country = "USA";

Delete Property

delete person.city;

Internally: Setting a property adds it to the object’s internal hash map. Deleting removes that key entirely.


5️⃣ Checking Property Existence

MethodExampleReturns
in operator"name" in persontrue/false
hasOwnProperty()person.hasOwnProperty("name")true/false

6️⃣ Looping Through Objects

Use for...in to iterate over enumerable properties:

for (let key in person) {
    console.log(`${key}: ${person[key]}`);
}

This loop includes inherited properties unless filtered using hasOwnProperty().


7️⃣ Object Methods (Functions Inside Objects)

Functions inside objects are called methods.

let student = {
    name: "Bob",
    greet: function() {
        console.log("Hi, I'm " + this.name);
    }
};

student.greet(); // Hi, I'm Bob

this keyword

  • Refers to the object calling the method.

  • It dynamically binds depending on context.


8️⃣ Object Destructuring

Destructuring allows you to extract values from an object into variables.

let { name, age } = person;
console.log(name);  // Alice
console.log(age);   // 30

Can rename variables too:

let { name: userName } = person;
console.log(userName);  // Alice

9️⃣ Useful Object Methods

MethodDescriptionExample
Object.keys(obj)Returns array of keys["name", "age", "country"]
Object.values(obj)Returns array of values["Alice", 30, "USA"]
Object.entries(obj)Returns array of [key, value] pairs[[“name”, “Alice”], …]

🔟 Copying Objects

Shallow Copy

Copies top-level properties only. Nested objects are shared by reference.

let person2 = { ...person };               // Spread
let person3 = Object.assign({}, person);   // Object.assign

Deep Copy

Creates a fully independent copy, including nested values.

let deepCopy = JSON.parse(JSON.stringify(person));

Deep copy doesn't support functions or special types like Date.


Internal Working of JavaScript Objects

JavaScript objects are implemented as hash tables:

  • Keys are always strings (or Symbols).

  • Values can be any data type.

  • Insertion & lookup are generally O(1) due to hashing.

let obj = {};
obj[true] = "bool";       // converted to string "true"
obj[1] = "num";           // converted to string "1"
obj[{ a: 1 }] = "object"; // converted to "[object Object]"

Use Map if you need keys that are truly objects and preserve type identity.


Summary Table

ConceptExampleNotes
Createlet obj = {}Literal is preferred
Accessobj.key or obj["key"]Dot is cleaner
Modifyobj.key = valueDirect assignment
Deletedelete obj.keyRemoves property
Loopfor...inLoops over keys
Copy{ ...obj } / JSON.parse(JSON.stringify())Shallow vs deep
Check existencein, hasOwnProperty()Validate keys
ConvertObject.keys(), etc.Useful for iteration

Examples:

  • User Profile: Store name, email, settings.

  • Cart Item: productId, quantity, price.

  • Calendar Event: title, date, location.


Pro Tips:

  • Avoid using numbers or objects as keys unless necessary.

  • Use Object.freeze(obj) to make an object immutable.

  • Use Object.defineProperty() for custom descriptors like non-enumerable properties.




0
Subscribe to my newsletter

Read articles from Nishant directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nishant
Nishant