Skip to content

Latest commit

ย 

History

History
1303 lines (898 loc) ยท 34.2 KB

File metadata and controls

1303 lines (898 loc) ยท 34.2 KB

Back to Javascript Home Page

โœ… Basic Topics

These are fundamentals every JavaScript developer must know:


What is JavaScript?

JavaScript is a high-level, interpreted, lightweight, and multi-paradigm programming language that is one of the core technologies of the web, alongside HTML and CSS.

It allows developers to build interactive, dynamic, and responsive user experiences in the browser, and also power server-side applications using environments like Node.js. ๐Ÿš€๐Ÿ–ฅ๏ธ๐Ÿ’ก

๐Ÿ“Œ Key Characteristics:

  • Interpreted: Runs directly in the browser (or in Node.js) without the need for compilation.
  • Dynamically typed: You donโ€™t need to define variable types explicitly.
  • Single-threaded: Uses one call stack, but handles async tasks via the event loop.
  • Prototype-based: Inheritance is done using prototypes instead of classical classes (though class syntax exists now).
  • Multi-paradigm: Supports functional, procedural, and object-oriented programming styles.

๐Ÿ“œ A Brief History:

  • Created in 1995 by Brendan Eich in just 10 days at Netscape.
  • Originally called Mocha, then LiveScript, and finally JavaScript (for marketing reasons, not related to Java).
  • Standardized as ECMAScript (ES), with ES6 (2015) being the most influential modern update. ๐Ÿ“…๐Ÿ“˜๐Ÿ“ˆ

๐ŸŒ Where is JavaScript Used?

  • Client-side (Browser): DOM manipulation, form validation, UI interactivity.
  • Server-side: Backend APIs with Node.js, Express.js, etc.
  • Mobile Apps: Frameworks like React Native, Ionic.
  • Desktop Apps: Electron-based apps like VSCode, Slack.
  • Game Development: 2D/3D games using libraries like Phaser or Three.js.
  • IoT & Robotics: With platforms like Johnny-Five.

๐Ÿ’ฌ Why Learn JavaScript?

  • Itโ€™s the only programming language that natively runs in browsers.
  • Massive community, endless job opportunities, and powerful ecosystem.
  • Acts as a gateway to learning frontend frameworks (React, Vue, Angular) and full-stack development.

๐Ÿงช Simple Example:

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

console.log(greet("Vishnu")); // Output: Hello, Vishnu!

Back to Top


JavaScript Engine & How It Runs in the Browser

JavaScript doesnโ€™t work on its own โ€” it needs a JavaScript engine to interpret and execute the code. Every modern browser comes with its own JS engine that runs your code behind the scenes.

Letโ€™s break down how it works, from engine to execution. ๐Ÿ› ๏ธ๐Ÿงฉ๐Ÿ”

๐Ÿง  What is a JavaScript Engine?

A JavaScript Engine is a program that takes your JS code, parses it, optimizes it, and finally executes it line by line.

Modern JS engines do much more than just interpretation โ€” they compile, optimize, and recompile code to make it fast.

๐Ÿ“Œ Popular JS Engines:

  • V8 โ€“ Chrome, Edge, Node.js
  • SpiderMonkey โ€“ Firefox
  • JavaScriptCore โ€“ Safari
  • Chakra โ€“ (Old) Microsoft Edge

๐Ÿงฉ Main Components of a JS Engine

  1. Parser: Breaks down your code into a syntax tree (AST โ€“ Abstract Syntax Tree).
  2. Interpreter: Quickly converts AST to bytecode and starts executing it.
  3. Compiler (JIT): Just-In-Time compiler that takes frequently used code and compiles it into optimized machine code for faster execution.
  4. Garbage Collector: Automatically frees memory that's no longer needed.

๐Ÿงช Example Flow:
Your Code โ†’ Parser โ†’ AST โ†’ Bytecode โ†’ Optimized Machine Code

๐ŸŒ€ How JavaScript Runs in the Browser

JavaScript code runs inside a browserโ€™s environment, where the JS engine is part of a bigger system including:

๐Ÿ“ฆ Web APIs
๐Ÿงต Call Stack
๐Ÿ“ค Callback Queue
โณ Event Loop

๐Ÿ“‘ Execution Steps in the Browser:

  1. Load HTML โ†’ CSS โ†’ JS

    • The browser loads and parses the HTML.
    • If it hits a <script> tag, it pauses rendering and sends JS to the engine.
  2. Parsing & Compilation

    • JS engine parses the code into tokens and builds an AST.
    • Bytecode is generated and compiled by the JIT compiler if needed.
  3. Execution via Call Stack

    • Synchronous code runs immediately via the call stack.
    • Asynchronous operations (setTimeout, fetch) are sent to Web APIs.
  4. Asynchronous Handling

    • After completing, async tasks move to the callback queue.
    • The event loop checks if the call stack is empty, and then pushes callback tasks to be executed.

