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

Lecture 5- Java Script

Uploaded by

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

Lecture 5- Java Script

Uploaded by

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

Lecture

5
JavaScript is a cross-platform, object-
oriented scripting language. It is a small
and lightweight language.

JavaScript contains a standard library of


objects, such as Array, Date, and Math,
and a core set of language elements
such as operators, control structures,
and statements.
Core JavaScript can be extended for a variety of
purposes by
supplementing it with additional
Client-side JavaScript extends objects;
the corefor example:
language by supplying objects to control a
browser and its Document Object Model (DOM).
For example, client-side extensions allow an
application to place elements on an HTML form and
respond to user events such as mouse clicks, form
input, and page navigation.
Server-side JavaScript extends the core language
by supplying objects relevant to running JavaScript
on a server.
For example, server-side extensions allow an
application to communicate with a database, provide
continuity of information from one invocation to
another of the application, or perform file manipulations
on a server.
Why Study JavaScript?
JavaScript is one of the 3 languages
all web developers must learn:

1. HTML to define the content of web pages


2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web
pages
One of many HTML methods is getElementById().
This example uses the method to "find" an HTML
element (with id="demo"), and changes the
element content (innerHTML) to "Hello
JavaScript":
<html>
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change HTML
content.</p>
<button type="button"
onclick="document.getElementById('demo').in
nerHTML = 'Hello JavaScript!'">
Click Me!</button>
</body>
<body>
<h1>JavaScript Can Change Images</h1>
<img id="myImage" onclick="changeImage()"
src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the
light.</p>
<script>
function changeImage() {
var image =
document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif"; } }
</script>
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change the
style of an
HTML element.</p>
<script>
function myFunction() {
var x =
document.getElementById("demo");
x.style.fontSize = "25px";
x.style.color = "red";
}
</script>
<button type="button"
onclick="myFunction()">Click
Me!</button>
<script>
<!DOCTYPE html>
function validateInput() {
<html lang="en">
var x, text;
<head>
// Get the value of the input field
<meta charset="UTF-8">
x=
<meta name="viewport"
document.getElementById("numb").value;
content="width=device-width, initial-
scale=1.0">
// Validate if the input is a number
<title>JavaScript Can Change Images
and within the range of 1-10
and Validate Input</title>
if (isNaN(x) || x < 1 || x > 10) {
</head>
text = "Input not valid"; // Invalid
<body>
input
} else {
<h2>JavaScript Can Validate
text = "Input OK"; // Valid input
Input</h2>
}
<p>Please input a number between 1
document.getElementById("demo").innerH
and 10:</p>
TML = text;
<input id="numb" type="number">
}
<button type="button"
</script>
onclick="validateInput()">Submit</butt
</body>
on>
</html>
<p id="demo"></p>
Older examples may use a type
attribute:
<script type="text/javascript">
The type attribute is not required.
JavaScript is the default scripting
language in HTML.

<script>
document.getElementById("demo").i
nnerHTM L = "My First JavaScript";
</script>
A JavaScript function is a block of
JavaScript code, that can be executed
when the function is called or invoked.
For example, a function can be executed
when an event occurs, like when the
user clicks a button

A JavaScript function is placed in the


<head> section or in <body> section of
an HTML page.
The function is invoked (called) when a
button is clicked
<hea
d> <script>
function myFunction() {
document.getElementById("demo").inne
rHTML =
"Paragraph changed.";
}
</script>
</head>
<body>
<h1>JavaScript in Head</h1>
<p id="demo">A Paragraph.</p>
<button type="button"
onclick="myFunction()">Try it</button>
</body>
Scripts can also be placed in external files.
External scripts are practical when the same
code is used in many different web pages.
JavaScript files have the file
extension .js. To use an external script,
put the name of the
script file in the src (source) attribute of
the
<script> tag:
<html>
<head>
<script
src="myScript.js"></script
Placing JavaScript in external files has
some advantages:

1. It separates HTML and code


2. It makes HTML and JavaScript
easier to read and maintain
3. Cached JavaScript files can speed up
page loads
JavaScript can "display" data in different
ways:
1. Writing into an alert
box,
using window.alert().
2. Writing into the HTML
output
using document.write().
3. Writing into an HTML
element,
using innerHTML.
4. Writing into the
browser console,
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script> window.alert(5 + 6);


</script>

</body>
</html>
<html>
<body>

<h1>My First Web


Page</h1>
<p>My first
paragraph.</p>

<script>
document.write(5 +
6);
</script>

</body>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.getElementById("demo").inne
rHTML =
5 + 6;
</script>

</body>
</html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script> console.log(5 + 6);


</script>

</body>
</html>
JavaScript syntax is the set of rules,
how JavaScript programs are
constructed.
JavaScript Programs
1. A computer program is a list of
"instructions" to be "executed" by the
computer. JavaScript statements are
composed of: Values, Operators,
Expressions, Keywords, and Comments.
2. In a programming language, these
program instructions are called
statements.
3. JavaScript is a programming
language.
<body>
<h1>JavaScript Statements</h1>
<p>Statements are separated by semicolons.</p>
<p>The variables x, y, and z are assigned the values
5, 6, and 11:</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x +
y;
document.
getElemen
tById("de
mo").inner
HTML =
z;
The JavaScript syntax defines two
types of values: Fixed values and
variable values.

1. Fixed values are called literals.


2. Variable values are called
variables.
JavaScript keywords are used to
identify actions to be performed.

The var keyword tells the browser to


create a new variable:
var x = 5 +
6; var y = x
* 10;

Other are
char, String, Array, toString, NaN,
valueOf, and more…
Declaration in js:
function example() {
var a = 1; // Function-scoped variable
let b = 2; // Block-scoped variable
const c = 3; // Block-scoped constant

if (true) {
var a = 4; // Overwrites the previous
value of a
let b = 5; // Scoped only to this block
// const c = 6; // Error: Re-declaring a
constant in the same block
console.log(a); // 4
console.log(b); // 5
}

console.log(a); // 4 (because var is function-


scoped)
console.log(b); // 2 (because let is block-
scoped)
console.log(c); // 3 (because const is block-
scoped and unchanging)
}
example();
Not all JavaScript statements are
"executed".
Code after double slashes // or
between /* and */ is treated as a
comment.
Comments are ignored, and will
not be executed:
var x = 5; // I will be executed
// var x = 6; I will NOT be
executed
Identifiers are names.

