In JavaScript, objects are fundamental constructs that represent collections of key-value pairs. These pairs, also known as properties and methods, encapsulate data and functionality related to the object. Objects provide a structured way to manage related data and behavior, making them crucial for building scalable and maintainable applications.
Key Characteristics of Objects:
Objects can be created in several ways, with object literals being the most common method. An object literal is a comma-separated list of key-value pairs enclosed in curly braces {}.
Example of Creating an Object:
let book = {
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
year: 1925,
isAvailable: true
};
In this example, book is an object with properties like title, author, year, and isAvailable.
Properties within an object can be accessed and modified using dot notation or bracket notation.
objectName.propertyNameobjectName["propertyName"] (useful when property names are dynamic or not valid identifiers)console.log(book.title); // Outputs "The Great Gatsby"
book.isAvailable = false; // Modifies the isAvailable property
Methods are functions that are properties of an object. The this keyword in a method refers to the object from which the method is called, providing access to the object’s properties and methods.
Example with Method and this:
let person = {
firstName: "Alice",
lastName: "Johnson",
greet: function() {
console.log("Hello, " + this.firstName + " " + this.lastName);
}
};
person.greet(); // Outputs "Hello, Alice Johnson"
In person.greet, this refers to the person object, allowing access to its firstName and lastName properties.
Let's apply these concepts by creating and using objects in practical scenarios:
Representing a Book:
let book = {
title: "1984",
author: "George Orwell",
publishYear: 1949,
getDescription: function() {
return `${this.title} by ${this.author}, published in ${this.publishYear}`;
}
};
console.log(book.getDescription());
Modeling a Person:
let person = {
name: "John Doe",
age: 30,
occupation: "Software Developer",
introduce: function() {
console.log(`Hi, I'm ${this.name}, a ${this.age}-year-old ${this.occupation}.`);
}
};
person.introduce();
Describing a Product:
let product = {
name: "Laptop",
price: 999.99,
discount: 0.10,
calculateDiscountPrice: function() {
return this.price * (1 - this.discount);
}
};
console.log("Discounted price:", product.calculateDiscountPrice());
These examples showcase how objects in JavaScript can encapsulate related data and behavior, providing a structured and intuitive way to represent complex entities in code. By using objects, developers can create more organized, readable, and maintainable programs.
Arrays in JavaScript are used to store ordered collections of items, which can be of any data type, including numbers, strings, objects, or even other arrays. Arrays are indexed collections, starting from index 0 for the first element, index 1 for the second, and so on.
Creating and Accessing Array Elements:
To create an array, you use square brackets [], with elements separated by commas. You access elements in an array by specifying the index in square brackets.
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Outputs "Apple"
console.log(fruits[2]); // Outputs "Cherry"
Arrays come with built-in methods that facilitate manipulation and querying of the array contents.
map: Transforms the elements in an array and returns a new array with the transformed elements.
let numbers = [1, 2, 3];
let squares = numbers.map(x => x * x); // [1, 4, 9]
filter: Creates a new array with all elements that pass the test implemented by the provided function.
let evenNumbers = numbers.filter(x => x % 2 === 0); // [2]
reduce: Applies a function against an accumulator and each element in the array to reduce it to a single value.
let sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // 6
forEach: Executes a provided function once for each array element.
fruits.forEach(fruit => console.log(fruit));
push: Adds one or more elements to the end of an array and returns the new length of the array.
fruits.push("Durian"); // ["Apple", "Banana", "Cherry", "Durian"]
pop: Removes the last element from an array and returns that element.
let lastFruit = fruits.pop(); // Removes "Durian"
shift: Removes the first element from an array and returns that removed element.
let firstFruit = fruits.shift(); // Removes "Apple"
unshift: Adds one or more elements to the beginning of an array and returns the new length.
fruits.unshift("Strawberry"); // ["Strawberry", "Banana", "Cherry"]
splice: Changes the contents of an array by removing or replacing existing elements and/or adding new elements.
fruits.splice(1, 1, "Mango"); // Replaces "Banana" with "Mango"
These array methods can be used to process and manipulate data within arrays, serving various purposes from transformation to aggregation.
map for transforming data: Create a new array by performing an operation on each element of the original array.filter for filtering data: Extract a subset of an array based on a condition.reduce for accumulating values: Reduce an array to a single value by cumulatively combining its elements.Students should apply these array methods to perform common tasks:
Data Transformation with map:
Convert an array of numbers to an array of their square roots.
let numbers = [4, 9, 16];
let roots = numbers.map(Math.sqrt); // [2, 3, 4]
Data Filtering with filter:
Extract numbers greater than a certain value from an array.
let filteredNumbers = numbers.filter(x => x > 5); // [9, 16]
Accumulating Values with reduce:
Calculate the total of all numbers in an array.
let total = numbers.reduce((sum, current) => sum + current, 0); // 29
Searching and Sorting:
Find elements in an array or sort them based on certain criteria using find, some, every, or sort.
let found = numbers.find(x => x > 10); // 16
numbers.sort((a, b) => a - b); // Sorts numbers in ascending order
Through these exercises, students will gain hands-on experience with JavaScript array methods, learning how to effectively manipulate and process array data. This practice reinforces their understanding of arrays and their
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page structure as a tree of objects, allowing scripts to access and manipulate the document’s content, structure, and styles. Through the DOM, JavaScript can add, remove, and modify elements and attributes, change styles, respond to user events, and more, enabling dynamic and interactive web experiences.
To manipulate the DOM, you first need to select the elements you want to work with. JavaScript provides several methods to select elements from the DOM:
getElementById: Selects an element by its ID.
let element = document.getElementById('myElement');
getElementsByClassName: Returns a live HTMLCollection of all elements with the specified class name.
let elements = document.getElementsByClassName('myClass');
getElementsByTagName: Returns a live HTMLCollection of elements with the given tag name.
let elements = document.getElementsByTagName('div');
querySelector: Returns the first element that matches a specified CSS selector.
let element = document.querySelector('.myClass');
querySelectorAll: Returns a static NodeList of all elements that match a specified CSS selector.
let elements = document.querySelectorAll('.myClass');
After selecting elements, you can manipulate the DOM in various ways:
Modifying Element Properties and Attributes: Change properties like innerText, innerHTML, or attributes like src, href.
let heading = document.getElementById('heading');
heading.innerText = 'New Heading Text';
Changing Styles: Modify an element’s style directly using the style property.
heading.style.color = 'red';
Creating and Inserting Elements: Create new DOM elements with document.createElement and insert them using methods like appendChild or insertBefore.
let newElement = document.createElement('p');
newElement.innerText = 'This is a new paragraph.';
document.body.appendChild(newElement);
Removing Elements: Remove elements from the DOM using removeChild or remove.
let parentElement = document.getElementById('parent');
parentElement.removeChild(heading); // Assuming 'heading' is a child of 'parent'
Let's engage in hands-on exercises to practice DOM manipulation:
Select and Modify Elements: Select elements on a webpage and modify their content, style, or other properties. For example, change the text and color of a heading element.
Create a Dynamic List:
Build a simple interactive list where users can add and remove items. Use prompt to get user input for new items and add them to the list displayed on the webpage.
let ulElement = document.createElement('ul');
document.body.appendChild(ulElement);
function addItem() {
let itemText = prompt('Enter item text');
if (itemText) {
let liElement = document.createElement('li');
liElement.innerText = itemText;
ulElement.appendChild(liElement);
}
}
function removeItem() {
if (ulElement.hasChildNodes()) {
ulElement.removeChild(ulElement.lastChild);
}
}
Respond to User Events:
Add buttons to the webpage that call addItem and removeItem functions when clicked, allowing the user to interact with the list dynamically.
In these exercises, students will learn how to select and manipulate DOM elements, create interactive content, and respond to user events, gaining practical skills in dynamic web page manipulation and enhancing their understanding of how JavaScript interacts with the DOM.