0% found this document useful (0 votes)
2 views14 pages

JavaScript Arrays, and DOM

This document provides an overview of JavaScript arrays, objects, and the Document Object Model (DOM). It explains how to create and manipulate arrays and objects, including accessing and modifying their elements and properties, as well as common methods and real-life applications. Additionally, it covers the DOM's role in enabling JavaScript to interact with HTML, allowing for dynamic content changes and event handling on web pages.

Uploaded by

Douglas Ndinyo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

JavaScript Arrays, and DOM

This document provides an overview of JavaScript arrays, objects, and the Document Object Model (DOM). It explains how to create and manipulate arrays and objects, including accessing and modifying their elements and properties, as well as common methods and real-life applications. Additionally, it covers the DOM's role in enabling JavaScript to interact with HTML, allowing for dynamic content changes and event handling on web pages.

Uploaded by

Douglas Ndinyo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Page 1 of 14

JavaScript Notes

Topic 1: Arrays, Objects and DOM (Document Object Model)

JAVASCRIPT ARRAYS

Learning Objectives

By the end of this lesson, you should be able to:

• Define an array.
• Explain why arrays are used.
• Create arrays in JavaScript.
• Access and modify array elements.
• Use common array methods.
• Loop through an array.
• Apply arrays in real-life situations.

Introduction to Arrays

Imagine you are a class teacher with 40 students.

One way of storing student names is:

let student1 = "John";


let student2 = "Mary";
let student3 = "James";
let student4 = "Peter";
let student5 = "Ann";

This method works for only a few students.

What if there are 200 students?

Creating 200 variables would be difficult to manage.

JavaScript provides a better solution called an Array.

An array is a special variable that stores multiple values inside one variable.

Instead of creating many variables, we create one array.

let students = ["John", "Mary", "James", "Peter", "Ann"];

Now all student names are stored inside one variable called students.
Page 2 of 14

Real-Life Examples of Arrays

Arrays are used almost everywhere.

Examples include:

A school system storing:

• Student names
• Subjects
• Examination marks
• Courses

An online shop storing:

• Products
• Prices
• Categories

A music player storing:

• Songs
• Albums
• Artists

A football application storing:

• Player names
• Teams
• Scores

Visual Representation of an Array

Suppose we have the following array:

let fruits = ["Apple", "Banana", "Orange", "Mango"];

It is stored like this:

Index Value
0 Apple
1 Banana
2 Orange
3 Mango
Page 3 of 14

Notice that arrays start counting from 0, not 1.

This is called Zero-Based Indexing.

Creating Arrays

There are two common ways.

Method 1 (Recommended)

let fruits = ["Apple", "Banana", "Orange"];

Method 2

let fruits = new Array("Apple", "Banana", "Orange");

Although both methods work, the first one is easier and more common.

Accessing Array Elements

To access an element, use its index.

let fruits = ["Apple", "Banana", "Orange"];

[Link](fruits[0]);

Output

Apple

[Link](fruits[1]);

Output

Banana

[Link](fruits[2]);

Output

Orange

Modifying Array Elements

Suppose you want to replace Banana with Mango.


Page 4 of 14

let fruits = ["Apple", "Banana", "Orange"];

fruits[1] = "Mango";

[Link](fruits);

Output

["Apple","Mango","Orange"]

Finding the Number of Elements

Use length.

let fruits = ["Apple","Banana","Orange"];

[Link]([Link]);

Output

Common Array Methods

1. push()

Adds a new item to the end.

let fruits = ["Apple","Banana"];

[Link]("Orange");

[Link](fruits);

Output

["Apple","Banana","Orange"]

2. pop()

Removes the last item.

[Link]();

Output

["Apple","Banana"]

3. shift()
Page 5 of 14

Removes the first element.

[Link]();

Output

["Banana"]

4. unshift()

Adds an element at the beginning.

[Link]("Mango");

Output

["Mango","Banana"]

5. includes()

Checks whether an item exists.

let fruits = ["Apple","Orange"];

[Link]([Link]("Orange"));

Output

true

6. indexOf()

Finds the position of an item.

let fruits = ["Apple","Banana","Orange"];

[Link]([Link]("Orange"));

Output

7. sort()

Sorts alphabetically.

let fruits = ["Orange","Apple","Banana"];


Page 6 of 14

[Link]();

[Link](fruits);

Output

["Apple","Banana","Orange"]

8. reverse()

Reverses the order.

[Link]();

Output

["Orange","Banana","Apple"]

Looping Through Arrays

Sometimes we need to display every element.

Using a for Loop

let fruits = ["Apple","Banana","Orange"];

