Ch 20 Programming
Ch 20 Programming
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>
<body>
<h1>This is my first web page</h1>
<script>
document.write("Have a great day");
Page 1 of 39
</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.
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>
Page 2 of 39
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".
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
>
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.
Page 3 of 39
Example:
<script>
var name = "Alice";
var age = 25;
console.log("Name:", name);
console.log("Age:", age);
</script>
Page 4 of 39
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).
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.
Page 5 of 39
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.
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 6 of 39
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 7 of 39
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).
Example:
<body>
<h1>Select a Fruit</h1>
Page 8 of 39
<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>
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>
Page 9 of 39
<script>
function showSelected() {
if (document.getElementById("apple").checked) { // Check if the "apple" radio button is
selected
Page 10 of 39
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.).
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>
Page 11 of 39
<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>
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 12 of 39
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>
Form Events:
Page 13 of 39
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 14 of 39
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 Specifies the font type for the .style.fontFamily = "Arial, sans-
family element. 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- Specifies whether to use small-caps .style.fontVariant = "small-caps";
variant or 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 .style.textTransform =
transform (e.g., capitalize, uppercase, "uppercase";
lowercase.
Page 15 of 39
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>
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>
Page 16 of 39
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.
Arithmetic operators:
Operat Descriptio Description
or n
+ Addition If JavaScript thinks the variables are numbers, then it add
them.
- Subtraction Subtracts the right operand from the left operand.
* Multiplicatio Multiplies two values.
n
/ 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:
Page 17 of 39
</script>
String Operators:
String operators are used to work with strings (text).
Operator Description Description
+ Concatenation You can combine strings using the +
operator.
+= Concatenation This operator can be used to add a string
Assignment 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 18 of 39
Assignment Operators:
In JavaScript, assignment operators are used to assign values to variables.
Operat Description Description
or
+= Add and Adds the right-hand operand to the left-hand
Assign operand and assigns the result to the left-hand
variable.
–= Subtract and Subtracts the right-hand operand from the left-
Assign hand 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 -= :",
JavaScript</h1> result);
<script> document.write("<br><br>");
var a = 10; result *= 2;
var b = 5; document.write("result after *= :",
result);
var result;
document.write("<br><br>");
result = a;
result /= 4;
result += b;
document.write("result after /= :",
document.write("result after += :",
result);
result);
</script>
document.write("<br><br>");
</body>
Page 19 of 39
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).
Operato Description Description
r
== 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 Checks if the left operand is less than or
to 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.
Example:
<script>
var x = 10;
var y = 20;
var str1 = "apple";
Page 20 of 39
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>
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>");
Page 21 of 39
// 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>
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
Page 22 of 39
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>
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 document.write("It's a cool day.");
value
}
if (temperature > 25) {
</script>
document.write("It's a hot day!");
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!");
Page 23 of 39
} else if (temperature >= 15 && temperature <= 25) {
document.write("It's a warm day.");
} else {
document.write("It's a cool day.");
}
</script>
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).
Page 24 of 39
4. default: If no case matches the expression, the default block is executed.
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;
Example 1:
var age = 60;
var result = (age > 59) ? "Adult" : "Not Adult";
document.write(result);
Page 25 of 39
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) {
}
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)
Page 26 of 39
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
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:
Page 27 of 39
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.
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
}
</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);
Page 28 of 39
After that, the condition is evaluated.
If the condition is true, the loop runs again. If the condition is false, the loop stops.
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
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 29 of 39
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()
Page 30 of 39
fruits.pop(); // Removes "Elderberry" from the array
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.
Example:
<script>
function greet() {
document.write("Hello after 2 seconds!");
}
// Call greet function after a delay of 2000 milliseconds (2 seconds)
setTimeout(greet, 2000);
Page 31 of 39
</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>
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 1 st 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).
Example:
<script>
Page 32 of 39
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.
Example:
replace(search, newValue):
Example:
Length:
Syntax: string.length;
Example:
document.write (str.length); // 11
Page 33 of 39
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.
Example:
var str1="Hello";
var str2="World";
Changing Case:
Example:
charAt (number):
Example:
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.
Page 34 of 39
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:
});
Example:
});
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:
});
Example:
Page 35 of 39
var numbers = [1, 3, 5, 7, 8];
});
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:
});
Example:
});
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:
Page 36 of 39
});
Example:
fruits.forEach(function(fruit, index) {
});
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:
});
Example:
});
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
Page 37 of 39
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 {
} catch (error) {
} finally {
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
} catch (error) {
} finally {
Page 38 of 39
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>
function greet() {
alert("Hello, world!");
HTML File:
<body>
<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 39 of 39