Session 2.3 – Strings, Arrays, and Objects

Module 2: JavaScript & AJAX | Duration: 1 hr

Learning Objectives

By the end of this session, students will be able to:

  • Manipulate strings using JavaScript string methods
  • Create and manipulate arrays with various array methods
  • Work with JavaScript objects and their properties
  • Understand the difference between primitive and reference types
  • Parse and stringify JSON data

Introduction to Complex Data Types

JavaScript provides powerful data structures for handling text (strings), collections (arrays), and structured data (objects). Understanding these data types is essential for effective JavaScript programming.

Why These Matter

Strings, arrays, and objects are the building blocks of most JavaScript applications. Strings handle text data, arrays manage ordered collections, and objects store related data together. Mastering these is crucial for web development.

JavaScript Strings

Strings are used to store and manipulate text. JavaScript provides numerous methods for working with strings.

Creating Strings

// Different ways to create strings
let single = 'Single quotes';
let double = "Double quotes";
let template = `Template literal`;

// Multi-line strings with template literals
let multiLine = `This is a
multi-line
string`;

// String concatenation
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;

// Template literals with expressions
let age = 25;
let message = `My name is ${fullName} and I am ${age} years old.`;
console.log(message);

String Properties and Methods

let text = "JavaScript is Awesome!";

// Length property
console.log(text.length);  // 21

// Accessing characters
console.log(text[0]);           // "J"
console.log(text.charAt(0));    // "J"
console.log(text.charAt(10));   // "i"

// Case conversion
console.log(text.toLowerCase());  // "javascript is awesome!"
console.log(text.toUpperCase());  // "JAVASCRIPT IS AWESOME!"

// Searching
console.log(text.indexOf("is"));      // 11
console.log(text.lastIndexOf("a"));   // 18
console.log(text.includes("Awesome")); // true
console.log(text.startsWith("Java")); // true
console.log(text.endsWith("!"));      // true

// Extracting parts
console.log(text.substring(0, 10));   // "JavaScript"
console.log(text.substr(11, 2));      // "is" (deprecated)
console.log(text.slice(11, 13));      // "is"
console.log(text.slice(-8));          // "Awesome!"

// Replacing
console.log(text.replace("Awesome", "Amazing"));  // "JavaScript is Amazing!"
console.log(text.replaceAll("a", "@"));           // "J@v@Script is Awesome!"

// Splitting
let words = text.split(" ");
console.log(words);  // ["JavaScript", "is", "Awesome!"]

// Trimming
let padded = "   Hello   ";
console.log(padded.trim());       // "Hello"
console.log(padded.trimStart());  // "Hello   "
console.log(padded.trimEnd());    // "   Hello"

// Padding
console.log("5".padStart(3, "0"));  // "005"
console.log("5".padEnd(3, "0"));    // "500"

// Repeating
console.log("Ha".repeat(3));  // "HaHaHa"
Method Description Example
length Returns the length of a string "hello".length → 5
toUpperCase() Converts to uppercase "hello".toUpperCase() → "HELLO"
toLowerCase() Converts to lowercase "HELLO".toLowerCase() → "hello"
indexOf() Returns first index of substring "hello".indexOf("l") → 2
slice() Extracts a part of string "hello".slice(1,4) → "ell"
split() Splits string into array "a,b,c".split(",") → ["a","b","c"]

JavaScript Arrays

Arrays are used to store multiple values in a single variable. They are ordered, indexed collections.

Creating and Accessing Arrays

