
javaScript Everything
- Aditya Dhawle
- Basic , Java script
- May 2, 2025
Table of Contents
Complete JavaScript Syllabus
๐ฆ Chapter 1: Variables & Declarations
๐ง What are Variables?
Variables are containers that hold data. They help us store, reuse, and update information in JavaScript โ from simple values like numbers to complex data like arrays and objects. Think of a variable as a box with a name on it. You can put something inside it (a value), and later check or change what's inside. In JavaScript, you create these boxes using keywords: var , let , or const .
๐งช var, let, and const โ Line-by-Line Comparison
๐ง var โ Old and risky
- Scoped to functions, not blocks
- Can be redeclared and reassigned
- Hoisted to the top with undefined value
var score = 10;
var score = 20; // OK
๐ป let โ Modern and safe
- Scoped to blocks ( {} )
- Can be reassigned but not redeclared
- Hoisted, but stays in the Temporal Dead Zone (TDZ)
let age = 25;
age = 30; // โ
let age = 40; // โ Error (same block)
๐ const โ Constant values
- Scoped to blocks
- Cannot be reassigned or redeclared
- Value must be assigned at declaration
- TDZ applies here too
const PI = 3.14;
PI = 3.14159; // โ Error
๐ But: If const holds an object/array, you can still change its contents:
const student = { name: "Riya" };
student.name = "Priya"; // โ
OK
student = {}; // โ Error
๐ฅ Scope in Real Life
- Block Scope โ Code inside {} like in loops, if , etc.
- Function Scope โ Code inside a function
- let and const follow block scope
- var ignores block scope โ which leads to bugs.
{
var x = 5;
let y = 10;
const z = 15;
}
console.log(x); // โ
5
console.log(y); // โ ReferenceError
console.log(z); // โ ReferenceError
๐งจ Hoisting
JavaScript prepares memory before running code.It moves all declarations to the top โ this is called hoisting.
But:
- var is hoisted and set to undefined
- let and const are hoisted but not initialized โ so accessing them early gives ReferenceError
console.log(a); // undefined
var a = 10;
console.log(b); // โ ReferenceError
let b = 20;
๏ธ โ ๏ธCommon Confusions (JS Reality Checks)
- const doesnโt make things fully constant. It protects the variable, not the value
- var is outdated โ itโs better to use let and const .
- let and const behave similarly, but const gives more safety โ use it when youโre not planning to reassign.
๐ง Mindset Rule
Use const by default. Use let only when you plan to change the value.Avoid var โ it belongs to the past.
๐งช Practice Zone
- Declare your name and city using const , and your age using let .
- Try this and observe the result:
let x = 5;
let x = 10;
- Guess the output:
console.log(count);
var count = 42;
- Create a const object and add a new key to it โ does it work?
- Try accessing a let variable before declaring it โ what error do you see?
- Change a const array by pushing a value. Will it throw an error?
What is the purpose of variables in JavaScript?
Which statement about 'var' is TRUE?
What happens when you try to redeclare a 'let' variable in the same block?
Which is TRUE about 'const'?
Can a const object be modified?
Which variable is accessible outside the block?
What is printed when you access a var before its declaration?
Accessing a let variable before it's declared results in:
What happens if you try to reassign a const variable?
What is the recommended mindset when using variables?
๐ง Chapter 2: Data Types + Type System
๐ฆ What Are Data Types?
In JavaScript, every value has a type. These types define what kind of data is being stored โ a number, text, boolean, object, etc. There are two categories:
- Primitive types โ stored directly
- Reference types โ stored as memory references.
๐น Primitive Data Types
- String โ Text โhelloโ , โAdityaโ
- Number โ Any numeric value 3 , -99 , 3.14
- Boolean โ True or false true , false
- Undefined โ Variable declared but not assigned let x; โ x is undefined
- Null โ Intentional empty value let x = null;
- Symbol โ Unique identifier (rarely used)
- . BigInt โ Very large integers 123456789012345678901234567890n
๐น Reference Data Types
- Object โ { name: โHarshโ, age: 26 }
- Array โ [10, 20, 30]
- Function โ function greet() {} These are not copied directly, but by reference.
๐ typeof Operator
Used to check the data type of a value:
typeof "Your Name" // "string"
typeof 99 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" โ known bug
typeof [] // "object"
typeof {} // "object"
typeof function(){} // "function"
Note: typeof null === โobjectโ is a bug, but has existed since the early days of JS.
๐ Type Coercion (Auto-Conversion)
JavaScript auto-converts types in some operations:
"5" + 1 // "51" โ number converted to string
"5" - 1 // 4 โ string converted to number
true + 1 // 2
null + 1 // 1
undefined + 1 // NaN
๐จ Loose vs Strict Equality
- == compares value with type conversion
- === compares value + type (no conversion)
5 == "5" // true
5 === "5" // false
Always prefer === for accurate comparisons
NaN โ Not a Number
typeof NaN // "number"
Even though it means โNot a Numberโ, NaN is actually of type number . This is because operations like 0 / 0 or parseInt("abc") still produce a numeric result โ just an invalid one.
๐ฆ Truthy and Falsy Values
Falsy values:
false , 0 , "" , null , undefined , NaN Everything else is truthy, including: โ0โ , โfalseโ , [] , {} , function(){}
Practice Zone
What is the type of 'Hello' in JavaScript?
Which of the following is a reference type in JavaScript?
What does typeof null return?
What is the typeof a function?
What is the result of '5' + 1 in JavaScript?
What is the result of true + 1?
What does 5 == '5' return?
What does 5 === '5' return?
Which of these is a falsy value in JavaScript?
What is the typeof NaN?
๐ Chapter 3: Operators
๐ง What are Operators?
Operators are special symbols or keywords in JavaScript used to perform operations on values (operands). Youสผll use them in calculations, comparisons, logic, assignments, and even type checks. Think of them as the verbs of your code โ they act on data.
โ Arithmetic Operators
Used for basic math.
+ // addition
- // subtraction
* // multiplication
/ // division
% // modulus (remainder)
** // exponentiation (power)
Example:
let a = 10, b = 3;
console.log(a + b); // 13
console.log(a % b); // 1
console.log(2 ** 3); // 8
๐งฎ Assignment Operators
Assign values to variables.
= // assigns value
+= // a += b => a = a + b
-= // a -= b
*=, /=, %=
Example:
let score = 5;
score += 2; // score = 7
๐งพ Comparison Operators
== // equal (loose)
=== // equal (strict โ value + type)
!= // not equal (loose)
!== // not equal (strict)
> < >= <=
Example:
console.log(5 == "5"); // true
console.log(5 === "5"); // false
โ Logical Operators
Used to combine multiple conditions
&& // AND โ both must be true
|| // OR โ either one true
! // NOT โ negates truthiness
Example:
let age = 20, hasID = true;
if (age >= 18 && hasID) {
console.log("Allowed");
}
๐ Unary Operators
Used on a single operand.
+ // tries to convert to number
- // negates
++ // increment
-- // decrement
typeof // returns data type
Example:
let x = "5";
console.log(+x); // 5 (converted to number)
โ Ternary Operator (Conditional)
Shorthand for ifโฆelse
condition ? valueIfTrue : valueIfFalse
Example:
let score = 80;
let grade = score > 50 ? "Pass" : "Fail";
๐งช typeof Operator
typeof 123 // "number"
typeof "hi" // "string"
typeof null // "object" (JS bug)
typeof [] // "object"
typeof {} // "object"
typeof function(){} // "function"
๐ง Mindset
Operators make logic happen. They help you make decisions, combine values, and create expressions. Try to:
- Use === instead of == to avoid type bugs.
- se ternary for quick decisions, not complex ones
- Think in truthy/falsy when using && , || , ! .
โ Common Confusions
โ5โ + 1 is โ51โ (string concat), but โ5โ - 1 is 4 (number subtract)
!!value is a quick trick to convert anything into a boolean
Pre-increment ( ++i ) vs post-increment ( i++ ) return different results
What is the result of 10 % 3?
What does 2 ** 3 evaluate to?
What is the final value of score if score = 5; score += 2;
What does 5 == '5' return?
What does 5 === '5' return?
What is the result of true && false?
What is the result of false || true?
What does !true return?
What is typeof undefined?
What is typeof null?
Which one returns the value before incrementing?
What is returned by: (5 > 3) ? 'Yes' : 'No'?
What is typeof function(){} in JS?
What is the result of '5' - 1?
๐งญ Chapter 4: Control Flow
๐ฆ What is Control Flow?
Control flow decides which code runs, when it runs, and how many times it runs. It's like decision-making + direction in your JavaScript program. If operators are the verbs, control flow is the traffic signal.
๐งฑ if, else if, else
if (condition) {
// runs if condition is true
} else if (anotherCondition) {
// runs if first was false, second is true
} else {
// runs if none are true
}
โ Example:
if (condition) {
// runs if condition is true
} else if (anotherCondition) {
// runs if first was false, second is true
} else {
// runs if none are true
}
๐ switch-case
Great for checking one variable against many values
switch (value) {
case value1:
// code
break;
case value2:
// code
break;
default:
// fallback
}
Example:
let fruit = "apple";
switch (fruit) {
case "banana":
console.log("Yellow");
break;
case "apple":
console.log("Red");
break;
default:
console.log("Unknown");
}
๐ Early Return Pattern
Used in functions to exit early if some condition fails.
function checkAge(age) {
if (age < 18) return "Denied";
return "Allowed";
}
This avoids deep nesting and makes logic cleaner.
๏ธ Common Confusions
switch-case executes all cases after a match unless you break
else if chain works top-down โ order matters
You can use truthy/falsy values directly in if
๐ง Mindset
Control flow = conditional storytelling. It helps your program make choices and respond differently to different inputs. Write readable branches. Avoid nesting too deep โ use early return if needed
Which block runs if the condition in 'if' is true?
In an else if chain, which condition gets checked first?
When does the else block run?
What does the default case in switch do?
Why is early return used in functions?
Whatโs a common bug with switch-case statements?
๐ Chapter 5: Loops
๐ Why Loops?
Loops help us repeat code without rewriting it. If a task needs to be done multiple times (e.g., printing 1โ10, going through an array, or checking each character in a string), loops are the backbone.
๐ for Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
- Start from i = 0
- Run till i < 5
- Increase i each time
๐ while Loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
๐ do-while Loop
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
- Runs at least once, even if condition is false
โ break and continue
- break : Exit loop completely
- continue : Skip current iteration and move to next
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i); // Skips 3
}
๐ for-of โ Arrays & Strings
for (let char of "Sheryians") {
console.log(char);
}
- Works on anything iterable (arrays, strings)
๐งฑ forEach โ Arrays
let nums = [10, 20, 30];
nums.forEach((num) => {
console.log(num);
});
- Cleaner than for for arrays, but you canสผt break/return
๐งฑ for-in โ Objects (and arrays if needed)
let user = { name: "Harsh", age: 26 };
for (let key in user) {
console.log(key, user[key]);
}
- Goes over keys in objects
๏ธ Common Confusions
- for-in is for objects, not arrays (may cause issues with unexpected keys)
- forEach canโt use break or continue
- while and do-while work best when number of iterations is unknown
๐ง Mindset
What is the primary purpose of loops?
In a for loop, what usually happens first?
What does the condition in a for loop do?
When is the condition checked in a while loop?
Whatโs unique about do-while loops?
What will this print?\nfor(let i=0;i<3;i++) { console.log(i); }
What causes an infinite loop?
What does the break keyword do?
What does the continue keyword do?
What gets printed?\nfor(let i=1; i<=3; i++) {\n if(i==2) continue;\n console.log(i);\n}
What can for-of loop iterate over?
Which is the best use for for-in loop?
Whatโs a key limitation of forEach?
What will do-while run if the condition is false initially?
What argument does forEach provide to the callback?
Why is using for-in on arrays not recommended?
Which loop is best when you don't know how many times you'll run?
๐งฎ Chapter 6: Functions
๐ง What are Functions?
Functions are blocks of reusable logic. Instead of repeating the same task again and again, wrap it in a function and reuse it with different inputs.
Think of a function like a vending machine:
- Input: you give money + item code
- Output: it gives you the item
- Logic: hidden inside
๐ Function Declarations
function greet() {
console.log("Welcome to Sheryians!");
}
greet();
You define it once, then call it whenever needed.
๐งพ Parameters vs Arguments
function greet(name) {
console.log("Hello " + name);
}
greet("Harsh");
- name is a parameter
- โHarshโ is the argument you pass
๐ Return Values
function sum(a, b) {
return a + b;
}
let total = sum(5, 10); // total is 15
- return sends back a result to wherever the function was called
- After return , function exits
๐งฐ Function Expressions
const greet = function () {
console.log("Hello!");
};
- Functions stored in variables
- Cannot be hoisted (you canสผt call them before theyสผre defined)
๐น Arrow Functions
const greet = () => {
console.log("Hi!");
};
Cleaner syntax
No own this , no arguments object
๐ง Default + Rest + Spread
unction multiply(a = 1, b = 1) {
return a * b;
}
function sum(...nums) {
return nums.reduce((acc, val) => acc + val, 0);
}
let nums = [1, 2, 3];
console.log(sum(...nums)); // Spread
- a = 1 โ default parameter
- โฆnums โ rest parameter
- โฆnums (in call) โ spread operator
๐ฏ First-Class Functions
JavaScript treats functions as values:
- Assign to variables
- Pass as arguments
- Return from other functions
function shout(msg) {
return msg.toUpperCase();
}
function processMessage(fn) {
console.log(fn("hello"));
}
processMessage(shout);
๐ง Higher-Order Functions (HOF)
Functions that accept other functions or return functions.
nction createMultiplier(x) {
return function (y) {
return x * y;
};
}
let double = createMultiplier(2);
console.log(double(5)); // 10
๐ Closures & Lexical Scope
Closures = when a function remembers its parent scope, even after the parent has finished.
function outer() {
let count = 0;
return function () {
count++;
console.log(count);
};
}
let counter = outer();
counter(); // 1
counter(); // 2
Even after outer is done, counter still remembers count .
โก IIFE โ Immediately Invoked Function Expression
(function () {
console.log("Runs immediately");
})();
Used to create private scope instantly
๐ Hoisting: Declarations vs Expressions
hello(); // works
function hello() {
console.log("Hi");
}
greet(); // error
const greet = function () {
console.log("Hi");
};
- Declarations are hoisted
- Expressions are not
๏ธ ๏ธCommon Confusions
- Arrow functions donสผt have their own this
- You canสผt break out of forEach
- Closures often trap old variable values
- Return vs console.log โ donโt mix them up
๏ธ ๏ธ๐ง Mindset
Functions are your logic blocks + memory holders (via closure). They keep your code clean, DRY, and reusable.
Why do we use functions in JavaScript?
In function greet(name), what is 'name'?
What does the return keyword do?
Why can't you call a function expression before it's defined?
What is the default value of b in: function add(a, b = 5)?
What does ...nums do in function sum(...nums)?
What makes functions first-class in JS?
What is a Higher-Order Function?
What is a Closure in JavaScript?
In this code, what keeps 'count' remembered?\nfunction outer() {\n let count = 0;\n return function() {\n count++;\n console.log(count);\n };\n}
Why use an IIFE (Immediately Invoked Function Expression)?
๐งฐ Chapter 7: Arrays
๐ง What is an Array?
An array is like a row of boxes, where each box holds a value and has an index (0, 1, 2โฆ). Arrays help you store multiple values in a single variable โ numbers, strings, or even objects/functions.
```javascript let fruits = ["apple", "banana", "mango"]; ```๐ Creating & Accessing Arrays
let marks = [90, 85, 78];
console.log(marks[1]); // 85
marks[2] = 80; // Update index 2
- Indexing starts from 0
- You can access, update, or overwrite values by index
๏ธ Common Array Methods
๐งฑ Modifiers (Change original array)
let arr = [1, 2, 3, 4];
arr.push(5); // Add to end
arr.pop(); // Remove last
arr.shift(); // Remove first
arr.unshift(0); // Add to start
arr.splice(1, 2); // Remove 2 items starting at index 1
arr.reverse(); // Reverse order
๐ Extractors (Donโt modify original array)
let newArr = arr.slice(1, 3); // Copy from index 1 to 2
arr.sort(); // Lexical sort by default
๐ Iteration Methods
map() Returns a new array with modified values.
let prices = [100, 200, 300];
let taxed = prices.map(p => p * 1.18);
filter() Filters out elements based on a condition.
let nums = [1, 2, 3, 4];
let even = nums.filter(n => n % 2 === 0);
reduce() Reduces the array to a single value.
let total = nums.reduce((acc, val) => acc + val, 0);
forEach() Performs an action for each element (but returns undefined).
nums.forEach(n => console.log(n));
find(), some(), every()
nums.find(n => n > 2); // First match
nums.some(n => n > 5); // At least one true
nums.every(n => n > 0); // All true
๏ธ Destructuring & Spread
let [first, second] = ["a", "b", "c"];
let newArr = [...nums, 99]; // Spread to copy & add
What is an array in JavaScript?
What index does a JavaScript array start at?
What does arr.push(5) do?
What does arr.pop() do?
What does arr.shift() remove?
Which method adds to the beginning of an array?
What does arr.splice(1,2) do?
Which method reverses the array order?
What does arr.slice(1,3) return?
What does map() return?
What is filter() used for?
What does reduce() return?
Whatโs the key difference between forEach and map?
What does find() return?
What does some() return?
What does every() check for?
What does [...arr, 10] do?
Which method mutates the original array?
๐งฑ Chapter 8: Objects
๐ง What is an Object?
Objects in JavaScript are like real-world records โ a collection of key-value pairs. They help us store structured data (like a student, a product, or a user profile).
let student = {
name: "Ravi",
age: 21,
isEnrolled: true
};
๐ Key-Value Structure
Keys are always strings (even if you write them as numbers or identifiers)
Values can be anything โ string, number, array, object, function, etc.
console.log(student["name"]); // Ravi
console.log(student.age); // 21
๐ Dot vs Bracket Notation
Use dot notation for fixed key names
Use bracket notation for dynamic or multi-word keys
student["full name"] = "Ravi Kumar"; // โ
student.course = "JavaScript"; // โ
๐ Nesting and Deep Access
Objects can have nested objects (objects inside objects)
let user = {
name: "Amit",
address: {
city: "Delhi",
pincode: 110001
}
};
console.log(user.address.city); // Delhi
๏ธ Object Destructuring
You can extract values directly:
let { name, age } = student;
For nested objects:
let {
address: { city }
} = user;
๐ Looping Through Objects
for-in loop
for (let key in student) {
console.log(key, student[key]);
}
Object.keys(), Object.values(), Object.entries()
Object.keys(student); // ["name", "age", "isEnrolled"]
Object.entries(student); // [["name", "Ravi"], ["age", 21], ...]
๐ฆ Copying Objects
Shallow Copy (one level deep)
let newStudent = { ...student };
let newOne = Object.assign({}, student);
Deep Copy (nested levels)
let deepCopy = JSON.parse(JSON.stringify(user));
โ Note: JSON-based copy works only for plain data (no functions, undefined, etc.)
โ Optional Chaining
Avoids errors if a nested property is undefined:
console.log(user?.address?.city); // Delhi
console.log(user?.profile?.email); // undefined (no error)
๐ง Computed Properties
You can use variables as keys:
let key = "marks";
let report = {
[key]: 89
};
๏ธ Common Confusions
- Shallow copy copies only the first level
- for-in includes inherited keys (be cautious!)
- delete obj.key removes the property
- Spread โ deep copy
๏ธ ๐ง Mindset
Objects are structured state โ perfect for modeling anything complex: a user, a form, a product, etc. Use destructuring, chaining, and dynamic keys wisely.
What is the basic structure of a JavaScript object?
What type are keys in JavaScript objects?
What types can values in an object be?
When is bracket notation required?
What does for-in loop iterate over in objects?
What does Object.keys(obj) return?
What does Object.entries(obj) return?
Which method copies an object shallowly?
What can JSON deep copy NOT handle?
What does typeof {} return?
How to check if a value is an array?
Does spread operator create a deep copy?
What does Object.assign({}, obj) do?
Which is NOT true about JS objects?