JavaScript Arrays, Functions & Objects

Table of Contents

  1. Arrays – The Complete Guide
  2. Functions – Making Code Reusable
  3. Objects – Organizing Related Data
  4. Arrow Functions – Modern JavaScript
  5. Closures – Advanced Function Concepts
  6. Practice Questions

Arrays – The Complete Guide

What are Arrays?

Arrays are ordered collections of data that can store multiple values in a single variable. Think of them as lists or containers that hold related items.

// Simple array of numbers
let numbers = [1, 2, 3, 4, 5];

// Array of strings
let fruits = ["apple", "banana", "orange", "grape"];

// Mixed data types (valid but not recommended)
let mixed = [1, "hello", true, null, undefined];

Creating Arrays

1. Array Literal (Most Common)

let emptyArray = [];
let colors = ["red", "green", "blue"];
let scores = [95, 87, 92, 78, 88];

2. Array Constructor

let numbers = new Array(1, 2, 3, 4, 5);
let emptyArray = new Array();
let fixedSize = new Array(5);  // Creates array with 5 empty slots

3. Array.of() Method

let numbers = Array.of(1, 2, 3, 4, 5);
let singleItem = Array.of(7);  // Creates [7], not array with 7 slots

Accessing Array Elements

let fruits = ["apple", "banana", "orange", "grape"];

// Access by index (starts from 0)
console.log(fruits[0]);     // "apple"
console.log(fruits[1]);     // "banana"
console.log(fruits[3]);     // "grape"

// Last element
console.log(fruits[fruits.length - 1]);  // "grape"

// Non-existent index
console.log(fruits[10]);    // undefined

Array Properties and Methods

Length Property

let numbers = [10, 20, 30, 40, 50];
console.log(numbers.length);    // 5

// Change array length
numbers.length = 3;
console.log(numbers);           // [10, 20, 30]

numbers.length = 5;
console.log(numbers);           // [10, 20, 30, undefined, undefined]

Adding Elements

let fruits = ["apple", "banana"];

// Add to end - push()
fruits.push("orange");
console.log(fruits);            // ["apple", "banana", "orange"]

// Add multiple elements
fruits.push("grape", "mango");
console.log(fruits);            // ["apple", "banana", "orange", "grape", "mango"]

// Add to beginning - unshift()
fruits.unshift("strawberry");
console.log(fruits);            // ["strawberry", "apple", "banana", "orange", "grape", "mango"]

// Add at specific index - splice()
fruits.splice(2, 0, "kiwi");   // At index 2, remove 0, add "kiwi"
console.log(fruits);            // ["strawberry", "apple", "kiwi", "banana", "orange", "grape", "mango"]

Removing Elements

let fruits = ["apple", "banana", "orange", "grape"];

// Remove from end - pop()
let lastFruit = fruits.pop();
console.log(lastFruit);         // "grape"
console.log(fruits);            // ["apple", "banana", "orange"]

// Remove from beginning - shift()
let firstFruit = fruits.shift();
console.log(firstFruit);        // "apple"
console.log(fruits);            // ["banana", "orange"]

// Remove from specific index - splice()
fruits.splice(1, 1);           // At index 1, remove 1 element
console.log(fruits);            // ["banana"]

Finding Elements

let numbers = [10, 20, 30, 40, 50];
let fruits = ["apple", "banana", "orange"];

// Find index - indexOf()
console.log(numbers.indexOf(30));       // 2
console.log(fruits.indexOf("banana"));  // 1
console.log(fruits.indexOf("grape"));   // -1 (not found)

// Check if element exists - includes()
console.log(fruits.includes("apple"));  // true
console.log(fruits.includes("grape"));  // false

// Find element - find()
let bigNumber = numbers.find(num => num > 25);
console.log(bigNumber);                 // 30

// Find index with condition - findIndex()
let bigIndex = numbers.findIndex(num => num > 25);
console.log(bigIndex);                  // 2

Array Iteration

let fruits = ["apple", "banana", "orange"];

// Traditional for loop
for (let i = 0; i < fruits.length; i++) {
    console.log(i + ": " + fruits[i]);
}

// for...of loop (values)
for (let fruit of fruits) {
    console.log(fruit);
}

// for...in loop (indexes)
for (let index in fruits) {
    console.log(index + ": " + fruits[index]);
}

// forEach method
fruits.forEach(function(fruit, index) {
    console.log(index + ": " + fruit);
});

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

Other Useful Array Methods

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

