0% found this document useful (0 votes)
2 views22 pages

JavaScript Fundamentals - Complete Guide - Introdu...

Uploaded by

sambhavraj83
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

JavaScript Fundamentals - Complete Guide - Introdu...

Uploaded by

sambhavraj83
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Here is your comprehensive, expanded JavaScript Fundamentals Complete Guide.

Every
single topic now includes a clear, easy-to-understand explanation in simple English, along with
complete code examples to make things crystal clear.
Introduction
JavaScript Kya Hai?

JavaScript is a high-level, lightweight, and interpreted programming language. Initially, it was


created to make web pages alive and interactive (like handling button clicks, showing
animations, or dropping down menus).
Today, it is a multi-paradigm language, meaning it supports different coding styles
(object-oriented, functional, imperative). It is the only programming language that runs natively
inside your web browser, but thanks to modern tools, it can now run anywhere—including on
your laptop as a backend language.
Engine aur Runtime

●​ JavaScript Engine: A program or interpreter inside the browser that reads your
JavaScript code and converts it into machine code that the computer's CPU can actually
understand. Every major browser has its own engine. For example, Google Chrome and
[Link] use V8, Mozilla Firefox uses SpiderMonkey, and Apple Safari uses
JavaScriptCore.
●​ Runtime Environment: The engine alone isn't enough to build practical apps. It needs a
"home" or surroundings to talk to the outside world. The runtime environment provides
extra tools and APIs (like the ability to print messages to a console or set a timer)
alongside the engine to make the code useful.
Browser vs [Link]

While both use the same JavaScript language and the V8 engine, their surroundings are
completely different:
●​ Browser Environment: This is made for the frontend. It gives you access to the DOM (to
change HTML elements), the window object, localStorage (to save data in the browser),
and network tools to fetch data from the internet. It cannot access your computer's local
hard drive for security reasons.
●​ [Link] Environment: This is made for the backend (server-side). It takes JavaScript out
of the browser. It does not have a DOM or a window object, but it gives you access to
your operating system's features, like reading and writing files (fs module), creating an
HTTP web server, and connecting directly to databases.
Execution Process

When you run JavaScript, it doesn't just execute line-by-line instantly. It goes through three
main steps:
1.​ Parsing: The engine reads the source code and breaks it down into a tree structure
called an Abstract Syntax Tree (AST) to check if your syntax is correct.
2.​ Compilation: JavaScript uses Just-In-Time (JIT) Compilation. This means the code is
compiled into machine-readable bytecode right before it runs, instead of being compiled
ahead of time like C++ or Java.
3.​ Execution: The engine runs the compiled bytecode using a combination of an interpreter
(for speed) and a compiler (to optimize parts of the code that run repeatedly).
Variables & Data Types
var, let, const

Variables are containers used to store data values. JavaScript has three ways to declare them,
each with different rules regarding where they can be accessed (scope) and whether they can
be changed.

JavaScript
// 1. var: Old way. Function-scoped. Can be re-declared and updated.​
var a = 10;​
var a = 15; // No error! We re-declared it.​
a = 20; // Updated.​

// 2. let: Modern way. Block-scoped (only lives inside {}). Cannot be re-declared in the same scope,
but can be updated.​
let b = 20;​
// let b = 25; // ERROR! Cannot re-declare.​
b = 25; // Works fine! Value updated.​

// 3. const: Modern way. Block-scoped. Short for "constant". Cannot be re-declared or updated.​
const c = 30;​
// c = 35; // ERROR! You cannot reassign a const variable.​

Primitive vs Reference Types

●​ Primitive Types: These store the actual value directly in the memory (on the Stack). They
are simple data types and are immutable (cannot be altered directly). When you copy a
primitive value, it makes a brand-new copy of the actual value.
○​ Types: string, number, boolean, undefined, null, symbol, bigint.
●​ Reference Types: These don't store the value directly. Instead, they store a pointer or
reference address to a location in memory (on the Heap) where the actual data lives.
When you copy a reference type, you are just copying the address pointer, not the actual
data itself.
○​ Types: Object, Array, Function.
JavaScript
// Primitive Example: Value is copied cleanly​
let x = 5;​
let y = x; // y gets a copy of 5​
y = 10; // changing y doesn't change x​
[Link](x); // 5​