๐Ÿ” Visual Simplification:

JavaScript Code
   โ†“
JavaScript Engine (V8)
   โ†“
Parse โ†’ AST โ†’ Bytecode โ†’ Optimized Code
   โ†“
Execution in Browser (Call Stack + Web APIs + Event Loop)

๐Ÿ’ฅ Key Takeaways:

  • JS Engine handles execution, but the browser provides the environment (DOM, timers, fetch).
  • Modern engines are blazing fast thanks to JIT compilation and smart memory management.
  • The event loop enables JavaScript to be asynchronous even though it's single-threaded.

Back to Top


Code Editors & Setup

While JavaScript can be written in any plain text editor, using a modern code editor improves your speed, efficiency, and debugging skills. ๐Ÿ’ก

๐Ÿ”ง Recommended Code Editors:

  • Visual Studio Code (VS Code) โ€“ Most popular, rich extensions, built-in terminal, Git support.
  • Sublime Text โ€“ Lightweight and fast.
  • WebStorm โ€“ Full-featured but paid.

โš™๏ธ Suggested Setup (for Beginners):

  1. Install VS Code
  2. Add Extensions:
    • ESLint ๐Ÿงน
    • Prettier ๐ŸŽจ
    • JavaScript Snippets โšก
  3. Enable autosave and format-on-save for better consistency.

๐Ÿ”ฅ Bonus:

You can also try out JavaScript instantly in the browser using tools like:

Back to Top


Variables

Variables are containers that store data. In JavaScript, you can declare variables using var, let, or const. Choosing the right one affects the behavior, scope, and mutability of your code. ๐Ÿ“Œ๐Ÿ“šโš™๏ธ

๐Ÿ”น var, let, and const

Keyword Scope Reassignable Redeclarable Hoisted Use Case
var Function โœ… โœ… โœ… (undefined) Legacy code
let Block โœ… โŒ โœ… (TDZ*) Preferred for mutable values
const Block โŒ โŒ โœ… (TDZ*) Preferred for constants

*TDZ = Temporal Dead Zone: Variable exists but can't be accessed before declaration ๐ŸงŸโ€โ™‚๏ธโš ๏ธ๐ŸงŠ

๐Ÿ”ธ Examples:

var name = "Alice";
let age = 25;
const country = "India";

๐ŸŸข var is function-scoped, allows redeclaration, and hoists with undefined.

๐ŸŸก let is block-scoped, doesn't allow redeclaration in the same scope, and hoists with TDZ.

๐Ÿ”ด const is block-scoped and must be initialized. It doesnโ€™t allow reassignment.

๐Ÿ” Scope Behavior Example:

if (true) {
  var a = 10;
  let b = 20;
  const c = 30;
}

console.log(a); // โœ… 10
console.log(b); // โŒ ReferenceError
console.log(c); // โŒ ReferenceError

๐Ÿ“Ž var leaks out of the block โ€” not recommended for block-scoped code! ๐Ÿ”“๐Ÿšจ๐Ÿ“›

๐Ÿ”’ const and Mutability

Using const doesnโ€™t make the value immutable โ€” only the binding.

const arr = [1, 2, 3];
arr.push(4);     // โœ… Works
arr = [5, 6];    // โŒ Error: assignment to constant variable

So, use const by default, and only switch to let if reassignment is needed. โœ…๐Ÿ”๐Ÿ›ก๏ธ

โœ… Best Practices

  • Prefer const unless you know the variable will change.
  • Use let when mutation is required.
  • Avoid var in modern code unless working with legacy systems.

Back to Top


Data Types

JavaScript is a dynamically typed language, meaning you donโ€™t have to declare variable types โ€” the type is determined at runtime. ๐ŸŽฏ๐Ÿ’ก๐Ÿ•’

It has two major categories of data types:

๐Ÿงฑ 1. Primitive Data Types (Immutable, stored by value)

  • Number โ†’ 123, 3.14, -42
  • String โ†’ "Hello", 'World', `Template`
  • Boolean โ†’ true, false
  • null โ†’ Intentional absence of value
  • undefined โ†’ Declared but not assigned
  • Symbol โ†’ Unique and immutable identifier (ES6)
  • BigInt โ†’ For arbitrarily large integers (ES2020)
let name = "Alice";
let age = 30;
let isLoggedIn = true;
let id = Symbol("id");
let big = 1234567890123456789012345678901234567890n;

๐Ÿ“Œ Primitives are compared by value and are immutable. That means once created, their value canโ€™t be changed (though variables can point to a new one). ๐Ÿ”๐ŸŽˆ๐Ÿ”