// Join array into string
console.log(fruits.join());         // "banana,apple,orange"
console.log(fruits.join(" - "));    // "banana - apple - orange"

// Reverse array
let reversed = fruits.reverse();
console.log(reversed);              // ["orange", "apple", "banana"]

// Sort array
let sorted = fruits.sort();
console.log(sorted);                // ["apple", "banana", "orange"]

// Sort numbers properly
let sortedNumbers = numbers.sort((a, b) => a - b);
console.log(sortedNumbers);         // [1, 2, 3, 4, 5]

// Slice (extract portion)
let portion = fruits.slice(1, 3);   // From index 1 to 3 (exclusive)
console.log(portion);               // ["banana", "orange"]

// Concat (join arrays)
let moreNumbers = [6, 7, 8];
let allNumbers = numbers.concat(moreNumbers);
console.log(allNumbers);            // [1, 2, 3, 4, 5, 6, 7, 8]

Functions – Making Code Reusable

What are Functions?

Functions are reusable blocks of code that perform specific tasks. They help avoid code repetition and make programs more organized.

Function Declaration

// Basic function declaration
function greetUser() {
    console.log("Hello, welcome to our website!");
}

// Call/invoke the function
greetUser();                // Output: Hello, welcome to our website!

// Function with parameters
function greetPersonally(name) {
    console.log("Hello " + name + ", welcome!");
}

greetPersonally("Alice");   // Output: Hello Alice, welcome!
greetPersonally("Bob");     // Output: Hello Bob, welcome!

// Function with multiple parameters
function addNumbers(a, b) {
    let sum = a + b;
    console.log(a + " + " + b + " = " + sum);
}

addNumbers(5, 3);           // Output: 5 + 3 = 8
addNumbers(10, 7);          // Output: 10 + 7 = 17

Function with Return Values

// Function that returns a value
function calculateArea(length, width) {
    let area = length * width;
    return area;
}

// Use returned value
let roomArea = calculateArea(12, 10);
console.log("Room area: " + roomArea + " sq ft");  // Room area: 120 sq ft

// Return multiple calculations
function calculate(a, b) {
    return {
        sum: a + b,
        difference: a - b,
        product: a * b,
        quotient: a / b
    };
}

let results = calculate(20, 4);
console.log("Sum:", results.sum);           // Sum: 24
console.log("Product:", results.product);   // Product: 80

Function Parameters and Arguments

// Default parameters
function greet(name = "Guest", time = "day") {
    console.log(`Good ${time}, ${name}!`);
}

greet();                    // Good day, Guest!
greet("Alice");             // Good day, Alice!
greet("Bob", "morning");    // Good morning, Bob!

// Rest parameters (...args)
function addAllNumbers(...numbers) {
    let sum = 0;
    for (let num of numbers) {
        sum += num;
    }
    return sum;
}

console.log(addAllNumbers(1, 2, 3));        // 6
console.log(addAllNumbers(1, 2, 3, 4, 5));  // 15
console.log(addAllNumbers());               // 0

Function Expressions

// Function expression (anonymous function)
let multiply = function(a, b) {
    return a * b;
};

console.log(multiply(4, 5));    // 20

// Named function expression
let divide = function divideNumbers(a, b) {
    if (b === 0) {
        return "Cannot divide by zero";
    }
    return a / b;
};

console.log(divide(10, 2));     // 5
console.log(divide(10, 0));     // Cannot divide by zero

Function Scope

// Global scope
let globalVariable = "I'm global";

function demonstrateScope() {
    // Function scope
    let localVariable = "I'm local";
    
    console.log(globalVariable);    // Accessible
    console.log(localVariable);     // Accessible
}

demonstrateScope();
console.log(globalVariable);        // Accessible
// console.log(localVariable);      // Error: not defined

// Block scope with let/const
function blockScopeExample() {
    if (true) {
        let blockVariable = "I'm in a block";
        const anotherBlockVar = "Me too";
        console.log(blockVariable);     // Works
    }
    // console.log(blockVariable);      // Error: not defined
}

Objects – Organizing Related Data

What are Objects?

Objects are collections of key-value pairs that represent real-world entities or concepts. They group related data and functionality together.

Creating Objects

1. Object Literal (Most Common)

// Simple object
let person = {
    name: "John Doe",
    age: 30,
    city: "New York",
    isEmployed: true
};

