Conditionals
In JavaScript, conditionals are used to perform different actions based on different conditions. The most common conditional statements are:
- if statement
- if...else statement
- if...else if...else statement
- switch statement
1// 1. if statement 2// Executes the code block if the condition is true 3 4const age1 = 20; 5 6if (age1 >= 18) { 7 console.log("You are an adult."); // Output: You are an adult. 8} 9 10// 2. if...else statement 11// Executes one block if condition is true, another if false 12 13const age2 = 16; 14 15if (age2 >= 18) { 16 console.log("You are an adult."); 17} else { 18 console.log("You are a minor."); // Output: You are a minor. 19} 20 21// 3. if...else if...else statement 22// Checks multiple conditions in sequence 23 24const score = 75; 25 26if (score >= 90) { 27 console.log("Grade: A"); 28} else if (score >= 75) { 29 console.log("Grade: B"); // Output: Grade: B 30} else if (score >= 60) { 31 console.log("Grade: C"); 32} else { 33 console.log("Grade: F"); 34} 35 36// 4. switch statement 37// Cleaner way to compare the same variable with many values 38 39const day = "Tuesday"; 40 41switch (day) { 42 case "Monday": 43 console.log("Start of the week"); 44 break; 45 46 case "Tuesday": 47 console.log("Second day of the week"); // Output: Second day of the week 48 break; 49 50 case "Friday": 51 console.log("Almost weekend!"); 52 break; 53 54 default: 55 console.log("It's just another day"); 56}
Template Literals
Template literals in JavaScript are string literals that allow embedded expressions, multi-line strings, and easier string interpolation. They were introduced in ES6 (ECMAScript 2015).
1// 1. String Interpolation 2const name = "Alice"; 3const age = 25; 4 5const greeting = `Hello, my name is ${name} and I am ${age} years old.`; 6console.log(greeting); 7// Output: Hello, my name is Alice and I am 25 years old. 8 9// 2. Multi-line Strings 10const poem = ` 11Roses are red, 12Violets are blue, 13JavaScript is awesome, 14And so are you! 15`; 16 17console.log(poem); 18// Output: 19// Roses are red, 20// Violets are blue, 21// JavaScript is awesome, 22// And so are you! 23 24// 3. Expression Evaluation 25const a = 5; 26const b = 10; 27 28console.log(`The sum of ${a} and ${b} is ${a + b}.`); 29// Output: The sum of 5 and 10 is 15. 30 31// 4. Function Calls Inside Template Literals 32function toUpper(str) { 33 return str.toUpperCase(); 34} 35 36const phrase = `This is ${toUpper("cool")}!`; 37console.log(phrase); 38// Output: This is COOL! 39 40// 5. Nesting Template Literals 41const personName = "Bob"; 42const job = "developer"; 43 44const message = `Hi ${personName}, you are a ${`${job}`.toUpperCase()}!`; 45console.log(message); 46// Output: Hi Bob, you are a DEVELOPER! 47 48// 6. Tagged Template Literals (Advanced Usage) 49// A tag function processes the template before rendering it 50function highlight(strings, ...values) { 51 return strings.reduce((acc, str, i) => { 52 return `${acc}${str}<b>${values[i] || ''}</b>`; 53 }, ''); 54} 55 56const language = "JavaScript"; 57const level = "advanced"; 58 59const output = highlight`Learning ${language} at an ${level} level!`; 60console.log(output); 61// Output: Learning <b>JavaScript</b> at an <b>advanced</b> level!
Arrow Functions
Arrow functions in JavaScript are a concise way to write function expressions. Introduced in ES6, they are often used for cleaner, shorter syntax -- especially in functional programming patterns.
1// 1. Basic Syntax 2const greet = () => console.log("Hello, world!"); 3greet(); // Output: Hello, world! 4 5// 2. With Parameters 6const add = (a, b) => a + b; 7console.log(add(5, 3)); // Output: 8 8 9// 3. Single Parameter (No parentheses needed) 10const square = x => x * x; 11console.log(square(4)); // Output: 16 12 13// 4. Returning an Object 14// Must wrap the object in parentheses 15const getUser = () => ({ name: "Alice", age: 30 }); 16console.log(getUser()); // Output: { name: 'Alice', age: 30 } 17 18// 5. Used in Array Methods (map, filter, reduce) 19const numbers = [1, 2, 3, 4, 5]; 20 21const doubled = numbers.map(n => n * 2); 22console.log(doubled); // Output: [2, 4, 6, 8, 10] 23 24const even = numbers.filter(n => n % 2 === 0); 25console.log(even); // Output: [2, 4] 26 27const sum = numbers.reduce((acc, n) => acc + n, 0); 28console.log(sum); // Output: 15
Rest/Spread Operator
Rest operator
Rest operator collects multiple elements into a single array. It is mainly used in function parameters and destructuring assignments. It "packs" remaining elements into an array.
1// Example 1: Rest operator in function parameters 2function greet(greeting, ...names) { 3 console.log(greeting); 4 console.log("Names:", names); // 'names' is an array of all remaining arguments 5} 6 7greet("Hello", "Alice", "Bob", "Charlie"); 8// Output: 9// Hello 10// Names: [ 'Alice', 'Bob', 'Charlie' ] 11 12// Example 2: Rest operator in array destructuring 13const numbers = [1, 2, 3, 4, 5]; 14 15const [first, second, ...rest] = numbers; 16 17console.log(first); // Output: 1 18console.log(second); // Output: 2 19console.log(rest); // Output: [3, 4, 5] 20 21// Example 3: Rest operator in object destructuring 22const user = { 23 id: 101, 24 name: "Alice", 25 age: 30, 26 city: "New York" 27}; 28 29const { id, ...otherDetails } = user; 30 31console.log(id); // Output: 101 32console.log(otherDetails); // Output: { name: 'Alice', age: 30, city: 'New York' }
Spread operator
The spread operator expands or "spreads" elements of an array, object, or iterable. It is mainly used to copy or combine arrays/objects, or pass elements as individual arguments. It "unpacks" elements from an array or object.
1// Example 1: Copying an array 2const arr1 = [1, 2, 3]; 3const arr2 = [...arr1]; 4 5console.log(arr2); // Output: [1, 2, 3] 6 7// Example 2: Merging arrays 8const fruits = ['apple', 'banana']; 9const vegetables = ['carrot', 'lettuce']; 10 11const food = [...fruits, ...vegetables]; 12console.log(food); // Output: ['apple', 'banana', 'carrot', 'lettuce'] 13 14// Example 3: Spreading a string into an array of characters 15const word = "hello"; 16const chars = [...word]; 17 18console.log(chars); // Output: ['h', 'e', 'l', 'l', 'o'] 19 20// Example 4: Copying an object 21const obj1 = { a: 1, b: 2 }; 22const obj2 = { ...obj1 }; 23 24console.log(obj2); // Output: { a: 1, b: 2 } 25 26// Example 5: Merging objects 27const defaults = { theme: 'light', fontSize: 14 }; 28const settings = { fontSize: 18, fontWeight: 'bold' }; 29 30const mergedSettings = { ...defaults, ...settings }; 31 32console.log(mergedSettings); 33// Output: { theme: 'light', fontSize: 18, fontWeight: 'bold' } 34 35// Example 6: Using spread to pass array elements as function arguments 36const numbers = [5, 10, 15]; 37 38function multiply(a, b, c) { 39 return a * b * c; 40} 41 42console.log(multiply(...numbers)); // Output: 750
Destructuring
Destructuring is a syntax introduced in ES6 that allows you to unpack values from arrays or properties from objects into distinct variables. This makes it easier and cleaner to extract data without writing repetitive code.
Array Destructuring
It is used to extract values from an array and assign them to variables in a concise way. Variables correspond to the position/index in the array.
1const numbers = [10, 20, 30]; 2 3// Without destructuring 4const first = numbers[0]; 5const second = numbers[1]; 6 7// With destructuring 8const [a, b, c] = numbers; 9 10console.log(a); // 10 11console.log(b); // 20 12console.log(c); // 30
Object Destructuring
It is used to extract properties from objects and assign them to variables with matching property names. Can also assign to new variable names or provide default values.
1const user = { 2 name: "Alice", 3 age: 25, 4 city: "New York" 5}; 6 7// Basic destructuring 8const { name, age } = user; 9 10console.log(name); // Alice 11console.log(age); // 25 12 13// Assign to new variable names 14const { name: userName, city: userCity } = user; 15console.log(userName); // Alice 16console.log(userCity); // New York 17 18// Provide default value 19const { country = "USA" } = user; 20console.log(country); // USA 21 22// Using rest operator to collect remaining properties 23const { name: n, ...otherProps } = user; 24console.log(n); // Alice 25console.log(otherProps); // { age: 25, city: 'New York' }
Parameter Defaults
Parameter Defaults in JavaScript allow you to specify default values for function parameters. If the function is called without that argument or with undefined, the default value is used instead.
- It makes functions more flexible and prevents errors when arguments are missing.
- It avoids manual checks inside the function to set default values.
1// Example 1: 2function greet(name = "Guest", greeting = "Hello") { 3 console.log(`${greeting}, ${name}!`); 4} 5 6greet(); // Output: Hello, Guest! 7greet("Alice"); // Output: Hello, Alice! 8greet("Bob", "Good morning"); // Output: Good morning, Bob! 9 10// Example 2: 11// Default parameter with calculation 12function multiply(a, b = 2) { 13 return a * b; 14} 15 16console.log(multiply(5)); // Output: 10 (b defaults to 2) 17console.log(multiply(5, 3)); // Output: 15 18 19// Example 3: 20// Using default parameter with destructured object 21function createUser({name = "Anonymous", age = 18} = {}) { 22 console.log(`Name: ${name}, Age: ${age}`); 23} 24 25createUser(); // Name: Anonymous, Age: 18 26createUser({name: "Alice"}); // Name: Alice, Age: 18 27createUser({name: "Bob", age: 25}); // Name: Bob, Age: 25
ES Modules
ES Modules (or ESM) are the official standardized module system in JavaScript introduced in ES6 (ECMAScript 2015). They allow you to split your code into reusable pieces (modules), which can export variables, functions, or classes and import them where needed. ESM is supported natively in modern browsers and in Node.js (with .mjs extension or "type": "module" in package.json).
Exporting
1// utils.js 2 3// Example 1: 4// Named exports 5export const PI = 3.14159; 6 7export function add(a, b) { 8 return a + b; 9} 10 11export class Calculator { 12 subtract(a, b) { 13 return a - b; 14 } 15} 16 17// Example 2: 18// Default export 19export default function greet(name) { 20 return `Hello, ${name}!`; 21}
Importing
1// app.js 2 3// Import named exports 4import greet, { PI, add, Calculator } from './utils.js'; 5 6console.log(PI); // 3.14159 7console.log(add(5, 3)); // 8 8 9const calc = new Calculator(); 10console.log(calc.subtract(10, 4)); // 6 11 12console.log(greet('Alice')); // Hello, Alice!
Ternary Operator
The ternary operator in JavaScript is a shorthand way to write simple if-else statements. It’s called “ternary” because it takes three operands.
1condition ? expressionIfTrue : expressionIfFalse
- If condition is true, it evaluates and returns expressionIfTrue.
- If condition is false, it evaluates and returns expressionIfFalse.
1// Example 1: Basic ternary operator to check voting eligibility 2const age = 20; 3const canVote = age >= 18 ? "Yes, can vote" : "No, too young"; 4console.log(canVote); // Output: Yes, can vote 5 6// Example 2: Check if a number is even or odd 7const number = 7; 8const result = (number % 2 === 0) ? "Even" : "Odd"; 9console.log(result); // Output: Odd 10 11// Example 3: Assign default value if a variable is falsy 12const username = ""; 13const displayName = username ? username : "Guest"; 14console.log(displayName); // Output: Guest 15 16// Example 4: Nested ternary operators for grading system 17const score = 85; 18const grade = score > 90 ? "A" 19 : score > 75 ? "B" 20 : score > 50 ? "C" 21 : "F"; 22console.log(grade); // Output: B
Nullish Coalescing Operator
The Nullish Coalescing Operator (??) in JavaScript is a logical operator that returns the right-hand operand when the left-hand operand is null or undefined, and otherwise returns the left-hand operand.
1let result = value1 ?? value2;
- If value1 is not null or undefined, result will be value1.
- If value1 is null or undefined, result will be value2.
1// Example 1: 2// Basic usage of ?? with null 3let userName = null; 4let defaultName = "Guest"; 5 6// If userName is null or undefined, use defaultName 7let name = userName ?? defaultName; 8console.log("Example 1:", name); // Output: Guest 9 10// Example 2: 11// Difference between || and ?? 12let count = 0; 13 14// || considers 0 as falsy, so it falls back to 10 15let result1 = count || 10; 16 17// ?? only checks for null or undefined, so 0 is valid 18let result2 = count ?? 10; 19 20console.log("Example 2a (using ||):", result1); // Output: 10 21console.log("Example 2b (using ??):", result2); // Output: 0 22 23// Example 3: 24// Using ?? with undefined 25let age; 26 27let displayAge = age ?? 18; 28console.log("Example 3:", displayAge); // Output: 18 29 30// Example 4: 31// Comparison table (Optional for demonstration) 32const examples = [ 33 { value: null, description: "null" }, 34 { value: undefined, description: "undefined" }, 35 { value: false, description: "false" }, 36 { value: 0, description: "0 (zero)" }, 37 { value: '', description: "empty string" }, 38]; 39 40examples.forEach(({ value, description }) => { 41 const orResult = value || "fallback"; 42 const nullishResult = value ?? "fallback"; 43 console.log(`\nValue: ${description}`); 44 console.log(` Using || : ${orResult}`); 45 console.log(` Using ?? : ${nullishResult}`); 46});
Array Methods
coming soon ...
Object Methods
coming soon ...
Promises & Async/Await
coming soon ...