Arrays, Objects, and Basic DOM Manipulation
1. Arrays
Arrays are one of the fundamental data structures in JavaScript that allow you to store a collection of
elements in an ordered manner. Each item in the array has an index (position), starting from 0 for the
first element.
Creating Arrays:
Arrays are created using square brackets []. Elements inside the array are separated by commas.
const fruits = ["apple", "banana", "cherry"];
In the example above, the array fruits contains three string values: "apple", "banana", and
"cherry".
Array Methods:
JavaScript provides several methods to manipulate arrays.
.push(): Adds one or more elements to the end of the array.
let fruits = ["apple", "banana"];
fruits.push("cherry"); // Adds "cherry" to the end
console.log(fruits); // ["apple", "banana", "cherry"]
.pop(): Removes the last element from the array and returns it.
let fruits = ["apple", "banana", "cherry"];
let lastFruit = fruits.pop(); // Removes "cherry"
console.log(fruits); // ["apple", "banana"]
console.log(lastFruit); // "cherry"
.shift(): Removes the first element from the array and returns it.
let fruits = ["apple", "banana", "cherry"];
let firstFruit = fruits.shift(); // Removes "apple"
console.log(fruits); // ["banana", "cherry"]
console.log(firstFruit); // "apple"
.unshift(): Adds one or more elements to the beginning of the array.
let fruits = ["banana", "cherry"];
fruits.unshift("apple"); // Adds "apple" to the beginning
console.log(fruits); // ["apple", "banana", "cherry"]
.forEach(): Executes a function for each element in the array.
let fruits = ["apple", "banana", "cherry"];
fruits.forEach(function(fruit) {
console.log(fruit); // Logs each fruit
});
2. Objects
Objects in JavaScript are collections of key-value pairs where each key (property) is unique. They are
used to store data in a structured format, making it easy to organize and access related information.
Creating Objects:
An object is defined using curly braces {}, with properties (keys) and values.
const person = {
name: "Alice",
age: 25,
greet: function() {
return "Hello, " + this.name;
};
In the example above:
o name and age are properties (keys).
o "Alice" and 25 are their corresponding values.
o greet is a method (a function) within the object that returns a greeting message
using the name property.
Accessing Object Properties:
You can access an object’s properties in two ways:
Dot notation: Directly using the property name.
console.log(person.name); // "Alice"
Bracket notation: Useful if the property name is dynamic or contains special characters.
console.log(person["age"]); // 25
Modifying Object Properties:
You can also modify an object’s properties by reassigning values:
person.name = "Bob";
console.log(person.name); // "Bob"
3. Basic DOM Manipulation
DOM (Document Object Model) manipulation allows you to interact with and modify the structure,
style, and content of a webpage's HTML elements.
Selecting Elements:
To manipulate elements, you first need to select them.
document.getElementById(): Selects an element by its ID.
let heading = document.getElementById("header");
document.querySelector(): Selects the first matching element based on a CSS selector (e.g.,
a class, ID, or tag).
let firstButton = document.querySelector(".btn");
document.querySelectorAll(): Selects all matching elements based on a CSS selector and
returns a NodeList.
let buttons = document.querySelectorAll(".btn");
Modifying Elements:
Once you have selected an element, you can modify its content or style.
Changing Text Content: The .textContent property allows you to change the text inside an
element.
let heading = document.getElementById("header");
heading.textContent = "Updated Heading"; // Changes the text to "Updated
Heading"
Changing Style: You can directly modify an element’s style using the .style property.
let heading = document.getElementById("header");
heading.style.color = "red"; // Changes the text color to red
Changing HTML Content: The .innerHTML property allows you to modify the HTML content
inside an element.
let content = document.getElementById("content");
content.innerHTML = "<p>This is a new paragraph.</p>"; // Adds new HTML
content
Example - Complete DOM Manipulation:
Here’s a complete example that combines selecting and modifying elements:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation Example</title>
</head>
<body>
<h1 id="header">Old Heading</h1>
<button id="changeTextBtn">Change Heading Text</button>
<script>
const heading = document.getElementById("header");
const changeTextBtn = document.getElementById("changeTextBtn");
changeTextBtn.addEventListener("click", function() {
heading.textContent = "Updated Heading"; // Update text content of the
heading
heading.style.color = "green"; // Change the text color to green
});
</script>
</body>
</html>
In this example:
We select the header element and the changeTextBtn button.
When the button is clicked, the text content of the header element changes, and its color
turns green.
4. Higher-Order Functions in JavaScript
A higher-order function is a function that either takes one or more functions as arguments, returns a
function, or both.
• Function that takes a function as an argument:
function greet(name) {
console.log("Hello " + name);
function processUserInput(callback) {
let name = prompt("Enter your name:");
callback(name);
processUserInput(greet); // greet is passed as a callback
• Function that returns a function:
function multiplier(factor) {
return function(number) {
return number * factor;
};
const multiplyBy2 = multiplier(2);
console.log(multiplyBy2(5)); // 10
• Array methods using higher-order functions: JavaScript provides many array methods that are
higher-order functions like map, filter, and reduce.
o map(): Transforms an array by applying a function to each element.
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
o filter(): Filters an array by a condition.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
o reduce(): Reduces an array to a single value by applying a function.
const numbers = [1, 2, 3];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 6
Summary:
Arrays are used to store ordered collections of values. You can use various methods
like .push(), .pop(), and .forEach() to manipulate arrays.
Objects store data in key-value pairs, allowing you to organize related information and define
methods.
DOM Manipulation allows you to change the content, style, and structure of a webpage by
selecting and modifying HTML elements. Methods like getElementById(), querySelector(),
and textContent enable this interaction.
This knowledge will help students get comfortable with both JavaScript programming and how it
interacts with the HTML structure.