// Reference Example: Address pointer is shared​
let user1 = { name: "Amit" };​
let user2 = user1; // user2 points to the exact same object in memory​
[Link] = "Rahul";​
[Link]([Link]); // "Rahul" - user1 was affected!​

Type Conversion (Explicit)

Type conversion happens when you manually and intentionally convert a value from one data
type to another using built-in JavaScript functions.

JavaScript
let strNum = "42";​
let realNum = Number(strNum); // Converts String to Number​
[Link](typeof realNum); // "number"​

let age = 25;​
let strAge = String(age); // Converts Number to String​
[Link](typeof strAge); // "string"​

let zero = 0;​
let boolZero = Boolean(zero); // Converts Number to Boolean (0 becomes false)​
[Link](boolZero); // false​

Type Coercion (Implicit)


Type coercion is when JavaScript automatically changes a data type behind the scenes
because it is trying to make an operation work, even if the types don't match.

JavaScript
// Concatenation: When adding a string and a number, JS converts the number to a string​
[Link]("5" + 3); // "53" (String)​

// Subtraction: The minus operator only works with numbers, so JS converts the string to a number​
[Link]("5" - 3); // 2 (Number)​

// Boolean Coercion: true is treated as 1, false as 0 in math operations​
[Link](true + 1); // 2 (because 1 + 1 = 2)​

Operators
Arithmetic Operators

These operators are used to perform mathematical calculations on numbers.

JavaScript
let a = 10;​
let b = 3;​

[Link](a + b); // 13 (Addition)​
[Link](a - b); // 7 (Subtraction)​
[Link](a * b); // 30 (Multiplication)​
[Link](a / b); // 3.3333... (Division)​
[Link](a % b); // 1 (Remainder/Modulus: 10 divided by 3 leaves a remainder of 1)​
[Link](a ** b); // 1000 (Exponentiation: 10 to the power of 3)​

Comparison Operators

These operators compare two values and return a boolean value: either true or false.
JavaScript
// == Loose Equality: Checks values only, ignores data type (performs coercion)​
[Link](5 == "5"); // true​

// === Strict Equality: Checks BOTH the value and the data type (No coercion)​
[Link](5 === "5"); // false (because one is a number, one is a string)​

// != Loose Inequality and !== Strict Inequality​
[Link](10 != "10"); // false (values are same)​
[Link](10 !== "10"); // true (types are different)​

[Link](10 > 5); // true (Greater than)​
[Link](10 <= 10); // true (Less than or equal to)​

Logical Operators

These operators are used to combine multiple boolean conditions or values together.

JavaScript
// && (AND): Returns true ONLY if both sides are true​
[Link](true && false); // false​

// || (OR): Returns true if AT LEAST ONE side is true​
[Link](true || false); // true​

// ! (NOT): Inverts the value (turns true to false, and false to true)​
[Link](!true); // false​

Ternary Operator

The ternary operator is a short, one-line way of writing an if-else statement. It takes three
parts: a condition, an expression to execute if the condition is true, and an expression if it is
false.
Syntax: condition ? value_if_true : value_if_false;

JavaScript
let age = 18;​
let status = age >= 18 ? "Adult" : "Minor";​
[Link](status); // "Adult"​

Nullish Coalescing (??)

The nullish coalescing operator is a safety operator that returns its right-hand side value only
when its left-hand side value is either null or undefined. If the left side is anything else (even
empty string "" or 0), it will pick the left side.

JavaScript
let username = null;​
let defaultName = username ?? "Guest"; ​
[Link](defaultName); // "Guest" (since username was null)​

let score = 0;​
let finalScore = score ?? 100;​
[Link](finalScore); // 0 (picked score because 0 is not null or undefined)​

Optional Chaining (?.)

Optional chaining is a safe way to access deeply nested object properties. If any part of the
chain is missing (null or undefined), it stops immediately and returns undefined instead of
crashing your entire program with an error.
JavaScript
let user = {​
profile: { name: "Amit" }​
};​

// Safe access​
[Link]([Link]?.name); // "Amit"​

// Trying to access something that doesn't exist​
[Link]([Link]?.city); // undefined (No crash!)​

// Without `?.`, this line would crash the app:​
// [Link]([Link]); // ERROR: Cannot read properties of undefined​

