0% found this document useful (0 votes)
5 views

Ch 20 Programming

Uploaded by

Rifaya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Ch 20 Programming

Uploaded by

Rifaya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Chapter 20 – Programming for the web

It is a programming language which is used to make websites interactive.

HTML and CSS define the structure and style of webpages.

JavaScript allows you to add behavior to your site like responding to user actions, updating
content dynamically and creating animations.

JavaScript can run directly in web browsers, so it is easy to start.

You can add JavaScript to a webpage by writing it inside <script> tags in your HTML file.

Example:

<body>

<h1>This is my first web page</h1>

<script>

alert("Hello world");

</script>

</body>

Displaying output:

Document.write:

The code document.write(the output) will output the text inside the brackets to the web page.

document.write() is a method in JavaScript that allows you to write (or insert) content directly
into the HTML document. This content can be plain text, HTML, or even JavaScript code.
When the document.write() function is called, the content is inserted at the current position
in the document<html>

Page 1 of 46
<body>

<h1>This is my first web page</h1>

<script>

document.write("Have a great day");

</script>

</body>

.innerHTML:

The .innerHTML property allows you to get or set the HTML content of an element. This
means you can use it to dynamically change the content of any HTML element on your page
without overwriting the entire document. .innerHTML modifies the content of a specific
element on the page without affecting other content.

<body>

<h1>This is my first web page</h1>

<p id = "Paragraph 1"></p>

<p id = "Paragraph 2"></p>

<script>

document.getElementById("Paragraph 1").innerHTML = "Myself Rifaya";

document.getElementById("Paragraph 2").innerHTML = "Am working in BISJES";

</script>

In the above example document.getElementId(“elementID”): Finds the HTML element with


the specified id.

.innerHTML allows you to set the content inside the element.

Page 2 of 46
Pop-up boxes:

1. Alert Box

An alert box is used to display a simple message to the user. The user must click the "OK"
button to dismiss the alert.

alert("Hello world");

or window.alert(“Hello world);

2. Confirm Box

A confirm box has two options: Ok and Cancel. It is often used to confirm an action from the
user.

<script>

var userResponse = confirm("Do you want to delete this item?");

if (userResponse) {

alert("Item deleted.");

else {

alert("Action canceled.");

</script>

In this example, if the user confirms, it shows "Item deleted"; if canceled, it shows "Action
canceled".

Page 3 of 46
3. prompt Box

A prompt box allows the user to input data. It displays a text field where the user can type in a
response. It gives them the option of ok and cancel.

<script>

var userName = prompt("What is your name?");

alert("userName ");

</script>

Console.log:
console.log() is designed to log output to the browser's Developer Tools Console for
debugging purposes. It doesn't affect what is displayed on the page itself. This means it doesn't
alter the page's HTML or visual content. Instead, it helps developers track the state of
variables, view error messages, or trace the flow of code execution.

The browser sees that you used console.log(), and it displays the information in the Console
section of its Developer Tools.

Example:

<script>

var name = "Alice";

var age = 25;

console.log("Name:", name);

console.log("Age:", age);

</script>

Page 4 of 46
Where to see the logs:

• Open Developer Tools (F12 or Ctrl+Shift+I or right-click and select Inspect).

• Go to the Console tab to see the logged output.

Variables: A variable is a space in memory that is given a name (an identifier), where you can
store data that can change while the program is running. It is like a storage container where
you can keep data (like numbers, text, etc.) and use it later in your program.

Var is used to declare variables.

Example: var name

Var tells javaScript that you are creating a variable and name is the name of the variable.

Variable Naming Rules:

• Variable names can include letters, numbers, underscores (_), and dollar signs ($).

• Cannot start with a number (e.g., 2ndValue is not allowed).

• Cannot be a JavaScript keyword (like if, else, function, etc.).

• Use meaningful names (e.g., age, name, totalPrice).

• Variables names are case sensitive.

Initializing a Variable: When you declare a variable, you can immediately assign it a value using
the = operator. Assigning means adding a value to that variable.

• Example: var age = 25; – This creates a variable named age and sets it to 25.

Data Types:

The data stored in a variable will be of a set data type. Data types are not declared when
declaring a variable; it is assumed when a value is given to the variable.

• String: A sequence of characters & numbers. Any text string must start and end with
either single or double quotation marks, for example ‘…..’ or “……”. (e.g., "Hello",
'JavaScript').

• Number: A numeric value (e.g., 100, 3.14).

Page 5 of 46
• Boolean: A value that is either true or false.

• Object: A collection of data or a series of named values of the variable (like a person
with a name and age).

• Array: A list of values off the same data type. (e.g., [1, 2, 3]).

• Undefined: A variable declared but not assigned a value.

Functions

A function is a set of instructions that perform a specific task. It is an independent code that
only runs if it is called.

Functions can be a) called from within the JavaScript code, b) called when an event occurs
such as clicking a button, and automatically run.