๐Ÿ—ƒ๏ธ 2. Reference Data Types (Mutable, stored by reference)

  • Object โ†’ { name: "John" }
  • Array โ†’ [1, 2, 3]
  • Function โ†’ function() {} or arrow functions
  • Date, RegExp, etc.
let user = { name: "John", age: 25 };
let colors = ["red", "green", "blue"];

๐Ÿ“Ž These are stored by reference and are mutable โ€” modifying them affects the original. โš ๏ธ

๐Ÿงช Checking Data Types

Use typeof:

typeof "hello"       // "string"
typeof 123           // "number"
typeof null          // "object" ๐Ÿ˜ฑ (quirk!)
typeof undefined     // "undefined"
typeof {}            // "object"
typeof []            // "object"
typeof (() => {})    // "function"

๐Ÿ” Note: typeof null returns "object" โ€” this is a long-standing bug in JavaScript. ๐Ÿž๐Ÿ“Ž๐Ÿงฑ

๐Ÿ“ Type Conversion

JavaScript does implicit and explicit type conversion (type coercion).

"5" + 1     // "51" โ†’ string concatenation
"5" - 1     // 4   โ†’ string converted to number
Number("123") // 123
Boolean("")   // false

๐Ÿ”„ This can lead to confusing bugs, so understanding coercion is vital. โš–๏ธ๐Ÿšจ๐Ÿ”ง

๐Ÿ”š Summary

  • JavaScript has 7 primitive types and multiple reference types.
  • Always be cautious with comparisons and coercion.
  • Use typeof, Array.isArray(), and strict equality === for clarity.

๐Ÿง  Knowing your data types makes debugging and designing logic much easier! ๐ŸŽฏ๐Ÿ”๐Ÿ“˜

Back to Top


Operators

Operators are special symbols used to perform operations on operands (variables and values). They are the building blocks of logic in any JavaScript program. ๐Ÿงฑโš’๏ธ๐Ÿš€

โž— Arithmetic Operators โž•โž–โœ–๏ธ

Used to perform mathematical operations.

  • + Addition
  • - Subtraction
  • * Multiplication
  • / Division
  • % Modulus (remainder)
  • ** Exponentiation (ES6)
  • ++ Increment
  • -- Decrement
let x = 10, y = 3;
x + y      // 13
x % y      // 1
x ** y     // 1000

๐Ÿ“Œ Arithmetic operators work on numbers and sometimes strings (like with +). ๐ŸŽฒ๐Ÿ“๐Ÿงฎ

๐Ÿ” Comparison Operators ๐Ÿงชโš–๏ธ๐Ÿ“Š

Used to compare two values. Returns a Boolean.

  • == Equal to (with coercion)
  • === Strictly equal (no coercion)
  • != Not equal
  • !== Strictly not equal
  • > Greater than
  • < Less than
  • >= Greater than or equal
  • <= Less than or equal
5 == "5"      // true
5 === "5"     // false
10 > 3        // true

โœ… Prefer === and !== for accurate comparisons. ๐Ÿšซ๐Ÿ’ก๐Ÿ“

๐Ÿง  Logical Operators ๐Ÿงฉ๐Ÿ”—๐ŸŽฏ

Used to combine logical expressions.

  • && AND
  • || OR
  • ! NOT
true && false   // false
true || false   // true
!true           // false

๐Ÿ’ก Logical operators are essential for control flow and conditionals. ๐Ÿ”๐Ÿงฒ๐Ÿ”“

๐Ÿ“ Assignment Operators ๐Ÿช„๐Ÿงพ๐ŸŽ

Used to assign values to variables.

  • =
  • +=, -=, *=, /=, %=, **=
let a = 5;
a += 3;    // a = a + 3 โ†’ 8

๐Ÿ“Œ These help write cleaner, more concise code. ๐Ÿงผ๐Ÿ”ก๐Ÿงพ

๐Ÿ”ข Bitwise Operators โš™๏ธ๐Ÿ” ๐Ÿงฉ

Used for binary operations on 32-bit integers.

  • & AND
  • | OR
  • ^ XOR
  • ~ NOT
  • << Left shift
  • >> Right shift
  • >>> Zero-fill right shift
5 & 1      // 1
5 | 1      // 5
5 ^ 1      // 4

โš ๏ธ Rarely used in regular web dev, but powerful for low-level ops. ๐Ÿงฌ๐Ÿ”Œ๐Ÿง 

โ” Ternary Operator (Conditional) ๐Ÿ”€๐Ÿงญ๐ŸŽญ

A shorthand for if...else:

let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";  // "Adult"

Clean and expressive for simple conditional assignments! โœ๏ธ

๐Ÿง  Summary

  • Know the differences between == and ===
  • Use logical operators for conditions and flow
  • Ternary is your best friend for quick decisions
  • Understand bitwise, even if you rarely use it

๐Ÿ“š Mastering operators improves your coding fluency drastically! ๐ŸŽฏ๐Ÿง ๐Ÿ’ช

