📚

JavaScript Fundamentals

Master the core concepts of JavaScript

Variables and Data Types

Variable Declarations

// Variable declarations
var oldWay = "Don't use this anymore";  // Function-scoped, hoisted
let modernWay = "Use this for variables that change";  // Block-scoped
const constant = "Use this for values that don't change";  // Block-scoped, immutable

// Data Types
let string = "Hello World";
let number = 42;
let boolean = true;
let nullValue = null;
let undefinedValue = undefined;
let symbol = Symbol('unique');
let bigint = 123n;

// Objects
let object = { name: "Alice", age: 25 };
let array = [1, 2, 3, 4, 5];
let date = new Date();
let regex = /pattern/g;

💡 Best Practices

  • • Use const by default
  • • Use let when you need to reassign
  • • Avoid var in modern JavaScript
  • • Use descriptive variable names

Functions

Function Declarations and Expressions

// Function Declaration (hoisted)
function greet(name) {
    return `Hello, ${name}!`;
}

// Function Expression
const greetExpression = function(name) {
    return `Hello, ${name}!`;
};

// Arrow Functions (ES6+)
const greetArrow = (name) => `Hello, ${name}!`;
const add = (a, b) => a + b;
const multiply = (a, b) => {
    const result = a * b;
    return result;
};

// Default Parameters
function greetWithDefault(name = "World") {
    return `Hello, ${name}!`;
}

// Rest Parameters
function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}

// Destructuring Parameters
function createUser({name, age, email}) {
    return { name, age, email, id: Date.now() };
}

const user = createUser({name: "Alice", age: 25, email: "alice@example.com"});

Objects and Arrays

Working with Objects

// Object Creation
const person = {
    name: "Alice",
    age: 25,
    hobbies: ["reading", "coding"],
    greet() {
        return `Hi, I'm ${this.name}`;
    }
};

// Object Destructuring
const {name, age} = person;
const {name: personName, age: personAge} = person;

// Object Methods
const keys = Object.keys(person);
const values = Object.values(person);
const entries = Object.entries(person);

// Spread Operator
const updatedPerson = {...person, age: 26, city: "New York"};

// Object.assign()
const merged = Object.assign({}, person, {profession: "Developer"});

Array Methods

const numbers = [1, 2, 3, 4, 5];
const fruits = ["apple", "banana", "orange"];

// Transforming Arrays
const doubled = numbers.map(n => n * 2);
const uppercased = fruits.map(fruit => fruit.toUpperCase());

// Filtering Arrays
const evens = numbers.filter(n => n % 2 === 0);
const longFruits = fruits.filter(fruit => fruit.length > 5);

// Reducing Arrays
const sum = numbers.reduce((total, n) => total + n, 0);
const concatenated = fruits.reduce((result, fruit) => result + fruit + " ", "");

// Finding Elements
const found = numbers.find(n => n > 3);
const foundIndex = numbers.findIndex(n => n > 3);

// Checking Conditions
const allPositive = numbers.every(n => n > 0);
const hasEven = numbers.some(n => n % 2 === 0);

// Array Destructuring
const [first, second, ...rest] = numbers;

Control Flow

Conditionals and Loops

// Conditionals
const age = 25;

if (age >= 18) {
    console.log("Adult");
} else if (age >= 13) {
    console.log("Teenager");
} else {
    console.log("Child");
}

// Ternary Operator
const status = age >= 18 ? "Adult" : "Minor";

// Switch Statement
const day = "Monday";
switch (day) {
    case "Monday":
        console.log("Start of work week");
        break;
    case "Friday":
        console.log("TGIF!");
        break;
    default:
        console.log("Regular day");
}

// Loops
for (let i = 0; i < 5; i++) {
    console.log(i);
}

const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
    console.log(fruit);
}

for (const index in fruits) {
    console.log(index, fruits[index]);
}

// While Loop
let count = 0;
while (count < 3) {
    console.log(count);
    count++;
}

// forEach
fruits.forEach((fruit, index) => {
    console.log(`${index}: ${fruit}`);
});

Error Handling

Try-Catch and Error Types

// Basic Error Handling
try {
    const result = riskyOperation();
    console.log(result);
} catch (error) {
    console.error("Something went wrong:", error.message);
} finally {
    console.log("This always runs");
}

// Throwing Custom Errors
function divide(a, b) {
    if (b === 0) {
        throw new Error("Division by zero is not allowed");
    }
    return a / b;
}

// Different Error Types
try {
    JSON.parse("invalid json");
} catch (error) {
    if (error instanceof SyntaxError) {
        console.log("Invalid JSON syntax");
    } else if (error instanceof ReferenceError) {
        console.log("Variable not defined");
    } else {
        console.log("Unknown error:", error.message);
    }
}

// Async Error Handling
async function fetchData() {
    try {
        const response = await fetch('/api/data');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        return data;
    } catch (error) {
        console.error("Failed to fetch data:", error);
        throw error; // Re-throw if needed
    }
}