JavaScript 101: The Basic Concepts Explained

JavaScript is a high-level, interpreted, dynamically typed, event-driven, prototype-based, single-threaded programming language.
Term | Meaning |
High-level | You don’t manage memory or hardware directly—JS handles it for you. |
Interpreted | Code is run line by line, not compiled ahead of time. |
Dynamically Typed | Variable types are determined at runtime. |
Event-driven | JS reacts to user events like clicks, scrolls, etc. |
Prototype-based | JS uses prototypes instead of classical classes for inheritance. |
Single-threaded | Only 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:
Area | Example Tech |
Front-end | React, Vue, Angular |
Back-end | Node.js |
Mobile Apps | React Native, Ionic |
Databases | MongoDB (via Node.js drivers) |
AI & ML | TensorFlow.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 execution | Translates and runs line-by-line |
Faster after compilation | Slower initially, but faster with JIT |
Strict with types | Dynamic 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.
Popular Engines:
Engine | Browser/Environment |
V8 | Chrome, Edge, Node.js |
Spider Monkey | Firefox |
JavaScript Core | Safari |
Internal Working:
Parsing → Code is broken into tokens
JIT Compilation → Tokens compiled into bytecode
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:
Component | Role |
Memory (Variable Env) | Stores variables and function declarations |
Call Stack | Manages function execution order |
Code Example:
let x = 10;
function sayHello() {
console.log("Hello!");
}
sayHello();
Internally:
JS stores
x = 10
in memory.Stores
sayHello
function.Adds
sayHello()
to the Call Stack and runs it.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
Element | Real-World Analogy |
let | Tells the warehouse manager to create a box |
x | Label on the box |
10 | Item 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 Type | Purpose | What Goes Here |
Call Stack | Keeps track of function calls | Primitives (number, string...) |
Memory Heap | Stores large or reference data | Objects, 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
Keyword | Scope | Can Reassign | Hoisted? | Temporal Dead Zone |
var | Function | ✅ Yes | ✅ Yes (as undefined ) | ❌ No |
let | Block ({}-scoped) | ✅ Yes | ✅ Yes (in TDZ) | ✅ Yes |
const | Block | ❌ 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:
Memory (Variable Environment)
let
,const
, andvar
declarations go here
Call Stack
- Keeps track of "who called whom" (function execution order)
Variables declared:
With
let
/const
→ Lexical EnvironmentWith
var
→ Hoisted to the top of scope
Summary:
Concept | Details |
Variable | A labeled storage in memory |
var | Function scoped, hoisted with value undefined , avoid using |
let | Block scoped, hoisted but in TDZ, best for changing values |
const | Block scoped, immutable binding, best for constants |
Primitives | Stored in Call Stack, copied by value |
Reference Types | Stored in Heap, copied by reference (same address) |
Hoisting | var is hoisted and initialized to undefined , let /const are not accessible before declaration (TDZ) |
Best Practice | Prefer 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:
Category | Data Types | Stored In |
Primitive | Number , String , Boolean , null , undefined , Symbol , BigInt | Call Stack (stored by value) |
Reference | Object , Array , Function | Heap (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
, andNaN
(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;
Comparison | null | undefined |
Meaning | Intentional absence of value | Variable declared but not assigned |
Type (typeof ) | "object" (bug) | "undefined" |
Use Case | Explicitly cleared value | JS 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:
Feature | Primitive Types | Reference Types |
Stored In | Call Stack | Heap (pointer in Call Stack) |
Copied By | Value | Reference |
Mutability | Immutable | Mutable |
Examples | Number , String , Boolean , null | Object , 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
Type | Who Performs It? | Example | Real-World Analogy |
Implicit | JavaScript (auto/coercion) | "5" + 2 → "52" | Like auto-switching between metric/imperial units |
Explicit | Developer (manual casting) | Number("5") → 5 | Manually 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
Value | Number() | String() | Boolean() |
null | 0 | "null" | false |
undefined | NaN | "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
Concept | Description |
Implicit Conversion | Auto by JS in expressions like "5" + 1 → "51" |
Explicit Conversion | You use Number() , String() , Boolean() |
Falsy Values | 0 , "" , null , undefined , NaN |
Truthy Values | Everything else: "text" , 1 , [] , {} |
+ Operator | Triggers string coercion if one is a string |
- , * , / Operators | Triggers number coercion |
NaN Check | Use Number.isNaN(value) |
Safe String Conversion | String(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
Type | Examples |
Arithmetic | + , - , * , / , % , ** |
Assignment | = , += , -= , *= , /= , %= |
Comparison | == , === , != , !== , > , < , >= , <= |
Logical | && , ` |
Bitwise | & , ` |
Ternary | condition ? value1 : value2 |
1️⃣ Arithmetic Operators (Basic Math)
Operator | Name | Example | Result |
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 6 * 2 | 12 |
/ | Division | 10 / 2 | 5 |
% | Modulus (Remainder) | 10 % 3 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
console.log(10 + 5); // 15
console.log(10 % 3); // 1
console.log(2 ** 4); // 16
2️⃣ Assignment Operators
Operator | Description | Example | Equivalent |
= | Assign | x = 10 | — |
+= | Add & assign | x += 5 | x = x + 5 |
-= | Subtract & assign | x -= 2 | x = x - 2 |
*= | Multiply & assign | x *= 3 | x = x * 3 |
/= | Divide & assign | x /= 4 | x = x / 4 |
%= | Modulo & assign | x %= 2 | x = x % 2 |
let x = 10;
x += 5;
console.log(x); // 15
3️⃣ Comparison Operators
Operator | Name | Example | Result |
== | Loose equality | 5 == "5" | true |
=== | Strict equality | 5 === "5" | false |
!= | Loose inequality | 10 != 5 | true |
!== | Strict inequality | 10 !== "10" | true |
> | Greater than | 10 > 5 | true |
< | Less than | 3 < 7 | true |
>= | Greater or equal | 5 >= 5 | true |
<= | Less or equal | 4 <= 6 | true |
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
Operator | Name | Example | Result | ||||
&& | AND | true && false | false | ||||
OR | `false | true` | true | ||||
! | NOT | !true | false |
Short-circuit behavior:
console.log(0 && "Hello"); // 0 (first falsy)
console.log(1 || "World"); // 1 (first truthy)
5️⃣ Bitwise Operators (Binary Level)
Operator | Description | Example | Binary | Result | |||
& | AND | 5 & 3 | 0101 & 0011 | 0001 (1) | |||
OR | `5 | 3` | `0101 | 0011` | 0111 (7) | ||
^ | XOR | 5 ^ 3 | 0101 ^ 0011 | 0110 (6) | |||
~ | NOT | ~5 | ~0000000000000101 | -6 | |||
<< | Left shift | 5 << 1 | 0101 << 1 | 1010 (10) | |||
>> | Right shift | 5 >> 1 | 0101 >> 1 | 0010 (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 Operator → condition ? 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
Property | Description |
.length | Returns 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
Method | Description |
.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
Method | Purpose |
.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
Method | Use 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
Sequence | Meaning |
\' | Single quote |
\" | Double quote |
\\ | Backslash |
\n | New line |
\t | Tab |
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 checksUse
String()
/.toString()
/${}
to convert typesEscape 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:
Value | Description |
Infinity | Number too large to represent |
-Infinity | Number 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:
Method | Description |
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:
Operator | Meaning |
+ | 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:
Method | Description |
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:
Method | Description |
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:
Conversion | Method |
String → Number | Number(str) , parseInt(str) |
Number → String | String(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:
Unit | Multiplier |
Seconds | 1000 |
Minutes | 1000 × 60 |
Hours | 1000 × 60 × 60 |
Days | 1000 × 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 Case | How to Use |
Show local date/time | toLocaleString() |
Store date in DB | toISOString() |
Compare dates | date1.getTime() < date2.getTime() |
Measure execution time | Date.now () |
Calculate remaining days | diff / (1000 * 60 * 60 * 24) |
Log timestamps | new 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
Method | Syntax | Use Case | Notes |
Literal | let arr = [1, 2, 3]; | Most commonly used | Recommended |
Constructor | let arr = new Array(1, 2, 3); | Less common | ❌ Can be confusing |
Literal Method (Recommended)
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
Operation | Syntax | Description |
Get element | arr[0] | Gets value at index 0 |
Out-of-bounds | arr[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
Property | Description |
length | Total 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
Method | Action | Adds/Removes | Position |
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
Method | Use Case | Returns |
for | General loop | N/A |
forEach() | Loop without return | undefined |
map() | Transform each element | New 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
Method | Purpose | Returns |
includes() | Checks existence | Boolean |
find() | Finds first match | Single element |
filter() | Filters matching items | Array |
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
Task | Method | Description |
Join array → string | join() | Takes a separator |
String → array | split() | 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
Feature | Method | Purpose |
Add elements | push() , unshift() | Add at end/start |
Remove elements | pop() , shift() | Remove from end/start |
Check type | Array.isArray() | Check if variable is an array |
Iterate | for , forEach() , map() | Loop through elements |
Search | includes() , find() , filter() | Search/filter values |
Transform | map() , sort() , reverse() | Modify structure |
Combine/split | join() , 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
Method | Syntax | Use Case |
Object Literal | {} | Recommended |
Constructor | new 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
Method | Syntax | When to Use |
Dot Notation | obj.key | ✅ Default and readable |
Bracket Notation | obj["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
Method | Example | Returns |
in operator | "name" in person | true/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
Method | Description | Example |
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
Concept | Example | Notes |
Create | let obj = {} | Literal is preferred |
Access | obj.key or obj["key"] | Dot is cleaner |
Modify | obj.key = value | Direct assignment |
Delete | delete obj.key | Removes property |
Loop | for...in | Loops over keys |
Copy | { ...obj } / JSON.parse(JSON.stringify()) | Shallow vs deep |
Check existence | in , hasOwnProperty() | Validate keys |
Convert | Object.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.
Subscribe to my newsletter
Read articles from Nishant directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