Back to Top


Type Conversion & Coercion

JavaScript is a dynamically typed language, which means variables can hold any type of data, and the engine automatically converts types when necessary. This behavior is called type coercion, and you can also convert types manually using type conversion. ๐Ÿง โš’๏ธ๐Ÿงช

๐Ÿง™โ€โ™‚๏ธ Type Conversion (Explicit) โœ๏ธ๐Ÿ“๐Ÿ› ๏ธ

You explicitly convert data from one type to another using built-in functions.

  • To String: String(value) or value.toString()
  • To Number: Number(value), parseInt(), parseFloat()
  • To Boolean: Boolean(value)
String(123);      // "123"
Number("456");    // 456
Boolean(0);       // false

๐Ÿ“Œ Always use explicit conversion when you want full control over the type. ๐ŸŽ›๏ธ๐Ÿงผ๐Ÿ“

๐ŸŽฉ Type Coercion (Implicit) โœจ๐Ÿ”ฎ๐Ÿ”€

JavaScript automatically converts types behind the scenes in certain operations.

'5' + 1     // "51" (number 1 is coerced to string)
'5' - 1     // 4   (string '5' is coerced to number)
true + 1    // 2   (true is coerced to 1)
false + '2' // "false2"

๐Ÿ“Œ Coercion can lead to unexpected bugs if not well understood. ๐Ÿ”๐Ÿž๐Ÿ˜…

๐Ÿ“Š Truthy & Falsy Values โš–๏ธ๐Ÿงช๐Ÿ’ญ

When converting to Boolean, JavaScript treats some values as falsy, and everything else as truthy.

Falsy Values:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

Everything else is truthy, including:

  • '0'
  • 'false'
  • []
  • {}
Boolean("")     // false
Boolean([])     // true
Boolean(0)      // false
Boolean("0")    // true

๐Ÿง  This plays a huge role in conditionals (if, while, etc.). ๐Ÿ›ก๏ธ๐Ÿ”—๐Ÿงญ

โš ๏ธ Common Gotchas ๐Ÿ˜ฌ๐Ÿงจ๐Ÿงฉ

null == undefined   // true
null === undefined  // false

[] == false         // true
[] === false        // false

'5' == 5            // true
'5' === 5           // false

โœ… Use strict equality (===) to avoid bugs due to coercion. ๐Ÿ”๐Ÿงฏ๐Ÿ“Œ

๐Ÿ’ก Summary

  • Explicit Conversion = You choose the type.
  • Implicit Coercion = JavaScript chooses the type (sometimes weirdly).
  • Know your truthy/falsy values.
  • Avoid confusion: prefer === over ==.

๐ŸŽฏ Understanding this is crucial to becoming a confident JS developer! ๐Ÿง ๐Ÿš€โœ…

Back to Top


Conditionals

Conditionals let your program make decisions based on certain conditions. You use them to control the flow of execution. ๐Ÿ“ˆโš™๏ธ๐Ÿ›ฃ๏ธ

โœ… if, else if, and else ๐Ÿ“๐Ÿ”๐Ÿ“ฆ

The most basic and widely used control structure.

let age = 20;

if (age >= 18) {
  console.log("You're an adult.");
} else if (age > 12) {
  console.log("You're a teenager.");
} else {
  console.log("You're a child.");
}

๐Ÿง  You can have multiple else if blocks, but only one else. ๐Ÿงฑ๐Ÿงญโš™๏ธ

๐Ÿ”„ switch Statement ๐Ÿ”˜๐ŸŽš๏ธ๐ŸŽฏ

Used for multiple possible values of a single expression. It's more elegant than long if-else chains when checking equality.

const fruit = "apple";

switch (fruit) {
  case "apple":
    console.log("It's red.");
    break;
  case "banana":
    console.log("It's yellow.");
    break;
  default:
    console.log("Unknown fruit.");
}

๐Ÿ“Œ Don't forget to use break to avoid fall-through behavior. ๐Ÿšซโ›“๏ธโฌ

โšก Ternary Operator โ“โณโš™๏ธ

A shorthand if-else, useful for short conditional logic.

let age = 16;
let access = age >= 18 ? "Granted" : "Denied";
console.log(access); // "Denied"

โœ… Use ternary for simple conditions only. Avoid nesting for readability. ๐Ÿช„๐ŸŒŸ๐Ÿ“‰

๐Ÿงช Logical Operators in Conditionals ๐Ÿ”—๐Ÿง ๐Ÿ“š

  • && (AND): All conditions must be true
  • || (OR): At least one must be true
  • ! (NOT): Inverts a condition
if (isLoggedIn && userRole === "admin") {
  // do something
}

if (!isEmailVerified) {
  // ask to verify
}