Control Flow
if-else

An if-else statement tells JavaScript to run a specific block of code only if a certain condition is
met. If that condition is false, it can check other conditions using else if, or fallback to an else
block.

JavaScript
let marks = 75;​

if (marks >= 90) {​
[Link]("A+");​
} else if (marks >= 70) {​
[Link]("A"); // This runs because 75 is >= 70​
} else {​
[Link]("B");​
}​

switch

The switch statement evaluates an expression and matches its value against multiple case
clauses. It is a cleaner alternative to writing many chained if-else statements when checking a
single value.

JavaScript
let day = 2;​

switch (day) {​
case 1:​
[Link]("Monday");​
break; // Stops the switch execution​
case 2:​
[Link]("Tuesday"); // This runs​
break;​
default:​
[Link]("Other day"); // Runs if no cases match​
}​

Loops

Loops are used to run the same block of code over and over again for a specific number of
times, or as long as a condition remains true.

JavaScript
// 1. for loop: Used when you know exactly how many times you want to run the code.​
for (let i = 0; i < 3; i++) {​
[Link]("For loop iteration:", i);​
}​

// 2. while loop: Runs as long as the specified condition evaluates to true.​
let count = 0;​
while (count < 3) {​
[Link]("While loop count:", count);​
count++;​
}​

// 3. do...while loop: Always runs the code block AT LEAST ONCE before checking the condition.​
let num = 5;​
do {​
[Link]("This will print exactly once.");​
} while (num < 2);​

break & continue

●​ continue: Skips the rest of the code inside the current loop iteration and jumps directly
to the next loop cycle.
●​ break: Exits and stops the loop entirely, ignoring any remaining cycles.

JavaScript
for (let i = 1; i <= 5; i++) {​
if (i === 3) {​
continue; // Skips printing 3, goes straight to i = 4​
}​
if (i === 5) {​
break; // Completely terminates the loop when i reaches 5​
}​
[Link](i); // Prints: 1, 2, 4​
}​

Functions
Function Declaration

A function declaration is a standard way of defining a reusable block of code with a specific
name. It is hoisted, meaning it can be called even before it is written in the code file.

JavaScript
function greet(name) {​
return `Hello, ${name}`;​
}​

[Link](greet("Rahul")); // "Hello, Rahul"​

Function Expression

A function expression is when you define a function and assign it inside a variable. Function
expressions are not hoisted, so you cannot use them before they are declared.

JavaScript
const greetExpression = function(name) {​
return `Hello, ${name}`;​
};​

[Link](greetExpression("Amit")); // "Hello, Amit"​

Arrow Functions

Introduced in ES6, arrow functions give us a shorter syntax to write functions. They don't need
the function keyword or a return keyword if written on a single line. They also handle the this
keyword differently (they inherit this from their surroundings).

JavaScript
// Single line arrow function (Implicit return)​
const greetArrow = (name) => `Hello, ${name}`;​
const add = (a, b) => a + b;​

[Link](greetArrow("Sonia")); // "Hello, Sonia"​
[Link](add(5, 10)); // 15​

Callback Functions
A callback function is a function that you pass as an argument into another function. The
receiving function can then execute that callback function later on when an operation finishes.

JavaScript
function processData(callback) {​
[Link]("Processing started...");​
// Simulate a 1-second delay​
setTimeout(() => {​
callback("Success: Data received!");​
}, 1000);​
}​

// Passing an arrow function as a callback​
processData((message) => {​
[Link](message); // Prints after 1 second​
});​

Higher Order Functions

A Higher-Order Function is a function that does at least one of two things: it either takes one
or more functions as arguments (like a callback), or it returns a whole new function as its
output.

JavaScript
// This function RETURNS a new function​
function multiplier(factor) {​
return function(number) {​
return number * factor;​
};​
}​

const double = multiplier(2); // double is now a function that multiplies by 2​
[Link](double(5)); // 10​
Scope & Hoisting
Global Scope

Any variable declared outside of all functions or code blocks {} is in the global scope. It can be
accessed and modified from absolutely anywhere in your entire JavaScript file.

JavaScript
let globalVar = "I am global";​

function test() {​
[Link](globalVar); // Accessible inside functions​
}​
test();​

Function Scope