for(let i=0;i<[Link];i++){

[Link](fruits[i]);

Output

Apple

Banana

Orange

Using for...of

let fruits=["Apple","Banana","Orange"];

for(let fruit of fruits){

[Link](fruit);

This is easier to read.


Page 7 of 14

Practical Example

Suppose a school stores students.

let students=[];

[Link]("John");

[Link]("Mary");

[Link]("James");

[Link](students);

Output

["John","Mary","James"]

Common Mistakes

❌ Starting from index 1.

Wrong

fruits[1]

if you want the first item.

Correct

fruits[0]

❌ Forgetting quotation marks around text.

Wrong

let fruits=[Apple,Banana];

Correct

let fruits=["Apple","Banana"];

Summary

Arrays
Page 8 of 14

• Store multiple values.


• Use indexes starting from 0.
• Can be modified.
• Have many useful methods.
• Can be looped through easily.

Exercise

1. Create an array of five counties in Kenya.


2. Display the first county.
3. Display the last county.
4. Add another county.
5. Remove the last county.
6. Display the total number of counties.

JAVASCRIPT OBJECTS
Learning Objectives

By the end of this lesson, you should be able to:

• Define an object.
• Create objects.
• Access object properties.
• Modify object values.
• Add and delete properties.
• Create object methods.
• Apply objects in real-world situations.

What is an Object?

An object is a data structure used to store related information as key-value pairs.

Think of a student registration form.

Property Value
Name John
Age 20
Course ICT

Instead of storing these separately, we use an object.

let student={
Page 9 of 14

name:"John",

age:20,

course:"ICT"

};

Everything about one student is stored together.

Real-Life Uses of Objects

Objects can represent:

• A student
• A teacher
• A car
• A phone
• A bank account
• A product

Accessing Object Properties

Dot Notation

[Link]([Link]);

Output

John

Bracket Notation

[Link](student["course"]);

Output

ICT

Modifying Properties

[Link]=21;

[Link]([Link]);
Page 10 of 14

Output

21

Adding New Properties

[Link]="Male";

Deleting Properties
delete [Link];

Object Methods

Objects can also contain functions.

let student={

name:"John",

greet:function(){

[Link]("Welcome "+[Link]);

[Link]();

Output

Welcome John

Arrays vs Objects

Array Object
Stores a list Stores related information
Uses indexes Uses property names
Example: Fruits Example: Student

Practical Example
let laptop={

brand:"HP",
Page 11 of 14

ram:"8GB",

price:55000

};

[Link]([Link]);

Output

HP

Exercise

Create an object representing yourself containing:

• Name
• Age
• Course
• County
• Phone Number

Display each property.

DOCUMENT OBJECT MODEL (DOM)


Learning Objectives

You should be able to:

• Explain the DOM.


• Access HTML elements.
• Change HTML content.
• Change styles.
• Handle button clicks.
• Create interactive web pages.

What is the DOM?

DOM stands for Document Object Model.

It is a way that JavaScript uses to communicate with an HTML page.

Think of HTML as a house.

The DOM is the key that allows JavaScript to enter the house and make changes.
Page 12 of 14

Without the DOM, JavaScript cannot change anything on a webpage.

How DOM Works

Suppose you have this HTML.

<h1 id="title">Welcome</h1>

JavaScript can find it.

[Link]("title");

Then change it.

[Link]("title").innerHTML="Hello Students";

The webpage changes immediately.

Selecting HTML Elements

By ID
[Link]("demo");

By Class

[Link]("box");

By Tag Name

[Link]("p");

Modern Method

[Link]("#demo");

[Link](".box");

Changing Text

HTML

<p id="message">Good Morning</p>


Page 13 of 14

JavaScript

[Link]("message").textContent="Good Evening";

Changing CSS Styles


[Link]("message").[Link]="blue";

[Link]("message").[Link]="30px";

[Link]("message").[Link]="yellow";

Handling Button Clicks

HTML

<button onclick="welcome()">Click Me</button>

<p id="demo"></p>

JavaScript

function welcome(){

[Link]("demo").innerHTML="Welcome to JavaScript";

Using Event Listeners

HTML

<button id="btn">Click</button>

JavaScript

[Link]("btn").addEventListener("click",function(){

alert("Button Clicked");

});

Practical Project
HTML

<input type="text" id="name" placeholder="Enter your name">

<button onclick="showName()">Submit</button>
Page 14 of 14

<h2 id="output"></h2>

JavaScript

function showName(){

let username=[Link]("name").value;

[Link]("output").innerHTML="Welcome "+username;

When the user types a name and clicks Submit, the webpage displays a personalized
welcome message.

Summary

• The DOM connects JavaScript to HTML.


• It allows JavaScript to read and modify webpage content.
• You can change text, styles, images, and other elements.
• Events such as button clicks, keyboard input, and mouse movements make webpages
interactive.
• The DOM is the foundation for building dynamic websites and web applications.

End of Topic Assignment


Create a simple Student Registration Page that includes:

1. An input field for the student's name.


2. An input field for the student's course.
3. A Register button.
4. When the button is clicked:
o Display the student's name and course on the page.
o Change the text color to green.
o Display the message: "Registration Successful!"
5. Extend the program by storing several student names in an array, representing each
student as an object, and using the DOM to display all registered students in a list on
the webpage.

You might also like