In JavaScript, identifiers are used to


name variables (and keywords, and
functions, and labels).

In JavaScript, the first character must be


a letter, an underscore (_), or a dollar
sign ($).
Subsequent characters may be letters,
digits,
underscores, or dollar signs.
All JavaScript identifiers are case
sensitive

The variables lastName and lastname,


are two different variables.

lastName = "Doe";
lastname =
"Peterson";
JavaScript uses the Unicode character
set.
Unicode covers (almost) all the
characters, punctuations, and
symbols in the world
JavaScript Assignment Operators
Shift Assignment Operators
Bitwise Assignment Operators
Logical Assignment Operators
Data Types
JavaScript has 8 Datatypes:
String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object
JavaScript Function Syntax

function name(parameter1, parameter2,


parameter3) {
// code to be executed
}

• Function parameters are listed inside the parentheses


() in the function definition.
• Function arguments are the values received by the
function when it is invoked.
• Inside the function, the arguments (the parameters)
behave as local variables.
JavaScript Objects

Object Properties
• A real life car has properties like weight
and color:
• car.name = Fiat, car.model = 500,
car.weight = 850kg, car.color = white.
• Car objects have the same properties,
but the values differ from car to car.
Creating a JavaScript Object
1. // Create an Object
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
2. // Create an Object
const person = {};

// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

3. // Create an Object
const person = new Object();

// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
Accessing Object Properties

• objectName.propertyName
• objectName["propertyName"]

JavaScript Object Methods

const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + "
" + this.lastName;
}
};
JavaScript Objects are Mutable

• Objects are mutable: They are addressed by reference,


not by value.
• If person is an object, the following statement will not
create a copy of person:

//Create an Object
const person = {
firstName:"John",
lastName:"Doe",
age:50, eyeColor:"blue"
}

// Create a copy
const x = person;

// Change Age in both


x.age = 10;
Accessing JavaScript Properties
Example:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Object Properties</h1>
<h2>Access a Property with .</h2>

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

<script>
const person = {
firstname: "John",
lastname: "Doe",
age: 50,
eyecolor: "blue"
};

document.getElementById("demo").innerHTML = person.firstname
+ " is " + person.age + " years old.";
</script>

</body>
</html>
Adding New Properties
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Object Properties</h1>
<h2>Adding a new Property</h2>

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

<script>
const person = {
firstname: "John",
lastname: "Doe",
age: 50,
eyecolor: "blue"
};

person.nationality = "English";
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.nationality + ".";
</script>