// Creating arrays
let fruits = ["Apple", "Banana", "Orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "text", true, null, {key: "value"}];
let empty = [];

// Array constructor
let arr = new Array(3);  // Creates array with 3 empty slots
let arr2 = new Array(1, 2, 3);  // Creates [1, 2, 3]

// Accessing elements
console.log(fruits[0]);      // "Apple"
console.log(fruits[1]);      // "Banana"
console.log(fruits.length);  // 3

// Modifying elements
fruits[1] = "Mango";
console.log(fruits);  // ["Apple", "Mango", "Orange"]

// Adding elements
fruits[3] = "Grape";
console.log(fruits);  // ["Apple", "Mango", "Orange", "Grape"]

Array Methods: Adding and Removing

let arr = ["a", "b", "c"];

// push() - add to end
arr.push("d");
console.log(arr);  // ["a", "b", "c", "d"]

// pop() - remove from end
let last = arr.pop();
console.log(last);  // "d"
console.log(arr);   // ["a", "b", "c"]

// unshift() - add to beginning
arr.unshift("z");
console.log(arr);  // ["z", "a", "b", "c"]

// shift() - remove from beginning
let first = arr.shift();
console.log(first);  // "z"
console.log(arr);    // ["a", "b", "c"]

// splice() - add/remove at specific position
arr.splice(1, 0, "x", "y");  // At index 1, remove 0, add "x", "y"
console.log(arr);  // ["a", "x", "y", "b", "c"]

arr.splice(1, 2);  // At index 1, remove 2 elements
console.log(arr);  // ["a", "b", "c"]

// slice() - extract portion (doesn't modify original)
let sliced = arr.slice(1, 3);
console.log(sliced);  // ["b", "c"]
console.log(arr);     // ["a", "b", "c"] (unchanged)

Array Methods: Searching and Sorting

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

// indexOf() and lastIndexOf()
console.log(numbers.indexOf(1));      // 1
console.log(numbers.lastIndexOf(1));  // 3
console.log(numbers.indexOf(10));     // -1 (not found)

// includes()
console.log(numbers.includes(5));  // true
console.log(numbers.includes(10)); // false

// find() and findIndex()
let found = numbers.find(num => num > 5);
console.log(found);  // 9 (first element > 5)

let index = numbers.findIndex(num => num > 5);
console.log(index);  // 5

// sort() - sorts in place
let fruits = ["Banana", "Apple", "Orange"];
fruits.sort();
console.log(fruits);  // ["Apple", "Banana", "Orange"]

// Sort numbers correctly
numbers.sort((a, b) => a - b);
console.log(numbers);  // [1, 1, 2, 3, 4, 5, 6, 9]

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

Array Methods: Iteration

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

// forEach() - execute function for each element
numbers.forEach((num, index) => {
    console.log(`Index ${index}: ${num}`);
});

// map() - create new array with transformed elements
let doubled = numbers.map(num => num * 2);
console.log(doubled);  // [2, 4, 6, 8, 10]

// filter() - create new array with elements that pass test
let evens = numbers.filter(num => num % 2 === 0);
console.log(evens);  // [2, 4]

// reduce() - reduce array to single value
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum);  // 15

// every() - check if all elements pass test
let allPositive = numbers.every(num => num > 0);
console.log(allPositive);  // true

// some() - check if at least one element passes test
let hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven);  // true

// Chaining methods
let result = numbers
    .filter(num => num > 2)
    .map(num => num * 2)
    .reduce((acc, num) => acc + num, 0);
console.log(result);  // 24

Array Destructuring (ES6)

// Array destructuring
let colors = ["red", "green", "blue"];
let [first, second, third] = colors;
console.log(first);   // "red"
console.log(second);  // "green"

// Skip elements
let [primary, , tertiary] = colors;
console.log(primary);   // "red"
console.log(tertiary);  // "blue"

// Rest operator
let numbers = [1, 2, 3, 4, 5];
let [one, two, ...rest] = numbers;
console.log(one);   // 1
console.log(two);   // 2
console.log(rest);  // [3, 4, 5]

// Swapping variables
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b);  // 2 1

Spread Operator (ES6)

// Spread operator
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

// Combining arrays
let combined = [...arr1, ...arr2];
console.log(combined);  // [1, 2, 3, 4, 5, 6]

// Copying arrays
let copy = [...arr1];
console.log(copy);  // [1, 2, 3]

// Adding elements
let extended = [0, ...arr1, 4];
console.log(extended);  // [0, 1, 2, 3, 4]