How Functions Work:

1. Input: The function takes some data (parameters).

2. Processing: It does something with that data (like adding, multiplying, etc.).

3. Output: The function returns a result (a value that you can use later).

All the code that will run in the function needs to be inside the brackets { }.

When you create a function, you can create a variable inside it (local) or outside it (global).

Local Variable:

A local variable is a variable that is defined inside a function. It can only be used within that
function and is not accessible outside of it.

Only accessible inside the function where they are defined. They are "local" to that function.

Exist only as long as the function is running. Once the function finishes, the local variable is
destroyed.

Local Variables are used when you want a variable to be used only within a specific function,
keeping it isolated from the rest of the program.

Page 6 of 46
Global Variable:

A global variable is a variable that is defined outside any function, typically at the top of your
program. It can be accessed and modified from anywhere in your code, including inside
functions.

Accessible throughout the entire program, both inside and outside any function.

Exist for as long as the program runs, and their values can be changed from anywhere.

Global Variables are used when you need a variable to be shared across multiple functions or
parts of your program.

Example:

<script>

var globalVariable = "I am a global variable";

function exampleFunction() {

var localVariable = "I am a local variable"; // Local variable

document.write("Inside the function:", "<br>");

document.write(globalVariable, "<br>"); // Can access global variable inside the function

document.write(localVariable, "<br>"); // Can access local variable inside the function

exampleFunction();

document.write("Outside the function:", "<br>");

document.write(globalVariable); // Can access global variable outside the function

document.write(localVariable);// ERROR: Cannot access local variable outside the function

</script>

Page 7 of 46
Form elements:

Form elements in JavaScript are HTML elements that allow users to input data. These elements
typically include <input>, <select>, <textarea>, <button>, etc.

You need to tell HTML that you are creating a form using the <form></form> tag.

In JavaScript, you can manipulate these elements to create interactive forms, capture user
input, validate data, and process form submissions.

Button:

When the user clicks on an element, for example an HTML button, it can be programmed to
call a JavaScript function.

Example: // JavaScript function that runs when the button is clicked

<body>

<button onclick="showMessage()"> Click me </button>

<script>

function showMessage() {

alert('Hello, you clicked the button!');

</script>

</body>

Page 8 of 46
Text Input Field (<input type="text">)

The <input> element is used to create interactive fields where the user can type text.

The entered data can be accessed and used. The data is accessed using
document.getElementById( ).value with the textbox identifier in the brackets.

Example:

<body>

<label for="userInput">Enter some text: </label>

<input type="text" id="userInput">

<button onclick="showText()">Show Text</button>

<p id="output"></p>

<script>

function showText() {

var inputText = document.getElementById("userInput").value;

document.getElementById("output").innerHTML = inputText;

</script>

Dropdown box:

A dropdown box in JavaScript is an HTML element that allows users to select one option from
a list of options. It is created using the <select> element, and the individual options within the
dropdown are represented by the <option> element.

✓ The <select> element creates the dropdown menu.


✓ The <option> elements represent the items within the dropdown menu.
✓ The value attribute of the <option> element specifies what value will be sent when the
form is submitted (or used in JavaScript).

Page 9 of 46
Example:

<body>

<h1>Select a Fruit</h1>

<select id="fruitDropdown" onchange="displaySelectedFruit()">

<option value="">--Select a fruit--</option>

<option value="apple">Apple</option> //if the user selects "Apple" from the dropdown, the
value "apple" is what will be used when submitting the form

<option value="banana">Banana</option>

<option value="cherry">Cherry</option>

<option value="date">Date</option>

</select>

<p id="selectedFruit">You have selected: </p>

<script>

function displaySelectedFruit() {

var selectedValue = document.getElementById("fruitDropdown").value;

document.getElementById("selectedFruit").innerHTML = "You have selected: " +


selectedValue;

</script>

</body>

Page 10 of 46
Radio Button:

Radio buttons are used when the user needs to select one option from multiple choices. They
are commonly used in forms when there are multiple options, but only one selection is
allowed.

Example:

<body>

<h1>Choose a fruit:</h1>

<label> <input type="radio" id="apple" name="fruit" value="Apple"> Apple </label>

<label> <input type="radio" id="banana" name="fruit" value="Banana"> Banana </label>

<label> <input type="radio" id="cherry" name="fruit" value="Cherry"> Cherry </label>

<button onclick="showSelected()">Show Selected Fruit</button>

<p id="result"></p>

<script>

function showSelected() {

if (document.getElementById("apple").checked) { // Check if the "apple" radio button is selected

document.getElementById("result").innerHTML = "You selected: Apple";

if (document.getElementById("banana").checked) { // Check if the "banana" radio button is selected

document.getElementById("result").innerHTML = "You selected: Banana";

if (document.getElementById("cherry").checked) { // Check if the "cherry" radio button is selected

document.getElementById("result").innerHTML = "You selected: Cherry";

} }

</script> </body>

Page 11 of 46
Changing images:

You can change or set an image by modifying the src (source) attribute of an <img> element.

You can do this by selecting the image with getElementById().

Prepare your images:

• Place image1.jpg and image2.jpg (or any two images you want to use) in the same folder
as your HTML file.

Example:

<body>

<img id="myImage" src="image1.jpg" alt="First Image" width="300" height="200">

<button onclick="changeImage()"> Change Image </button>

<script>

function changeImage() {

var image = document.getElementById("myImage");

image.src = "image2.jpeg";

image.alt = "Second Image";

</script>

Detecting events

Events are actions that occur in the browser or webpage, such as when a user clicks a button,
hovers over an element, submits a form, or presses a key. JavaScript provides ways to detect
these events and trigger specific actions (functions) in response.

You can directly assign event handlers in HTML attributes (like onclick, onmouseover, etc.).

Page 12 of 46
Types of Events:

Mouse Events:

1. click: Triggered when the mouse button is clicked.

Onclick is used in buttons. Clicking the button a function will be called.

Example:

<body>

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

<script>

function showMessage(){

alert("Hello World"); }

</script>

</body>

2. mouseover: Triggered when the mouse pointer enters an element.

In the below example, when the user puts their cursor over the image, the image will change.

Example:

<body>

<h1> mouseover example</h1>

<img src="image1.jpg" id="imageHolder" width="300" Height="200"


onmouseover="changeImage()">

<script>

function changeImage(){

document.getElementById("imageHolder").src="image2.jpeg" }

</script> </body>

Page 13 of 46
3. mouseout: Triggered when the mouse pointer leaves an element.

In the below example, when the user moves the cursor away from the image, a different
function is called.

Example:

<body>

<h1> mouseout example</h1>

<img src="image1.jpg" id="imageHolder" width="300" Height="200"


onmouseover="changeImage1()" onmouseout="changeImage2()">

<script>

function changeImage1(){

document.getElementById("imageHolder").src="image2.jpeg"

function changeImage2(){

document.getElementById("imageHolder").src="image1.jpg"

</script>

</body>

Page 14 of 46
Keyboard Events:

keydown: Triggered when a key is pressed.

In the below example, every time the user types a letter a message will output.

<body>

<h1> keydown example</h1>

<input type="text" onkeydown="outputLetter()">

<script>

function outputLetter(){

alert("Letter clicked")

</script>

</body>

Window Events:

load: Triggered when the entire page (including images, scripts, etc.) has finished loading.

When onload is attached to an element, it will run when the element is called or loaded.

Example:

<body onload = "outputText()">

<h1> Onload Example</h1>

<script>

function outputText(){

alert("Hello World"); }

</script>

</body>

Page 15 of 46
Form Events:

Change event: Onchange is typically used to detect when the value of an input element (like a
text field, checkbox, select dropdown, etc.) changes. This event occurs when the element's
value is modified, and the element loses focus.

In the below example, when the user changes their option in the drop-down box, the function
will called.

<body>

<h1> onchange example</h1>

<select id="colours" onchange="outputText()">

<option> purple</option>

<option> orange</option>

<option> blue</option>

</select>

<script>

function outputText(){

alert("Hello world")

</script>

</body>

Page 16 of 46
Changing HTML styles:

In HTML, style refers to the appearance of elements on the page like:

• Colors (e.g., background color, text color).

• Size (e.g., width, height).

• Position (e.g., left, right, margin).

• Text properties (e.g., font size, font style)

After the name of your element, put the command .style and then the name of the style you
are trying to change, for example, .color, or .fontsize.

Style Function Example


Font family Specifies the font type for the element. .style.fontFamily = "Arial, sans-serif"
Font size Specifies the size of the font. .style.fontSize = "16px";
Font- Specifies the thickness of the font .style.fontWeight = "bold ";
weight characters(normal, bolder, lighter)
font-style Specifies the style of the font (e.g., .style.fontStyle = "italic";
italic, oblique).
font-variant Specifies whether to use small-caps or .style.fontVariant = "small-caps";
normal text.
line-height Specifies the height of a line of text. .style.lineHeight = "1.5";
letter- Specifies the spacing between .style.letterSpacing = "2px";
spacing characters.
text- Controls the capitalization of text (e.g., .style.textTransform = "uppercase";
transform capitalize, uppercase, lowercase.

text- Specifies the decoration applied to text .style.textDecoration = "underline";


decoration (underline, overline, line-through).
Background Changes the entire page’s colour or font .style.backgroundColor = “red”;
Colour or colour. .style.color = “green”;
Font Color

Page 17 of 46
Example 1: Changing the Background color

<body>

<h1> Click to change Background color</h1>

<button onclick="changeBackgroundColor()">Change Background Color</button>

<script>

function changeBackgroundColor() {

document.body.style.backgroundColor = "lightblue";

</script>

</body>

Example 2: Changing Font size and Text Colour:

<body>

<h1> Click to change font size and text color</h1>

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

<button onclick="changeTextStyle()"> Change Text Style </button>

<script>

function changeTextStyle() {

var textElement = document.getElementById("text");

textElement.style.color = "green";

textElement.style.fontSize = "48px";

</script>

</body>

Page 18 of 46
Changing Values:

You can change the value stored in a variable after it is declared. To convert data to a string,
use the command String (). To convert data to an integer, use the command Number ().

Example:

<script>

var firstName = "Luca";

var lastName = "Singh";

var age = 28;

alert(firstName);

alert(lastName);

alert(age);

console.log("Name:", firstName);

console.log("Age:", age);

</script>

Operators:

An operator is a symbol, or set of symbols, that perform an action. JavaScript has a number of
types of operators.

• Arithmetic operators
• string operators
• assignment operators
• comparison operators and logical operators
• conditional operator.

Page 19 of 46
Arithmetic operators:

Operator Description Description


+ Addition If JavaScript thinks the variables are numbers, then it add them.
- Subtraction Subtracts the right operand from the left operand.
* Multiplication Multiplies two values.
/ Division Divides the left operand by the right operand.
% Modulus Returns the remainder of a division.
++ Increment Increases a number by 1.
-- Decrement Decreases a number by 1

Example:

<script> document.write(product);

var num1 = 10; document.write(" ");

var num2 = 5; var quotient = num1 / num2;

var sum = num1 + num2; document.write(quotient);

document.write(sum); document.write(" ");

document.write(" "); var remainder = num1 % num2;

var difference = num1 - num2; document.write(remainder);

document.write(difference); document.write(" ");

document.write(" "); </script>

var product = num1 * num2;

Page 20 of 46
String Operators:

String operators are used to work with strings (text).

Operator Description Description


+ Concatenation You can combine strings using the + operator.
+= Concatenation Assignment This operator can be used to add a string to
an existing string and assign it back to the
variable.

Example:

<script>

var firstName = "John";

var lastName = "Doe";

var fullName = firstName + " " + lastName;

document.write("Full Name: " + fullName);

document.write("<br><br>");

var greeting = "Hello";

greeting += ", " + firstName + "!";

document.write("Greeting :" + greeting);

</script>

Page 21 of 46
Assignment Operators:

In JavaScript, assignment operators are used to assign values to variables.

Operator Description Description


+= Add and Assign Adds the right-hand operand to the left-hand operand
and assigns the result to the left-hand variable.
–= Subtract and Subtracts the right-hand operand from the left-hand
Assign operand and assigns the result to the left-hand variable.
*= Multiply and Multiplies the left-hand operand by the right-hand
Assign operand and assigns the result to the left-hand variable.
/= Divide and Divides the left-hand operand by the right-hand
Assign operand and assigns the result to the left-hand variable.

Example:

<body> result -= 3;

<h1>Assignment Operators in document.write("result after -= :", result);


JavaScript</h1>
document.write("<br><br>");
<script>
result *= 2;
var a = 10;
document.write("result after *= :", result);
var b = 5;
document.write("<br><br>");
var result;
result /= 4;
result = a;
document.write("result after /= :", result);
result += b;
</script>
document.write("result after += :", result);
</body>
document.write("<br><br>");

Page 22 of 46
Comparison and Logical operators:

Comparison operators are used to compare two values. The result of a comparison is always a
boolean value: either true or false.

Logical operators are used to combine multiple boolean expressions and return a boolean
value (true or false).

Operator Description Description


== Equal to Compares two values for equality (without
considering the type).
!= Not equal to Compares two values for inequality (without
considering the type).
=== Strict Equal to Compares both the value and the type of two
operands.
!== Strict Not Equal to Compares both the value and the type for
inequality.
> Greater than Checks if the left operand is greater than the
right operand.
>= Greater than or Checks if the left operand is greater than or
equal to equal to the right operand.

< Less than Checks if the left operand is less than the right
operand.
<= Less than or equal to Checks if the left operand is less than or equal
to the right operand.
&& Logical AND Returns true if both operands are true.
|| Logical OR Returns true if at least one of the operands is
true
! Not Replaces a true with false, or a false with true.

Page 23 of 46
Example:

<script>

var x = 10;

var y = 20;

var str1 = "apple";

var str2 = "banana";

document.write("<b>Comparison Operators Results:</b><br><br>");

document.write("x == y: ", (x == y),"<br>");

document.write("x === 10: " , (x === 10) , "<br>");

document.write("x != y: " , (x != y) , "<br>"); // true (10 is not equal to 20)

document.write("x !== 10: " , (x !== 10) , "<br>");

document.write("x > y: " , (x > y) , "<br>"); // false (10 is not greater than 20)

document.write("x < y: " , (x < y) , "<br>"); // true (10 is less than 20)

document.write("x >= 10: " , (x >= 10) , "<br>"); // true (10 is equal to 10)

document.write("y <= 20: " , (y <= 20) , "<br>"); // true (20 is equal to 20)

document.write("str1 == str2: " , (str1 == str2) , "<br>");

document.write("str1 === str2: " , (str1 === str2) , "<br>"); // false (different strings)

</script>

Page 24 of 46
Example 2:

<script>

var a = true;

var b = false;

var c = true;

// AND operator (&&)

document.write(a && b); // Output: false

// Explanation: Since 'a' is true but 'b' is false, the result is false.

document.write("<br><br>");

// OR operator (||)

document.write(a || b); // Output: true

// Explanation: Since 'a' is true, the result is true even if 'b' is false.

document.write("<br><br>");

// NOT operator (!)

document.write(!a); // Output: false

// Explanation: The value of 'a' is true, but the NOT operator reverses it to false.

document.write("<br><br>");

// Combining multiple operators

document.write((a && b) || c); // Output: true

// Explanation: (a && b) is false, but since 'c' is true, the OR operator makes the whole
expression

document.write("<br><br>");

</script>

Page 25 of 46
Conditional Statements:

Conditional statements allow a program to perform different actions depending on the result
of a condition.

If statement:

An if statement is used to execute a block of code only if a specified condition is true. If the
condition is false, the code inside the if block is skipped.

Example:

<body>

<h3>Enter a number:</h3>

<input type="number" id="numberInput">

<button onclick="checkNumber()">Check</button>

<p id="output"></p>

<script>

function checkNumber() {

// Get the value from the input box

var number = document.getElementById("numberInput").value;

// Convert the input to a number

number = Number(number);

// Simple if statement: Check if the number is greater than 10

if (number > 10) {

document.getElementById("output").innerText = "The number is greater than 10!";

</script> </body>

Page 26 of 46
If else:

If-else statement is a control flow structure that allows you to execute different blocks of code
based on certain conditions.

The if statement evaluates an expression (the condition). If the condition is true, the code
inside the if block is executed.

If the condition is false, the code inside the else block is executed.

Example:

<script> } else {

var temperature = 30; // temperature value document.write("It's a cool day.");

if (temperature > 25) { }

document.write("It's a hot day!"); </script>

Else if:

This allows you to have multiple conditions that you set to different outcomes.

Example:

<script>

var temperature = 50; // temperature value

if (temperature > 25) {

document.write("It's a hot day!");

} else if (temperature >= 15 && temperature <= 25) {

document.write("It's a warm day.");

} else {

document.write("It's a cool day.");

</script>

Page 27 of 46
Switch statement:

A switch statement is used to perform different actions based on different conditions. It's like
an if-else if chain, but in a more concise way, especially when checking for multiple values of a
single variable.

It can take a variable (or expression) and then check its value against a series of options.

Switch Statement Syntax

switch (expression) {

case value1:

// code block 1;

break;

case value2:

// code block 2;

break;

...

default:

// default code block;

Key Points:

1. expression: This is the value being checked.

2. case: Each case compares the expression to a value. If it matches, the code inside that
case block is executed.

3. break: Stops the switch statement after a match is found (otherwise, it will continue
checking other cases).

4. default: If no case matches the expression, the default block is executed.

Page 28 of 46
Example:

<script> break;

var day = 3; case 5:

var dayName; dayName = "Friday";

switch (day) { break;

case 1: case 6:

dayName = "Monday"; dayName = "Saturday";

break; break;

case 2: case 7:

dayName = "Tuesday"; dayName = "Sunday";

break; break;

case 3: default:

dayName = "Wednesday"; dayName = "Invalid day";

break; }

case 4: document.write(dayName);

dayName = "Thursday"; </script>

Ternary Operator:

The ternary operator is a special type of selection statement. It has a single comparison and
can then assign a variable a value dependent on whether this comparison is true or false.

Syntax:

condition ? value_if_true : value_if_false;

Page 29 of 46
Example 1:

var age = 60;

var result = (age > 59) ? "Adult" : "Not Adult";

document.write(result);

Example 2:

var marks = 95;

var res = (marks < 40) ? "Unsatisfactory" :

(marks < 60) ? "Average" :

(marks < 80) ? "Good" : "Excellent";

document.write(result);

Loops in JavaScript

Loops in JavaScript allow you to run a block of code multiple times.

It is also called iteration.

They are useful when you want to perform repetitive tasks without writing the same code
repeatedly. There are different types of loops in JavaScript: for, while, do-while, and
for...in/for...of.

1. for loop

The for loop is the most commonly used loop in JavaScript. It runs a block of code a specific
number of times, and you can define the starting point, the condition, and how to change the
value each time the loop runs.

Syntax:

for (initialization; condition; increment) {

Page 30 of 46
Example:

<body>

<h2>For Loop Example</h2>

<button onclick="showNumbers()">Show Numbers</button>

<script>

function showNumbers() {

// Loop from 1 to 5

for (var i = 1; i <= 5; i++) {

document.write(i)

document.write(“<br>”)

</script>

</body>

2. for...in loop

The for...in loop is used to iterate over the keys (properties) of an object or elements in an
array (in terms of indexes). This loop is especially useful for looping through objects, where
you need to access both the property names (keys) and their corresponding values.

Syntax:

for (let key in object) {

// Code to be executed for each property }

key: This is a variable that will hold the name of the property in the object for each iteration.

object: This is the object whose properties you want to iterate over

Page 31 of 46
Example:

<script>

var person = {

name: "Alice",

age: 25,

city: "New York" };

for (let key in person) {

document.write(key + ": " + person[key]+"<br>");

</script>

While loop:

The while loop in JavaScript is used to repeatedly execute a block of code as long as a specified
condition is true.

Syntax of the while loop:

while (condition) {

// Code to be executed as long as condition is true

condition: This is an expression that gets evaluated before each iteration of the loop. If the
condition is true, the code inside the loop runs. If it's false, the loop stops.

Code to be executed: The statements inside the loop will run as long as the condition remains
true.

Page 32 of 46
Example:

<script>

var i = 1; // Initialization: Start from 1

while (i <= 5) { // Condition: Loop will run as long as i is less than or equal to 5

document.write(i + "<br>"); // Output the current value of i

i++; // Increment i by 1 after each iteration

</script>

Do/while loop:

The do...while loop is similar to the while loop, but with a key difference: the condition is
checked after the loop body is executed. This means that the code inside the loop will always
run at least once, even if the condition is false initially.

Syntax of do...while loop:

do {

// Code to be executed

} while (condition);

The code block inside the do is executed first.

After that, the condition is evaluated.

If the condition is true, the loop runs again. If the condition is false, the loop stops.

Page 33 of 46
Example:

<script>

var i = 1; // Initialization: Start from 1

do {

document.write(i + "<br>"); // Output the current value of i and add a line break

i++; // Increment i by 1 after each iteration

} while (i <= 5);

</script>

Arrays

An array in JavaScript is a special variable that can hold multiple values under one name.
Unlike regular variables that can only store a single value, an array can store multiple values of
different types (numbers, strings, objects, etc.).

Arrays in JavaScript are zero-indexed, meaning the first element is at index 0, the second
element is at index 1, and so on.

You can store any type of data in an array: numbers, strings, objects, etc.

Arrays can be accessed by their index, and you can also modify or add elements to them.

Arrays are defined using square brackets [], and elements are separated by commas.

Syntax of an Array:

var arrayName = [element1, element2, element3, ...];

Page 34 of 46
Example:

<script>

var fruits = ["Apple", "Banana", "Cherry", "Date"];

// Access and print each element of the array using index

document.write(fruits[0] + "<br>"); // Output: Apple

document.write(fruits[1] + "<br>"); // Output: Banana

document.write(fruits[2] + "<br>"); // Output: Cherry

document.write(fruits[3] + "<br>"); // Output: Date

</script>

Modifying and Adding Elements to Arrays:

You can modify an element in an array using its index, and you can also add new elements to
the array.

Example:

<script>

var fruits = ["Apple", "Banana", "Cherry", "Date"];

fruits[1] = "Blueberry"; // Modify an element at index 1 (change "Banana" to "Blueberry")

fruits.push("Elderberry"); // Add a new element to the array at the end using push()

document.write(fruits[0] + "<br>"); // Apple // Print the updated array

document.write(fruits[1] + "<br>"); // Blueberry

document.write(fruits[2] + "<br>"); // Cherry

document.write(fruits[3] + "<br>"); // Date

document.write(fruits[4] + "<br>"); // Elderberry

</script>

Page 35 of 46
push(): Adds an element to the end of the array.

fruits.push("Elderberry");

pop(): Removes the last element from the array.

fruits.pop(); // Removes "Elderberry" from the array

shift(): Removes the first element of the array.

fruits.shift(); // Removes "Apple" from the array

unshift(): Adds an element to the beginning of the array.

fruits.unshift("Grapes"); // Adds "Grapes" to the beginning

Timing events

In JavaScript, timing events allow you to execute functions or code after a specified amount of
time or at regular intervals. This can be useful for scenarios like animations, handling user
interactions, or scheduling tasks. There are two main methods for handling timing events in
JavaScript:

1. setTimeout() – Executes a function after a specified delay (in milliseconds).

2. setInterval() – Repeatedly executes a function at a specified interval (in milliseconds).

setTimeout():

Executes a function or a piece of code after a specified time delay.

Syntax:

setTimeout(function, delay, param1, param2, ...)

function: The function to be executed.

delay: Time in milliseconds (1 second = 1000 milliseconds).

param1, param2, ...: Optional parameters that will be passed to the function.

In the below example, the output will be displayed after 2 seconds.

Page 36 of 46
Example:

<script>

function greet() {

document.write("Hello after 2 seconds!");

// Call greet function after a delay of 2000 milliseconds (2 seconds)

setTimeout(greet, 2000);

</script>

setInterval():

Executes a function or a piece of code repeatedly at a fixed interval.

Syntax:

setInterval(function, interval, param1, param2, ...)

function: The function to be executed.

interval: Time in milliseconds between each function call (1 second = 1000 milliseconds).

param1, param2, ...: Optional parameters that will be passed to the function.

Example:

script>

function repeatMessage() {

document.write("This message repeats every 3 seconds.");

// Call repeatMessage function every 3000 milliseconds (3 seconds)

setInterval(repeatMessage, 3000);

</script>

Page 37 of 46
String manipulation

A string manipulator involves working with text(strings) to modify, extract, or analyse parts of
it. When counting letters in a string, the 1st letter is letter 0, the 2nd letter is letter 1, and so on.
Spaces and all symbols all count as letters.

Substring:

The substring (start, end) method is used to extract a part of a string between two specified
indices (start and end) and returns it as a new string. The starting index is inclusive and ending
index is exclusive (not included in the result).

Syntax: string.substring(start, end);

Example:

<script>

var str ="Inul Rifaya"

var result = str.substring(0, 4);

document.write(result);

</script>

Substr(strat, length):

Extracts a portion of a string starting from a specified position (start) for a specified number of
characters (length). If length is omitted, it extracts until the end of the string. It also allows
negative start values, which count from the end of the string.

Syntax: string.substr(strat, length);

Example:

var str = "JavaScript"

document.write(str.substr(4, 6)); // script 6 characters starting from index 4

document.write (str.substr(-6, 6)); // scripts 6 characters strating from 6th to last index.

Page 38 of 46
replace(search, newValue):

Replaces the first occurrence of a substring(search) with a new string(newValue). It is case


sensitive. For multiple occurrences use a regular expression with the g flag.

Syntax: string.replace(search, newValue);

Example:

var str = "I love JavaScript. JavaScript is fun! ";

document.write (str.replace("JavaScript", “Math”)); // “I love Math. Javascript is fun!”

document.write (str.replace(/JavaScript/g, "Math")); // “I love Math. Math is fun!”

Length:

Returns the total number of characters in a string.

Syntax: string.length;

Example:

var str = "Hello World"

document.write (str.length); // 11

Concat():

Concatenate will join string 1 and string 2 together. You can have more than two strings. It
does not modify the original strings. Using the + operator is more common.

Syntax: string1.concat(string2, string3, ….); or string1 + string2

Example:

var str1="Hello";

var str2="World";

document.write (str1.concat(", " , str2, "!")); // “Hello, World”

document.write (str1 + ", " + str2 +"!"); // “Hello, World!”

Page 39 of 46
Changing Case:

toUpperCase() – Converts the string to uppercase.

toLowerCase() – Converts the string to lowercase.

Example:

var text = "Hello World";

document.write(text.touppercase()); //”HELLO WORLD”

document.write(text.toLowerCase()); //”hello world”

charAt (number):

Returns the character in the string at location number.

Example:

var word = "Hello"; // Declare a variable with the correct case

var letter = word.charAt(4); // Access the character at index 4

document.write(letter); // Outputs: "o"

Comments

Comments are used to add explanations or annotations to the code. Comments are ignored by
the JavaScript engine, meaning they have no effect on how the code runs.

Single-line Comments begin with // and extend to the end of the line.

Multi-line Comments are enclosed between /* and */.

Page 40 of 46
Iterative methods

every method:

The every method tests whether all elements in an array pass the test implemented by the
provided function. It returns true if all elements pass the test, otherwise false.

Syntax:

var result = array.every(function(currentValue, index, array) {

// Return true or false based on the condition

});

Example:

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

var areAllPositive = numbers.every(function(number) {

return number > 0; // Check if every number is positive

});

document.write(areAllPositive);

some Method:

The some method checks whether at least one element in an array passes the test implemented
by the provided function. It returns true if any element passes, otherwise false.

Syntax:

let result = array.some(function(currentValue, index, array) {

// Return true or false based on the condition

});

Page 41 of 46
Example:

var numbers = [1, 3, 5, 7, 8];

var hasEven = numbers.some(function(number) {

return number % 2 === 0; // Check if any number is even

});

document.write(hasEven);

filter Method:

The filter method creates a new array with all elements that pass the test implemented by the
provided function. It's often used to filter out unwanted elements.

Syntax:

var newArray = array.filter(function(currentValue, index, array) {

// Return true or false to decide whether to include the element

});

Example:

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

var evenNumbers = numbers.filter(function(number) {

return number % 2 === 0; // Filter out odd numbers

});

document.write(evenNumbers); // Outputs [2, 4, 6

Page 42 of 46
foreach Method:

The forEach method is an array method that executes a provided function once for each array
element. It's an alternative to using a for loop.

Syntax:

array.forEach(function(currentValue, index, array) {

// Code to be executed for each element

});

Example:

var fruits = ["apple", "banana", "cherry"];

fruits.forEach(function(fruit, index) {

document.write(index + ": " + fruit); // Outputs the index and fruit

});

Map Method:

The map method creates a new array with the results of calling a provided function on every
element in the array. Unlike forEach, map returns a new array.

Syntax:

let newArray = array.map(function(currentValue, index, array) {

// Return a new value

});

Page 43 of 46
Example:

var numbers = [1, 2, 3, 4];

var doubled = numbers.map(function(number) {

return number * 2; // Creates a new array with doubled values

});

document.write(doubled); // Outputs [2, 4, 6, 8]

Trap errors

In JavaScript, errors can occur during the execution of your code due to various reasons, such
as syntax mistakes, wrong data types, or incorrect logic. JavaScript provides a way to trap and
handle these errors to prevent the program from crashing. This is achieved through try...catch
blocks and other mechanisms.

The most common way to trap and handle errors in JavaScript is by using the try...catch
statement. It allows you to attempt (or "try") executing a block of code, and if an error occurs,
it "catches" the error and executes a block of code to handle it.

Syntax:

try {

// Code that may throw an error

} catch (error) {

// Code to handle the error

} finally {

// Code that will always run (optional)

Page 44 of 46
try Block: Contains the code that might throw an error.

catch Block: Contains code that runs if an error occurs in the try block. The error object is
passed to the catch block.

finally Block (Optional): Contains code that runs regardless of whether an error occurred or
not. It is often used for cleanup tasks

Example:

try {

let result = 10 / 0; // This will not throw an error, but a result of Infinity

document.write("Result: " + result);

} catch (error) {

document.write("An error occurred: " + error.message); // This block won't execute

} finally {

document.write("This will always run.");

Using External Scripts

In JavaScript, you can include external scripts in your web page or application to modularize
and organize your code better. External scripts are typically stored in separate .js files and are
linked to your HTML using the <script> tag.

To include an external JavaScript file in your HTML document, you use the <script> tag with
the src (source) attribute pointing to the path of the external .js file.

Syntax:

<script src="path/to/your/script.js"></script>

Page 45 of 46
External JavaScript File (app.js)

function greet() {

alert("Hello, world!");

HTML File:

<body>

<button onclick="greet()">Click me to greet</button>

<!-- Including external JavaScript file -->

<script src="app.js">

</script>

</body>

The JavaScript file app.js is included using the <script> tag with the src attribute pointing to its
location.

The function greet() is defined in app.js, and it shows an alert when the button is clicked.

Page 46 of 46

You might also like