</body>
</html>
Deleting Properties
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Object Properties</h1>
<h2>Deleting a Property</h2>

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

<script>
const person = {
firstname: "John",
lastname: "Doe",
age: 50,
eyecolor: "blue"
};

delete person.age;

document.getElementById("demo").innerHTML =
person.firstname + " is " + person.age + " years old.";
</script>

</body>
</html>
Nested Objects
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<h2>Accessing Nested Objects</h2>

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

<script>
// Create nested Objects
const myObj = {
name: "John",
age: 30,
myCars: {
car1: "Ford",
car2: "BMW",
car3: "Fiat"
}
}
document.getElementById("demo").innerHTML =
myObj.myCars.car2;
</script>

</body>
</html>
Accessing Object Methods
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<h2>Object Methods</h2>
<p>A method is a function definition stored as a property
value.</p>

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

<script>
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};

document.getElementById("demo").innerHTML =
person.fullName();
</script>
</body>
Displaying Object Properties:

Some solutions to display JavaScript


objects are:
• Displaying the Object Properties by
name
• Displaying the Object Properties in a
Loop
• Displaying the Object using
Object.values()
• Displaying the Object using
JSON.stringify()
Displaying Object Properties
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<h2>Displaying Properties</h2>

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

<script>
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};

// Display Properties
document.getElementById("demo").innerHTML = person.name + ",
" + person.age + ", " + person.city;
</script>

</body>
</html>
Displaying Properties in a Loop
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<h2>Display Properties</h2>

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

<script>
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};

// Build a Text
let text = "";
for (let x in person) {
text += person[x] + " ";
};

// Display the Text


document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>
Using Object.values()
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<h2>The Object.values() Method</h2>
<p>Object.values() returns an array of values from an object:</p>

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

<script>
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};

// Create an Array
const myArray = Object.values(person);

// Display the Array


document.getElementById("demo").innerHTML = myArray;
</script>

</body>
</html>
Using JSON.stringify()
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<h2>Display Properties with JSON</h2>

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

<script>
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};

// Display JSON
document.getElementById("demo").innerHTML = JSON.stringify(person);
</script>

</body>
</html>
JavaScript String Methods
JavaScript Arrays
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>Array indexes are zero-based, which means the first


item is [0].</p>

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

<script>
const cars = ["Saab","Volvo","BMW"];

document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>
Converting an Array to a String

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


document.getElementById("demo").innerHTML =
fruits.toString();

Access the Full Array

const cars = ["Saab", "Volvo", "BMW"];


document.getElementById("demo").innerHTML = cars;
Accessing the First Array Element

const fruits =
["Banana", "Orange", "Apple", "M
ango"];
let fruit = fruits[0];
Accessing the Last Array Element

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


let fruit = fruits[fruits.length - 1];

Looping Array Elements

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


let fLen = fruits.length;

let text = "<ul>";


for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>

<p>Call a function for each array element:</p>

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

<script>
const fruits = ["Banana", "Orange", "Apple",
"Mango"];

let text = "<ul>";


fruits.forEach(myFunction);
text += "</ul>";

document.getElementById("demo").innerHTML =
text;

function myFunction(value) {
text += "<li>" + value + "</li>";
}
</script>

</body>
</html>
Adding Array Elements

New element can also be added to an array using the length property:

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


fruits[fruits.length] = "Lemon"; // Adds "Lemon"
to fruits
Associative Arrays
• Many programming languages support arrays with
named indexes.
• Arrays with named indexes are called associative
arrays (or hashes).
• JavaScript does not support arrays with named
indexes.
• In JavaScript, arrays always use numbered
indexes.
The Difference Between Arrays and
Objects
• In JavaScript, arrays use numbered indexes.
• In JavaScript, objects use named indexes.
How to Recognize an Array
JavaScript Array Methods
JavaScript Array Search
Method Description Example Output
Returns the first index of
indexOf() a specified element or -1 arr.indexOf(3) 2 or -1
if not found.

Returns the last index of a


lastIndexOf() specified element or -1 if arr.lastIndexOf(3) 5 or -1
not found.

Checks if an array
includes() contains a specified value, arr.includes(3) true or false
returns true or false.

Returns the first element


find() that satisfies the provided arr.find(x => x > 3) 4 or undefined
condition.

Returns the index of the


findIndex() first element that satisfies arr.findIndex(x => x > 3) 1 or -1
the condition.

Returns a new array with


filter() all elements that satisfy arr.filter(x => x > 3) [4, 5]
the condition.

Checks if at least one


some() element satisfies the arr.some(x => x > 3) true or false
condition.

Checks if all elements


every() arr.every(x => x > 3) true or false
satisfy the condition.
JavaScript Sorting Arrays
// Example Array
const numbers = [12, 1, 3, 2];

// Default Sorting (Lexicographical)


numbers.sort();
console.log("Default Sort:", numbers); // Output: [1, 12, 2, 3]

// Numeric Sorting (Ascending)


numbers.sort((a, b) => a - b);
console.log("Ascending Order:", numbers); // Output: [1, 2, 3, 12]

// Numeric Sorting (Descending)


numbers.sort((a, b) => b - a);
console.log("Descending Order:", numbers); // Output: [12, 3, 2, 1]

// Reverse the Array


numbers.reverse();
console.log("Reversed Array:", numbers); // Output: [1, 2, 3, 12]

// Sorting an Array of Objects by a Property


const people = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 20 },
{ name: "Charlie", age: 30 }
];

