Functions & Arrays - Building Blocks of JavaScript

Master JavaScript functions and arrays to write reusable, organized code that handles multiple values efficiently

Functions and arrays are fundamental building blocks of JavaScript. Let's master them!


2. Functions

What are Functions?

Functions are reusable blocks of code that perform a specific task. Think of them as recipes - you write the instructions once and use them many times.

Basic Function Syntax

function functionName(parameter1, parameter2) {
  // Code to execute
  return result; // Optional
}

Examples

Simple Function (no parameters, no return)

function sayHello() {
  console.log("Hello, everyone!");
}

// Call the function
sayHello(); // Output: "Hello, everyone!"
sayHello(); // Can be called multiple times

Function with Parameters

function greetUser(name) {
  console.log("Welcome, " + name + "!");
}

greetUser("Alice"); // Output: "Welcome, Alice!"
greetUser("Bob");   // Output: "Welcome, Bob!"

Function with Return Value

function addNumbers(a, b) {
  const sum = a + b;
  return sum;
}

const result = addNumbers(5, 3);
console.log(result); // Output: 8

// Use directly in other operations
const total = addNumbers(10, 20) + 5;
console.log(total); // Output: 35

Function with Multiple Parameters

function calculateArea(width, height) {
  return width * height;
}

const area1 = calculateArea(5, 10);
console.log(area1); // Output: 50

const area2 = calculateArea(7, 3);
console.log(area2); // Output: 21

Arrow Functions (Modern Syntax)

Arrow functions are a shorter way to write functions.

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

// Arrow function - same thing
const multiply = (x, y) => {
  return x * y;
};

// Arrow function - shorter (one-line)
const multiply = (x, y) => x * y;

// Example with one parameter
const square = (num) => num * num;
console.log(square(4)); // Output: 16

// Example with no parameters
const getRandom = () => Math.random();
console.log(getRandom()); // Output: random number

When to Use Functions?

  • When you repeat the same code multiple times
  • To organize complex code into smaller parts
  • To make code more readable and maintainable
// Without function - repetitive
let price1 = 100;
let tax1 = price1 * 0.2;
let total1 = price1 + tax1;

let price2 = 200;
let tax2 = price2 * 0.2;
let total2 = price2 + tax2;

// With function - clean and reusable
function calculateTotal(price) {
  const tax = price * 0.2;
  return price + tax;
}

const total1 = calculateTotal(100); // 120
const total2 = calculateTotal(200); // 240

3. Arrays

What are Arrays?

Arrays are ordered lists that store multiple values in a single variable. Each item has a position called an index, starting from 0.

Index:  0        1         2         3
Array: ["apple", "banana", "orange", "grape"]

Creating Arrays

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

// Array of numbers
const numbers = [10, 20, 30, 40, 50];

// Array with mixed types (possible but not recommended)
const mixed = ["text", 42, true];

// Empty array
const emptyArray = [];

Accessing Array Elements

const colors = ["red", "green", "blue", "yellow"];

console.log(colors[0]); // "red" (first item)
console.log(colors[1]); // "green" (second item)
console.log(colors[3]); // "yellow" (fourth item)

// Getting the last item
const lastColor = colors[colors.length - 1];
console.log(lastColor); // "yellow"

Modifying Arrays

const students = ["Alice", "Bob", "Charlie"];

// Change an existing element
students[1] = "Ben";
console.log(students); // ["Alice", "Ben", "Charlie"]

// Add a new element at specific index
students[3] = "Diana";
console.log(students); // ["Alice", "Ben", "Charlie", "Diana"]

Common Array Methods

Adding Elements

const numbers = [1, 2, 3];

// Add to the end
numbers.push(4);
console.log(numbers); // [1, 2, 3, 4]

numbers.push(5, 6);
console.log(numbers); // [1, 2, 3, 4, 5, 6]

// Add to the beginning
numbers.unshift(0);
console.log(numbers); // [0, 1, 2, 3, 4, 5, 6]

Removing Elements

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

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

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

Other Useful Methods

const animals = ["cat", "dog", "bird", "fish"];

// Get array length
console.log(animals.length); // 4

// Check if value exists
console.log(animals.includes("dog"));  // true
console.log(animals.includes("lion")); // false

// Find index of element
console.log(animals.indexOf("bird")); // 2
console.log(animals.indexOf("lion")); // -1 (not found)

// Join array into string
const text = animals.join(", ");
console.log(text); // "cat, dog, bird, fish"

Looping Through Arrays

Using a for loop

const scores = [85, 92, 78, 95, 88];

for (let i = 0; i < scores.length; i++) {
  console.log("Score " + (i + 1) + ": " + scores[i]);
}

// Output:
// Score 1: 85
// Score 2: 92
// Score 3: 78
// Score 4: 95
// Score 5: 88

Using forEach (modern way)

const names = ["Emma", "Liam", "Olivia"];

names.forEach((name, index) => {
  console.log(index + ": " + name);
});

// Output:
// 0: Emma
// 1: Liam
// 2: Olivia

Practical Example: Sum all numbers

const prices = [10, 25, 30, 15];
let total = 0;

for (let i = 0; i < prices.length; i++) {
  total += prices[i];
}

console.log("Total: $" + total); // Total: $80

What's Next?

In Part 3, we'll explore the DOM (Document Object Model) and learn how to select and manipulate HTML elements with JavaScript! 🎯