๐Ÿ“Œ Combine logical operators with conditionals for powerful decision-making logic. ๐Ÿ”Œ๐ŸŽฏ๐Ÿงฐ

๐Ÿง  Best Practices

  • Use === instead of == to avoid unexpected coercion.
  • Keep ternary usage minimal and readable.
  • Don't over-nest conditionals โ€” extract logic into functions if needed.

๐ŸŽฏ In summary, conditionals are the brain of your logic in JavaScript. Mastering them helps you write dynamic, decision-based programs! ๐Ÿง ๐Ÿ“Š๐Ÿš€

Back to Top


Loops

Loops allow you to repeat a block of code multiple times, either for a fixed number of times or until a condition is met. They're essential for working with arrays, objects, or performing repetitive tasks. ๐Ÿ”ง๐Ÿ”๐Ÿ“ฆ

๐Ÿ”„ for Loop ๐Ÿงฎ๐Ÿ“๐Ÿ“˜

Most commonly used loop when the number of iterations is known.

for (let i = 0; i < 5; i++) {
  console.log("Number:", i);
}
  • Initialization: let i = 0
  • Condition: i < 5
  • Increment: i++

๐Ÿ“Œ Best for fixed-length iteration, like looping over indices. ๐Ÿงพ๐ŸŽฏ๐Ÿ“…

๐Ÿ” while Loop โณ๐Ÿ”ƒ๐Ÿ‘ฃ

Runs as long as the condition is true.

let i = 0;
while (i < 5) {
  console.log("While Loop:", i);
  i++;
}

Useful when the number of iterations isnโ€™t known beforehand. ๐Ÿ•ต๏ธโ€โ™‚๏ธ๐Ÿ“ˆ๐ŸŒ€

๐Ÿ”‚ do...while Loop ๐Ÿšช๐Ÿ”๐Ÿงฉ

Executes the loop at least once, even if the condition is false initially.

let i = 0;
do {
  console.log("Do While:", i);
  i++;
} while (i < 5);

๐Ÿ›‘ Use only when you must run the block at least once. ๐Ÿ“๐Ÿ”„๐ŸŽฌ

๐Ÿ“ฆ for...of Loop (ES6) ๐Ÿงฐ๐Ÿ“ฌ๐Ÿงญ

Used to loop over iterables (arrays, strings, etc.).

const fruits = ["apple", "banana", "mango"];

for (const fruit of fruits) {
  console.log(fruit);
}

โœ”๏ธ Cleaner and more readable when working with values. ๐ŸŽ๐Ÿงผ๐Ÿ“ฆ

๐Ÿงฑ for...in Loop ๐Ÿ—‚๏ธ๐Ÿงพ๐Ÿ”

Used to loop over enumerable properties of objects.

const user = { name: "Alice", age: 25 };

for (const key in user) {
  console.log(key, user[key]);
}

โš ๏ธ Avoid for arrays โ€“ use for...of or for instead. ๐Ÿ“›๐Ÿ›‘๐Ÿ“‰

๐Ÿ›‘ break and continue ๐Ÿ”š๐ŸŽฏ๐Ÿ”€

  • break: Exits the loop entirely.
  • continue: Skips the current iteration and moves to the next.
for (let i = 0; i < 5; i++) {
  if (i === 3) break;
  console.log(i); // 0, 1, 2
}

โš™๏ธ Use wisely to control loop flow effectively. ๐Ÿง ๐Ÿšง๐Ÿ•น๏ธ

โœ… Best Practices ๐Ÿ“Œ๐Ÿ“˜๐Ÿง 

  • Use for...of for clean iteration over arrays and strings.
  • Avoid infinite loops: always ensure your condition changes.
  • Prefer functional methods (map, filter, reduce) for array processing when possible.

๐ŸŽฏ Loops are a backbone of repetitive logic โ€” mastering all types gives you the flexibility to tackle any logic scenario with elegance! ๐Ÿ› ๏ธ๐Ÿ”‚๐ŸŒˆ

Back to Top


Functions

Functions are reusable blocks of code designed to perform a particular task. They help keep your code modular, readable, and maintainable. You can define a function once and use it multiple times. ๐Ÿ’ก๐Ÿ”‚๐Ÿ“š

๐Ÿ”น Function Declaration vs Function Expression ๐Ÿ“๐Ÿ†š๐Ÿงพ

Function Declaration:

function greet(name) {
  return `Hello, ${name}!`;
}
  • Hoisted (can be called before declaration)
  • Has a name

Function Expression:

const greet = function(name) {
  return `Hello, ${name}!`;
};
  • Not hoisted
  • Often used for anonymous functions

๐Ÿ“Œ Use expressions for inline logic and declarations for reusable named logic. ๐Ÿง ๐Ÿ“ฆ๐Ÿ”ง

๐Ÿ”น Arrow Functions (ES6) โžก๏ธ๐Ÿน๐Ÿš€