// Object with methods
let car = {
    brand: "Toyota",
    model: "Camry",
    year: 2022,
    color: "blue",
    
    // Method (function inside object)
    startEngine: function() {
        console.log("Engine started!");
    },
    
    getInfo: function() {
        return this.brand + " " + this.model + " (" + this.year + ")";
    }
};

2. Object Constructor

let person = new Object();
person.name = "Alice";
person.age = 25;
person.city = "Boston";

3. Constructor Function

function Person(name, age, city) {
    this.name = name;
    this.age = age;
    this.city = city;
    this.introduce = function() {
        return "Hi, I'm " + this.name + " from " + this.city;
    };
}

let person1 = new Person("John", 30, "New York");
let person2 = new Person("Alice", 25, "Boston");

Accessing Object Properties

let student = {
    name: "Emily",
    age: 20,
    grades: [90, 85, 92, 88],
    address: {
        street: "123 Main St",
        city: "Chicago",
        state: "IL"
    }
};

// Dot notation
console.log(student.name);          // "Emily"
console.log(student.age);           // 20

// Bracket notation
console.log(student["name"]);       // "Emily"
console.log(student["age"]);        // 20

// Accessing nested objects
console.log(student.address.city);  // "Chicago"
console.log(student.address["state"]); // "IL"

// Accessing arrays in objects
console.log(student.grades[0]);     // 90
console.log(student.grades.length); // 4

Useful Object Methods

let person = {
    name: "John",
    age: 30,
    city: "New York"
};

// Get all keys
let keys = Object.keys(person);
console.log(keys);          // ["name", "age", "city"]

// Get all values
let values = Object.values(person);
console.log(values);        // ["John", 30, "New York"]

// Get key-value pairs
let entries = Object.entries(person);
console.log(entries);       // [["name", "John"], ["age", 30], ["city", "New York"]]

// Check if property exists
console.log("name" in person);          // true
console.log(person.hasOwnProperty("age")); // true

// Copy objects (shallow copy)
let personCopy = Object.assign({}, person);
let anotherCopy = { ...person };        // Spread operator

Arrow Functions – Modern JavaScript

What are Arrow Functions?

Arrow functions are a shorter way to write functions introduced in ES6. They provide cleaner syntax and handle this differently than regular functions.

Basic Syntax

// Traditional function
function add(a, b) {
    return a + b;
}

// Arrow function - full syntax
let add = (a, b) => {
    return a + b;
};

// Arrow function - shorter syntax (one expression)
let add = (a, b) => a + b;

// Single parameter (parentheses optional)
let square = x => x * x;
let square = (x) => x * x; // Also valid

// No parameters (parentheses required)
let greet = () => "Hello World!";

// Multiple lines (braces and return required)
let processData = (data) => {
    let processed = data.toUpperCase();
    let trimmed = processed.trim();
    return trimmed;
};

Arrow Functions with Arrays

let numbers = [1, 2, 3, 4, 5];

// Traditional way
let doubled = numbers.map(function(num) {
    return num * 2;
});

// Arrow function way
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// Filter with arrow functions
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]

// Find with arrow functions
let bigNumber = numbers.find(num => num > 3);
console.log(bigNumber); // 4

// Reduce with arrow functions
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15

Closures – Advanced Function Concepts

What are Closures?

A closure is when an inner function has access to variables from its outer function, even after the outer function has finished executing. This creates a “private” scope.

Closure Example

function outerFunction(x) {
    // Outer function variable
    let outerVariable = x;
    
    // Inner function
    function innerFunction(y) {
        // Inner function can access outer variables
        console.log(outerVariable + y);
    }
    
    // Return the inner function
    return innerFunction;
}

// Create a closure
let addFive = outerFunction(5);
addFive(10); // 15 (5 + 10)

let addTen = outerFunction(10);
addTen(5);  // 15 (10 + 5)

Quick Reference

Arrays

let arr = [1, 2, 3];
arr.push(4);              // Add to end
arr.pop();                // Remove from end  
arr.includes(2);          // Check if exists
arr.map(x => x * 2);      // Transform each element
arr.filter(x => x > 1);   // Filter elements

Functions

function name(params) { return value; }
let func = (params) => value;
let obj = { method() { return this; } };

Objects

let obj = { key: value };
obj.newKey = value;       // Add property
delete obj.key;           // Remove property
Object.keys(obj);         // Get keys array

Closures

function outer(x) {
    return function(y) {
        return x + y;       // Inner accesses outer's x
    };
}

Ready to tackle these challenges? Start with the basics and work your way up! 💪

Leave a Reply

Your email address will not be published. Required fields are marked *