When a variable is declared inside a function (using var, let, or const), it belongs to that
function's scope. It is locked inside that function and cannot be accessed from the outside
world.

JavaScript
function saySecret() {​
var secret = "shhh!";​
[Link](secret); // Works inside​
}​
// [Link](secret); // ERROR! secret is not defined out here​

Block Scope

Variables declared with let and const inside a block of curly braces {} (like an if statement or a
loop) are block-scoped. They only exist inside those specific curly braces. (var does not
respect block scope).

JavaScript
if (true) {​
let blockVar = "Visible only here";​
var functionVar = "Visible outside block too";​
}​
// [Link](blockVar); // ERROR! blockVar is locked in the block​
[Link](functionVar); // Works! Because var ignores block scope​

Hoisting

Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope
before executing the code.
●​ Variables declared with var are hoisted but initialized with undefined.
●​ Variables declared with let and const are hoisted but are not initialized, causing an error
if you try to use them early.

JavaScript
[Link](x); // Prints: undefined (due to var hoisting)​
var x = 5;​

// [Link](y); // ERROR: Cannot access 'y' before initialization​
let y = 10;​

Temporal Dead Zone (TDZ)

The Temporal Dead Zone is the period of time/area of code from the start of a block until the
line where a let or const variable is actually declared. If you try to touch or read that variable
while it is stuck in this zone, JavaScript will crash with a ReferenceError.
JavaScript
{​
// --- TDZ Starts for variable 'myVar' ---​
// [Link](myVar); // ERROR! Accessing variable while it's inside the TDZ​

let myVar = "Hello"; // --- TDZ Ends here ---​
[Link](myVar); // Works safely! "Hello"​
}​

Objects
Object Creation

An object is a collection of related data and behaviors stored as key-value pairs. You can think
of it as a container representing a real-world thing (like a person or a car).

JavaScript
const person = {​
name: "Rahul",​
age: 25,​
// A function inside an object is called a Method​
greet() {​
return `Hi, I'm ${[Link]}`;​
}​
};​

[Link]([Link]); // Accessing property: "Rahul"​
[Link]([Link]()); // Running method: "Hi, I'm Rahul"​

this keyword

The this keyword refers to the execution context—basically, it points to the object that is
currently running or calling the code.
●​ In a regular object method, this points to the object itself.
●​ In a standalone global function, this points to the global window object.

JavaScript
const car = {​
brand: "Toyota",​
showBrand() {​
[Link]([Link]); // 'this' points to the car object​
}​
};​
[Link](); // "Toyota"​

Destructuring

Destructuring is a clean syntax that lets you unpack values from objects or arrays directly into
individual, separate variables.

JavaScript
const user = { name: "Rahul", age: 25, city: "Delhi" };​

// Unpacking name and age properties directly​
const { name, age } = user;​

[Link](name); // "Rahul"​
[Link](age); // 25​

Spread Operator (...)

The spread operator allows you to copy all or parts of an existing object (or array) into a brand
new object. It makes cloning and updating data simple.
JavaScript
const basePerson = { name: "Rahul", age: 25 };​

// Copy all fields from basePerson and add a new city field​
const updatedPerson = { ...basePerson, city: "Delhi" };​

[Link](updatedPerson); // { name: "Rahul", age: 25, city: "Delhi" }​

Arrays
map()

The map() method loops through every element in an array, runs a function on each item, and
returns a brand new array containing the transformed results. It does not change the original
array.

JavaScript
const nums = [1, 2, 3];​
const doubled = [Link](n => n * 2);​

[Link](doubled); // [2, 4, 6]​

filter()

The filter() method tests every item in an array against a condition. It returns a new array
containing only the elements that passed the test (true).

JavaScript
const nums = [1, 2, 3, 4, 5];​
const even = [Link](n => n % 2 === 0);​

[Link](even); // [2, 4]​

reduce()

The reduce() method executes a reducer function on each element of the array, passing the
result from the calculation on the previous element. It boils the entire array down into a single
final value (like a sum or total).

JavaScript
const nums = [1, 2, 3, 4];​
// acc = accumulator (running total), curr = current item in loop​
const sum = [Link]((acc, curr) => acc + curr, 0);​

[Link](sum); // 10 (1+2+3+4)​

find()