A shorter syntax for writing functions. Useful for small, concise functions.

const add = (a, b) => a + b;
  • No this, arguments, or super binding
  • Cannot be used as constructors
  • Great for callbacks and one-liners

โš ๏ธ Avoid arrow functions when you need access to this in objects. โ—๐Ÿงญ๐Ÿ”„

๐Ÿ”น Parameters and Arguments ๐Ÿงฎ๐Ÿ“ฌ๐Ÿงพ

  • Parameters are variables listed in the function definition.
  • Arguments are actual values passed to the function.
function greet(name = "Guest") {
  console.log(`Hello, ${name}`);
}

โœ… Use default parameters to make functions flexible. ๐ŸŒˆ๐Ÿง ๐ŸŽฏ

๐Ÿ”น Rest & Spread in Functions ๐ŸŒช๏ธ๐Ÿ“ฆ๐Ÿ‘

Rest Parameter: Collects multiple arguments into an array.

function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}

Spread Operator: Expands arrays into individual elements.

const nums = [1, 2, 3];
console.log(Math.max(...nums));

๐Ÿ“Œ These are great for variadic functions and working with arrays/objects. ๐Ÿ› ๏ธ๐ŸŽ‰๐Ÿงƒ

๐Ÿ”น Returning Values ๐Ÿ๐ŸŽ๐Ÿ”„

Functions can return a value using the return keyword.

function multiply(x, y) {
  return x * y;
}

If no return is provided, the function returns undefined by default. โš ๏ธ๐Ÿ“ญ๐Ÿ”

๐Ÿ”น Callback Functions ๐Ÿ”„๐Ÿ“ฌ๐Ÿง 

A callback is a function passed as an argument to another function to be executed later.

function greet(name, callback) {
  callback(`Hello, ${name}`);
}

Essential for asynchronous operations (e.g., setTimeout, event handlers). โฑ๏ธ๐ŸŽฏ๐ŸŽ›๏ธ

โœ… Best Practices ๐Ÿงฝ๐Ÿ“Œ๐Ÿง 

  • Use meaningful function names.
  • Keep functions focused on one task.
  • Prefer arrow functions for short, non-method functions.
  • Document input/output behavior for clarity.

๐Ÿงฉ Mastering functions sets the foundation for asynchronous programming, event-driven architecture, and clean, modular code! ๐Ÿงฑ๐ŸŽฏ๐Ÿงช

Back to Top


Arrays

Arrays are ordered collections used to store multiple values in a single variable. They can hold elements of any data type, including other arrays or objects. Arrays are zero-indexed โ€” meaning the first element is at index 0. ๐Ÿ”ข๐Ÿ“ฆ๐Ÿ’ก

๐Ÿ”น Declaration, Access, and Iteration ๐Ÿ๐Ÿ”๐Ÿ”

Declaration:

const fruits = ["apple", "banana", "mango"];

Access:

console.log(fruits[1]); // "banana"

Update:

fruits[0] = "grape";

Iteration (Looping through arrays):

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

โœ… You can also use for...of, forEach(), or map() for iteration. ๐Ÿ“Œ๐Ÿ”„๐Ÿ”

๐Ÿ”น Basic Array Methods ๐Ÿ› ๏ธ๐Ÿ“ฆ๐Ÿ”ง

These methods let you manipulate the contents of an array easily:

  • push(item) โ€“ Add to the end
  • pop() โ€“ Remove from the end
  • shift() โ€“ Remove from the start
  • unshift(item) โ€“ Add to the start
  • indexOf(item) โ€“ Get index of a specific element
const nums = [10, 20, 30];
nums.push(40);      // [10, 20, 30, 40]
nums.pop();         // [10, 20, 30]
nums.shift();       // [20, 30]
nums.unshift(5);    // [5, 20, 30]
nums.indexOf(20);   // 1

๐Ÿงช These methods are commonly used for stack, queue, and search operations. ๐Ÿ”๐Ÿง ๐Ÿ“

๐Ÿ‘‰ Arrays are fundamental in JavaScript. Theyโ€™re everywhere โ€” from handling lists of data to manipulating DOM elements, responses from APIs, or storing form inputs! ๐ŸŒ๐Ÿ“ฅ๐Ÿงฑ

Next: Letโ€™s look into Array Methods (map, filter, reduce, etc.) โ€” the real power tools of JavaScript! โš’๏ธ๐Ÿš€๐Ÿงฉ

โš™๏ธ Array Methods (map, filter, reduce, etc.) โ€” The Real Power Tools of JavaScript ๐Ÿ› ๏ธ๐Ÿš€๐Ÿงฉ

Once you master the basics of arrays, it's time to unlock their full potential using high-order methods. These built-in methods make array manipulation clean, readable, and expressive. ๐Ÿ”ฅ๐Ÿ’ก๐Ÿง 