// Function arguments
function sum(a, b, c) {
    return a + b + c;
}
console.log(sum(...arr1));  // 6

JavaScript Objects

Objects are collections of key-value pairs and are used to store related data together.

Creating and Accessing Objects

// Object literal
let person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    email: "john@example.com",
    isEmployed: true
};

// Accessing properties
console.log(person.firstName);      // "John" (dot notation)
console.log(person["lastName"]);    // "Doe" (bracket notation)

// Adding properties
person.phone = "123-456-7890";
person["address"] = "123 Main St";

// Modifying properties
person.age = 31;

// Deleting properties
delete person.email;

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

// Object with methods
let calculator = {
    add: function(a, b) {
        return a + b;
    },
    subtract(a, b) {  // ES6 shorthand
        return a - b;
    }
};

console.log(calculator.add(5, 3));       // 8
console.log(calculator.subtract(5, 3));  // 2

Object Methods

let person = {
    firstName: "John",
    lastName: "Doe",
    age: 30
};

// Object.keys() - get array of keys
let keys = Object.keys(person);
console.log(keys);  // ["firstName", "lastName", "age"]

// Object.values() - get array of values
let values = Object.values(person);
console.log(values);  // ["John", "Doe", 30]

// Object.entries() - get array of [key, value] pairs
let entries = Object.entries(person);
console.log(entries);
// [["firstName", "John"], ["lastName", "Doe"], ["age", 30]]

// Iterating over objects
for (let key in person) {
    console.log(`${key}: ${person[key]}`);
}

// Object.assign() - copy properties
let target = {a: 1};
let source = {b: 2, c: 3};
Object.assign(target, source);
console.log(target);  // {a: 1, b: 2, c: 3}

// Object spread (ES2018)
let obj1 = {a: 1, b: 2};
let obj2 = {c: 3, d: 4};
let merged = {...obj1, ...obj2};
console.log(merged);  // {a: 1, b: 2, c: 3, d: 4}

Object Destructuring (ES6)

// Object destructuring
let person = {
    name: "Alice",
    age: 25,
    city: "New York"
};

// Extract properties
let {name, age, city} = person;
console.log(name);  // "Alice"
console.log(age);   // 25

// Rename variables
let {name: personName, age: personAge} = person;
console.log(personName);  // "Alice"

// Default values
let {name, country = "USA"} = person;
console.log(country);  // "USA" (default)

// Nested destructuring
let user = {
    id: 1,
    info: {
        name: "Bob",
        email: "bob@example.com"
    }
};

let {info: {name: userName, email}} = user;
console.log(userName);  // "Bob"
console.log(email);     // "bob@example.com"

This Keyword and Methods

// 'this' refers to the object
let person = {
    firstName: "John",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    },
    greet() {
        return `Hello, I'm ${this.firstName}`;
    }
};

console.log(person.fullName());  // "John Doe"
console.log(person.greet());     // "Hello, I'm John"

// Constructor function
function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.getFullName = function() {
        return `${this.firstName} ${this.lastName}`;
    };
}

let john = new Person("John", "Doe");
console.log(john.getFullName());  // "John Doe"

JSON (JavaScript Object Notation)

JSON is a lightweight data format used for data exchange between a server and a client.

// JavaScript object
let person = {
    name: "Alice",
    age: 30,
    hobbies: ["reading", "coding", "gaming"],
    address: {
        city: "New York",
        country: "USA"
    }
};

// Convert object to JSON string
let jsonString = JSON.stringify(person);
console.log(jsonString);
// {"name":"Alice","age":30,"hobbies":["reading","coding","gaming"],"address":{"city":"New York","country":"USA"}}

// Pretty print JSON
let prettyJson = JSON.stringify(person, null, 2);
console.log(prettyJson);
/* Output:
{
  "name": "Alice",
  "age": 30,
  "hobbies": [
    "reading",
    "coding",
    "gaming"
  ],
  "address": {
    "city": "New York",
    "country": "USA"
  }
}
*/