The find() method searches an array and returns the very first element that passes a specific
test condition. If nothing matches, it returns undefined.

JavaScript
const nums = [1, 2, 3, 4];​
const found = [Link](n => n > 2);​

[Link](found); // 3 (It is the first number greater than 2)​

some() & every()

●​ some(): Checks if at least one element in the array passes the condition. Returns true or
false.
●​ every(): Checks if every single element in the array passes the condition. Returns true
only if all pass.

JavaScript
const nums = [1, 2, 3];​

[Link]([Link](n => n > 2)); // true (3 is greater than 2)​
[Link]([Link](n => n > 0)); // true (all numbers are greater than 0)​

sort()

The sort() method sorts the items of an array in place (modifies the original array). By default, it
sorts items as strings, so you must pass a comparison function to sort numbers properly.

JavaScript
const arr = [3, 1, 4, 2];​
// Comparison function (a - b) sorts numbers in ascending order​
[Link]((a, b) => a - b);​

[Link](arr); // [1, 2, 3, 4]​

DOM Manipulation
Selecting Elements

DOM (Document Object Model) manipulation means using JavaScript to select, change, or
style HTML elements on a live webpage. To change something, you must select it first.
JavaScript
// Selects a single element by its unique ID attribute​
const heading = [Link]("title");​

// Selects ALL elements matching a CSS selector (returns a NodeList)​
const boxes = [Link](".box");​

Event Handling

An event is an action that happens on the webpage—like a user clicking a button, typing text, or
scrolling. An event handler listens for that action and triggers code when it occurs.

HTML
<button id="myBtn">Click Me</button>​

JavaScript
// JavaScript to listen to the click​
const btn = [Link]("#myBtn");​

[Link]("click", () => {​
[Link]("Button clicked!");​
});​

Event Delegation

Instead of adding individual event listeners to dozens of separate child items (which slows
down performance), event delegation means adding one single listener to their common
parent. Because of event bubbling, clicks on the child items bubble up to the parent anyway.
HTML
<ul id="itemList">​
<li>Item 1</li>​
<li>Item 2</li>​
</ul>​

JavaScript
const list = [Link]("#itemList");​

[Link]("click", (e) => {​
// [Link] is the actual exact item that was clicked​
if ([Link] === "LI") {​
[Link]("Clicked item text:", [Link]);​
}​
});​

Form Handling

Form handling is capturing data entered by a user into input fields when they hit submit, and
stopping the browser's default behavior (which reloads the whole page automatically).

HTML
<form id="userForm">​
<input type="text" name="username" placeholder="Enter Name">​
<button type="submit">Submit</button>​
</form>​
JavaScript
const form = [Link]("#userForm");​

[Link]("submit", (e) => {​
[Link](); // STOPS the webpage from reloading automatically​

const value = [Link]; // Grab the input value​
[Link]("Submitted Username:", value);​
});​

Related Interview Questions (Quick Answers)


●​ Difference between var, let, and const?​
var is function-scoped and hoisted with undefined. let and const are block-scoped and
stay in the Temporal Dead Zone until initialized. const values cannot be reassigned; let
values can.
●​ Explain hoisting and Temporal Dead Zone.​
Hoisting moves declarations to the top of the scope before running code. The TDZ is the
unsafe region from the start of a block until a let/const is declared where accessing them
causes an error.
●​ What is the difference between == and ===?​
== checks for loose equality by automatically converting types (coercion) to match. ===
checks for strict equality without type conversion—both value and type must match
perfectly.
●​ How does this behave in arrow functions vs regular functions?​
Regular functions have their own dynamic this context depending on who called them.
Arrow functions do not get their own this; they look outside and borrow it from the
surrounding code context.
●​ Difference between map(), filter(), and reduce()?​
map() changes every item and returns an array of the same length. filter() removes items
based on a condition and returns a shorter array. reduce() combines all elements into a
single output value.
●​ What is event delegation and why is it useful?​
It is a technique where you put a single event listener on a parent element instead of
putting multiple listeners on separate child elements. It saves memory and handles
dynamically added children automatically.
●​ Explain optional chaining and nullish coalescing.​
Optional chaining (?.) safely stops execution and returns undefined if an object property
is missing, preventing a crash. Nullish coalescing (??) provides a fallback value only if the
left side is null or undefined.

You might also like