// Sort by Age (Ascending)


people.sort((a, b) => a.age - b.age);
console.log("People Sorted by Age (Ascending):", people);

// Sort by Age (Descending)


people.sort((a, b) => b.age - a.age);
console.log("People Sorted by Age (Descending):", people);

// Sort by Name (Alphabetical)


people.sort((a, b) => a.name.localeCompare(b.name));
console.log("People Sorted by Name (Alphabetical):", people);
JavaScript Array Iteration
Example :
const arr = [1, 2, 3, 4, 5];

// 1. forEach
arr.forEach(num => console.log(num)); // Logs 1, 2, 3, 4, 5

// 2. map
const doubled = arr.map(num => num * 2); // [2, 4, 6, 8, 10]

// 3. filter
const evenNumbers = arr.filter(num => num % 2 === 0); // [2, 4]

// 4. reduce
const total = arr.reduce((acc, num) => acc + num, 0); // 15

// 5. some
const hasOdd = arr.some(num => num % 2 !== 0); // true

// 6. every
const allPositive = arr.every(num => num > 0); // true

// 7. keys and entries


for (const key of arr.keys()) console.log(key); // 0, 1, 2, 3, 4
for (const [index, value] of arr.entries()) console.log(index, value);

// 8. flatMap
const nestedArr = ["a b", "c d"];
const words = nestedArr.flatMap(str => str.split(" ")); // ['a', 'b', 'c', 'd']

// 9. with
const newArr = arr.with(2, 99); // [1, 2, 99, 4, 5]
HTML Events
JavaScript Event Handlers
Event Handler:

In JavaScript, an event handler is a


function or code that runs when a specific
event occurs on an HTML element. Events
can include user actions like clicking a
button, typing in a form, hovering over an
element, or even actions like loading a page.
How Event Handlers Work:
1.Event: Represents a user action or system trigger (e.g.,
click, mouseover, keydown).
2.Handler Function: A function that is executed in response
to the event.
3.Event Binding: The process of associating an event with a
handler function.
Ways to Add Event Handlers:

1. Inline Event Handlers (in HTML):


<button onclick="alert('Button clicked!')">Click
Me</button>

Using JavaScript addEventListener() (Preferred Way):


button id="myButton">Click Me</button>

cript>
onst button = document.getElementById("myButton");
button.addEventListener("click", function () {
alert("Button clicked!");
);
script>
Using HTML DOM Properties:

Assign the event handler function directly to an element’s event


property.

<button id="myButton">Click
Me</button>

<script>
const button =
document.getElementById("myButton");
button.onclick = function () {
alert("Button clicked!");
};
</script>
JavaScript Strings

Strings are for storing text


Strings are written with quotes
Template Strings also known template
literals:

In JavaScript, template strings (also called template


literals) are a more powerful way to work with strings.
They provide an easier and more readable syntax for
string creation, especially when including variables or
expressions inside a string.
Escape Characters
Examples
JavaScript Strings as Objects
Example :
JavaScript Template Strings
 String Templates
 Template Strings
 Template Literals
Template Strings
Expression Substitution
Example
Comparison Operators
If-else 0r if–else if
Switch Statment
JavaScript Loops
For in

const person = { name: 'Alice', age: 25, city: 'Wonderland' };

for (let key in person) {


console.log(key); // Output: "name", "age", "city"
"
}
The For Of Loop
JavaScript While Loop
The Do While Loop
JavaScript Sets
End of
Lecture

You might also like