// Parse JSON string to object
let parsed = JSON.parse(jsonString);
console.log(parsed.name);     // "Alice"
console.log(parsed.age);      // 30
console.log(parsed.hobbies);  // ["reading", "coding", "gaming"]

// Filtering during stringify
let filtered = JSON.stringify(person, ["name", "age"]);
console.log(filtered);  // {"name":"Alice","age":30}
JSON Rules
  • Property names must be in double quotes
  • Strings must use double quotes (not single quotes)
  • No trailing commas
  • Cannot contain functions, undefined, or symbols
  • Date objects are converted to strings

Practical Examples

Example 1: Student Grade Manager

// Student grade management system
let students = [
    {name: "Alice", scores: [85, 92, 78, 90]},
    {name: "Bob", scores: [75, 88, 92, 85]},
    {name: "Charlie", scores: [95, 98, 92, 96]}
];

// Calculate average score for each student
students.forEach(student => {
    let avg = student.scores.reduce((sum, score) => sum + score, 0) / student.scores.length;
    student.average = avg.toFixed(2);
});

// Find student with highest average
let topStudent = students.reduce((top, student) =>
    student.average > top.average ? student : top
);

console.log(`Top student: ${topStudent.name} with average ${topStudent.average}`);

Example 2: Shopping Cart

// Shopping cart functionality
let cart = {
    items: [],

    addItem(name, price, quantity) {
        this.items.push({name, price, quantity});
    },

    removeItem(name) {
        this.items = this.items.filter(item => item.name !== name);
    },

    getTotal() {
        return this.items.reduce((total, item) =>
            total + (item.price * item.quantity), 0
        );
    },

    getItemCount() {
        return this.items.reduce((count, item) =>
            count + item.quantity, 0
        );
    },

    displayCart() {
        console.log("Shopping Cart:");
        this.items.forEach(item => {
            console.log(`${item.name} - $${item.price} x ${item.quantity} = $${item.price * item.quantity}`);
        });
        console.log(`Total: $${this.getTotal().toFixed(2)}`);
    }
};

// Using the cart
cart.addItem("Laptop", 999.99, 1);
cart.addItem("Mouse", 29.99, 2);
cart.addItem("Keyboard", 79.99, 1);
cart.displayCart();

Example 3: Text Analysis

// Text analysis utility
function analyzeText(text) {
    // Remove punctuation and convert to lowercase
    let cleanText = text.toLowerCase().replace(/[^\w\s]/g, '');
    let words = cleanText.split(/\s+/).filter(word => word.length > 0);

    // Count words
    let wordCount = words.length;

    // Count unique words
    let uniqueWords = [...new Set(words)].length;

    // Find most common word
    let wordFreq = {};
    words.forEach(word => {
        wordFreq[word] = (wordFreq[word] || 0) + 1;
    });

    let mostCommon = Object.entries(wordFreq)
        .sort((a, b) => b[1] - a[1])[0];

    return {
        totalWords: wordCount,
        uniqueWords: uniqueWords,
        mostCommonWord: mostCommon[0],
        frequency: mostCommon[1],
        averageWordLength: (cleanText.replace(/\s/g, '').length / wordCount).toFixed(2)
    };
}

let text = "JavaScript is awesome. JavaScript makes web development fun and JavaScript is everywhere!";
let analysis = analyzeText(text);
console.log(analysis);

Session Summary

Key Points
  • Strings are immutable and have many built-in methods for manipulation
  • Template literals provide easy string interpolation and multi-line support
  • Arrays store ordered collections and offer powerful methods like map, filter, and reduce
  • Array methods can be chained for complex data transformations
  • Objects store key-value pairs and are fundamental to JavaScript
  • The spread operator (...) and destructuring simplify working with arrays and objects
  • JSON is used for data exchange and can be converted to/from JavaScript objects
  • Understanding the difference between primitive and reference types is crucial
Next Session Preview

In the next session, we will explore Functions and Events in JavaScript, including function declarations, arrow functions, event handling, and callback functions.