๐Ÿ”น map() โ€“ Transform Each Element ๐Ÿ“Œ๐Ÿ”„๐ŸŽจ

Creates a new array by applying a function to every element.

const nums = [1, 2, 3];
const squares = nums.map(n => n * n); // [1, 4, 9]

Useful when you want to transform or format data.

๐Ÿ”น filter() โ€“ Keep What Passes the Test ๐Ÿงชโœ…๐Ÿšฟ

Creates a new array with elements that pass a condition.

const scores = [45, 78, 88, 32];
const passed = scores.filter(score => score >= 50); // [78, 88]

Use it to extract matching or valid items.

๐Ÿ”น reduce() โ€“ Boil It Down to a Single Value ๐Ÿงฎโš–๏ธ๐Ÿฅ„

Reduces the array to a single value (number, string, object, etc.).

const prices = [10, 20, 30];
const total = prices.reduce((sum, val) => sum + val, 0); // 60

Perfect for totals, averages, or even object construction.

๐Ÿ”น find() โ€“ Get the First Match ๐Ÿงฒ๐Ÿ”๐Ÿ›‘

Returns the first element that satisfies the condition.

const users = [{id: 1}, {id: 2}];
const user = users.find(u => u.id === 2); // {id: 2}

Stops as soon as it finds a match โ€” faster than filter() in such use-cases.

๐Ÿ”น some() and every() โ€“ Boolean Checks ๐Ÿ”Žโœ…๐Ÿšซ

  • some() checks if at least one element matches
  • every() checks if all elements match
const nums = [1, 3, 5];
nums.some(n => n > 4); // true
nums.every(n => n > 0); // true

Great for quick yes/no conditions on arrays.

๐Ÿ”น sort() โ€“ Reorder the Array ๐Ÿ”ข๐Ÿ”„๐Ÿ“Š

Sorts the array in-place. Be cautious: it modifies the original array!

const points = [40, 100, 1, 5];
points.sort((a, b) => a - b); // [1, 5, 40, 100]

Use a compare function for accurate sorting (especially for numbers).

๐Ÿ”น flat() and flatMap() โ€“ Flatten Nested Arrays ๐Ÿ“๐Ÿ“‰๐Ÿ“ฆ

  • flat() flattens an array
  • flatMap() maps and flattens in one go
const arr = [1, [2, 3], [4, [5]]];
arr.flat(2); // [1, 2, 3, 4, 5]

Ideal for dealing with nested structures or returned arrays from mapping.

๐Ÿ”น forEach() โ€“ Loop Without Return ๐Ÿ“˜๐Ÿ”๐Ÿ“ญ

Performs an action on each item, but does not return anything.

[1, 2, 3].forEach(n => console.log(n * 2));

Useful for logging, side effects, or calling external functions.

๐Ÿ’ก These methods donโ€™t mutate the original array (except sort()), making them perfect for pure functional programming and cleaner, safer code. ๐Ÿงผ๐Ÿ“ˆ๐Ÿง˜

Back to Top


Objects

Objects are one of the core building blocks in JavaScript, used to store related data and functionality together.

They consist of key-value pairs, where the key (property name) is always a string (or symbol), and the value can be anything โ€” string, number, array, object, function, etc.

๐Ÿ”น Declaring an Object

const user = {
  name: "Alice",
  age: 30,
  isAdmin: true
};

Each entry in the object is a property with a key (name, age, isAdmin) and a value ("Alice", 30, true).

๐Ÿ”น Accessing Properties โ€“ Dot Notation vs Bracket Notation ๐Ÿ”

Dot Notation (most common):

console.log(user.name); // "Alice"

Bracket Notation (for dynamic or invalid identifiers):

console.log(user["age"]); // 30

Use bracket notation when:

  • The property name is stored in a variable:
    const key = "isAdmin";
    console.log(user[key]); // true
  • The property name contains special characters or spaces:
    const obj = { "first-name": "Bob" };
    console.log(obj["first-name"]); // "Bob"

๐Ÿ”น Modifying & Adding Properties โœ๏ธโž•

You can easily change or add new properties:

user.age = 31;
user.city = "New York";

๐Ÿ”น Deleting Properties ๐Ÿงน

Remove a property using the delete operator:

delete user.isAdmin;

๐Ÿ”น Nesting Objects ๐Ÿช†

Objects can contain other objects, enabling complex data structures:

const person = {
  name: "John",
  address: {
    city: "Paris",
    zip: "75001"
  }
};

console.log(person.address.city); // "Paris"

๐Ÿ”น Checking for Property Existence โœ…

Use the in operator or hasOwnProperty():

"age" in user;               // true
user.hasOwnProperty("age"); // true

Here you go! Here's the next section covering Advanced Object Techniques with clean structure and subtle emoji decoration:

๐Ÿง  Advanced Object Techniques โ€” Destructuring, Built-in Methods & More ๐Ÿงฐ๐Ÿงช๐Ÿ”ง

JavaScript objects come packed with powerful features that make data handling more elegant and readable. These advanced techniques are must-haves in your JS toolkit.

๐Ÿ”น Object Destructuring ๐Ÿงฌ

Object destructuring allows you to extract multiple properties into variables in a single statement.

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

const { name, age } = user;
console.log(name); // "Alice"

You can also rename variables during destructuring:

const { name: userName } = user;
console.log(userName); // "Alice"

๐Ÿ”น Nested Destructuring ๐Ÿ•ณ๏ธ

Works perfectly with nested objects too:

const person = {
  name: "John",
  address: {
    city: "Paris",
    zip: "75001"
  }
};

const { address: { city } } = person;
console.log(city); // "Paris"

๐Ÿ”น Default Values in Destructuring ๐Ÿงท

Assign defaults for missing properties:

const { role = "guest" } = user;
console.log(role); // "guest"

๐Ÿ”น Object Methods โ€” Object.keys, Object.values, Object.entries ๐Ÿ”

These built-in methods are perfect for looping over objects or converting them to arrays.

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

Object.keys(user);   // ["name", "age"]
Object.values(user); // ["Alice", 30]
Object.entries(user); // [["name", "Alice"], ["age", 30]]

Looping with Object.entries():

for (const [key, value] of Object.entries(user)) {
  console.log(`${key}: ${value}`);
}

๐Ÿ”น Spread & Rest with Objects ๐ŸŒช๏ธ

Spread operator creates shallow copies:

const updatedUser = { ...user, city: "Berlin" };

Rest operator gathers the remaining properties:

const { name, ...rest } = user;
console.log(rest); // { age: 30 }

๐Ÿ”น Object.freeze & Object.seal ๐ŸงŠ๐Ÿ”’

Prevent modifications:

Object.freeze(user); // Can't change or add/remove properties
Object.seal(user);   // Can change, but not add/remove properties

๐Ÿ”น Optional Chaining (?.) & Nullish Coalescing (??) ๐Ÿ›ก๏ธ

Safely access deeply nested properties:

const city = user?.address?.city ?? "Unknown";

Back to Top


Debugging using console

Debugging is a core skill for any developer. Fortunately, JavaScript offers the console object, which is a handy toolbox to inspect, trace, and troubleshoot your code with ease. Letโ€™s explore how to use it from simple logs to advanced tactics.

๐Ÿ”น Basic Console Methods ๐ŸŽฏ

  • console.log(): Outputs general information.
  • console.error(): Displays error messages (in red).
  • console.warn(): Shows warnings (often in yellow).
  • console.info(): Gives informational messages (not widely different from log() in most browsers).
console.log("Hello world!");
console.error("Something went wrong!");
console.warn("This is a warning!");
console.info("Fetching data...");

๐Ÿ”น Logging Variables & Expressions ๐Ÿ“ฆ

You can log anything โ€” strings, numbers, objects, arrays, functions, etc.

const user = { name: "Alice", age: 30 };
console.log(user);
console.log("User age is:", user.age);

๐Ÿ”น console.table() ๐Ÿงฎ

Perfect for visualizing objects or arrays in a table format.

const users = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 }
];

console.table(users);

๐Ÿ”น console.group() & console.groupEnd() ๐Ÿ—‚๏ธ

Helps you organize logs into collapsible groups.

console.group("User Info");
console.log("Name: Alice");
console.log("Age: 30");
console.groupEnd();

๐Ÿ”น console.time() and console.timeEnd() โฑ๏ธ

Measure how long a block of code takes to execute.

console.time("loop");
for (let i = 0; i < 1000000; i++) {}
console.timeEnd("loop"); // loop: 1.234ms

๐Ÿ”น console.assert() โœ…โŒ

Only logs if a condition fails โ€” great for inline checks.

const age = 15;
console.assert(age >= 18, "Age is below 18");

๐Ÿ”น Styled Console Logs ๐ŸŽจ

Make your logs visually stand out.

console.log("%cHello styled log", "color: blue; font-weight: bold;");

๐Ÿ”น Debugging in DevTools ๐Ÿงช

Use browser developer tools:

  • Set breakpoints in Sources tab.
  • Inspect variables in Scope panel.
  • Watch expressions.
  • Step through your code line by line.

Tip: Use debugger; in your code to automatically trigger a breakpoint.

function checkAge(age) {
  debugger;
  return age >= 18;
}

๐Ÿ”น Real-World Tips ๐Ÿ› ๏ธ

  • Keep logs consistent. Use log levels (log, warn, error) smartly.
  • Remove/disable excessive logging in production.
  • Label your logs clearly when debugging complex apps.

Back to Top