Chapter 4-JavaScript
Chapter 4-JavaScript
Chapter - 4
Introduction
• As of 2022, 98% of websites use JavaScript on the client side for webpage
behavior, often incorporating third-party libraries.
• All major web browsers have a dedicated JavaScript engine to execute the code
on users' devices.
• JavaScript It is multi-paradigm, supporting event-driven, functional, and
imperative programming styles.
• It has application programming interfaces (APIs) for working with text, dates,
regular expressions, standard data structures, and the Document Object Model
(DOM).
• An application programming interface (API):
• is a way for two or more computer programs to communicate with each other.
• It is a type of software interface, offering a service to other pieces of software
• In contrast to a user interface, which connects a computer to a person, an application
programming interface connects computers or pieces of software to each other.
• The Document Object Model (DOM):
• is a programming interface for HTML(HyperText Markup Language) and XML(Extensible
markup language) documents.
• With DOM, we can easily access and manipulate tags, IDs, classes, Attributes, or
Elements of HTML using commands or methods provided by the Document object.
• Using DOM, the JavaScript gets access to HTML as well as CSS of the web page and can
also add behavior to the HTML elements.
• so basically Document Object Model is an API that represents and interacts with HTML
or XML documents.
• Although Java and JavaScript are similar in name, syntax, and respective
standard libraries, the two languages are distinct and differ greatly in design.
• JavaScript and Java are completely different languages, both in concept and
design.
• JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in
1997.
• ECMA-262 is the official name of the standard. ECMAScript is the official name of the
language.
• JavaScript was initially created to “make web pages alive”.
• The programs in this language are called scripts.
• They can be written right in a web page’s HTML and run automatically as the page loads.
• Scripts are provided and executed as plain text.
• They don’t need special preparation or compilation to run.
• When JavaScript was created, it initially had another name: “LiveScript”.
• But Java was very popular at that time, so it was decided that positioning a new language
as a “younger brother” of Java would help.
• But as it evolved, JavaScript became a fully independent language with its own
specification called ECMAScript, and now it has no relation to Java at all.
• ECMAScript is a JavaScript standard intended to ensure the interoperability of web pages across
different browsers.
• It is standardized by Ecma International in the document ECMA-262.
• Ecma International is a nonprofit standards organization for information and communication systems.
• It acquired its current name in 1994, when the European Computer Manufacturers Association
(ECMA) changed its name to reflect the organization's global reach and activities.
• As a consequence, the name is no longer considered an acronym and no longer uses full capitalization.
Starting with JavaScript
• <script src="myScript1.js"></script>
<script src="myScript2.js"></script>
Example 1 - JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().
<!DOCTYPE html>
<html>
<body>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("demo").innerHTML =
"Hello JavaScript!"'>Click Me!</button>
</body>
</html>
Example 2 - JavaScript Can Change HTML Attributes
<!DOCTYPE html>
<html>
<body>
<p>In this case JavaScript changes the value of the src (source) attribute of
an image.</p>
<button
onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn
on the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button
onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn
off the light</button>
</body>
</html>
Example 3 - JavaScript Can Change HTML Styles (CSS)
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button"
onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>
</body>
</html>
Example 4 - JavaScript Can Hide HTML Elements
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button"
onclick="document.getElementById('demo').style.display='none'">Click Me!</button>
</body>
</html>
T h eH T M L D O M T reo fO b jects
• The DOM is a W3C (World Wide Web Consortium) standard.
• The DOM defines a standard for accessing documents.
• The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs
and scripts to dynamically access and update the content, structure, and style of a document. The W3C DOM
standard is separated into 3 different parts:
• Core DOM - standard model for all document types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents
• The HTML DOM can be accessed with JavaScript (and with other programming languages).
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and methods of each object.
• A property is a value that you can get or set (like changing the content of an HTML element).
• A method is an action you can do (like add or deleting an HTML element).
• The innerHTML Property
• The easiest way to get the content of an element is by using the innerHTML property.
• The innerHTML property is useful for getting or replacing the content of HTML elements.
• The innerHTML property can be used to get or change any HTML element, including <html> and <body>.
• JavaScript HTML DOM Document
• The HTML DOM document object is the owner of all other objects in your web page.
• The document object represents your web page.
<!DOCTYPE html>
<html>
<body>
<p id="intro"></p>
<p id="demo"></p>
<p class="intro"></p>
<script>
document.getElementById("demo").innerHTML = "Paragraph by element";
const x = document.getElementsByClassName("intro");
x[0].innerHTML="Paragraph by class";
const y = document.getElementsByTagName("p");
y[0].innerHTML = "Paragraph by tag";
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<form id="frm1" action="/action_page.php">
First name: <input type="text" name="fname" value="Abebe"><br>
Last name: <input type="text" name="lname" value="Tola"><br><br>
<input type="submit" value="Submit">
</form>
<p>These are the values of each element in the form:</p>
<p id="demo"></p>
<script>
const x = document.forms["frm1"];
let text = "";
for (let i = 0; i < x.length ;i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
JavaScript Output
<html>
<head>
<title>Java</title>
</head>
<body>
<p id="demo"> </p>
<script>
document.getElementById("demo").innerHTML=5+6;
alert("I am alerting. You got this?");
console.log("Hi");
</script>
<button type="button" onclick="document.write('The write property');">Click here</button>
</body>
</html>
• JavaScript statements are composed of: Values, Operators, Expressions,
Keywords, and Comments.
• The statements are executed, one by one, in the same order as they are
written.
• Semicolons separate JavaScript statements.
• JavaScript ignores multiple spaces.
• JavaScript statements can be grouped together in code blocks, inside curly
brackets {...}.
• JavaScript statements often start with a keyword to identify the JavaScript
action to be performed.
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition
switch Marks a block of statements to be executed in different cases
for Marks a block of statements to be executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of statements
JavaScript Syntax
• JavaScript syntax is the set of rules, how JavaScript programs are constructed.
• The JavaScript syntax defines two types of values: Fixed values and Variable
values.
• Fixed values
• Fixed values are called Literals.
• The two most important syntax rules for fixed values are:
• Numbers that are written with or without decimals and Strings that are text, written within double or
single quotes.
• Variable values
• Variable values are called Variables.
• In a programming language, variables are used to store data values.
• JavaScript uses the keywords var, let and const to declare variables.
• An equal sign is used to assign values to variables.
JavaScript Comments
• var x = 5;
• let x = 5;
• const price1 = 5;
const price2 = 6;
let total = price1 + price2;
• All JavaScript variables must be identified with unique names. These unique names are called
identifiers.
• Identifiers are JavaScript names used to name variables,keywords, and functions.
• The rules for legal names are the same in most programming languages.
• A JavaScript name must begin with: A letter (A-Z or a-z) , A dollar sign ($) Or an underscore
(_)
• Subsequent characters may be letters, digits, underscores, or dollar signs.
• Numbers are not allowed as the first character in names.
• All JavaScript identifiers are case sensitive.
• Creating a variable in JavaScript is called "declaring" a variable.
• After the declaration, the variable has no value (technically it is undefined).
• To assign a value to the variable, use the equal sign.
• You can also assign a value to the variable when you declare it.
• You can declare many variables in one statement by separating the variables by
comma.
• If you re-declare a JavaScript variable declared with var, it will not lose its value.
But you cannot re-declare a variable declared with let or const.
• Variables declared inside a { } block cannot be accessed from outside the block.
<p id="demo"></p>
<p id="demo1"></p>
<script>
{ var x=5; // can be accessed outside this block. }
{ let x=2; // cannot be accessed outside this block. }
y=6; // y variable hoisted above the declaration
var y;
document.getElementById("demo").innerHTML="x="+x+" and "+"y="+y;
//**************************************************************
const z = 3;
z = 3.14;
z = z + 10;
document.getElementById("demo1").innerHTML=z;
//**************************************************************
</script>
JavaScript Operators
• There are different types of JavaScript operators:
• Arithmetic Operators
• Arithmetic Operators are used to perform arithmetic on numbers.
• Assignment Operators
• Assignment operators assign values to JavaScript variables.
• Comparison Operators
• Operator Description
• == equal to
• === equal value and equal type
• != not equal
• !== not equal value or not equal type
• > greater than
• < less than
• >= greater than or equal to
• <= less than or equal to
• ? ternary operator
• String Operators
• All the comparison operators above can also be used on strings alphabetically. The + can also be used to add (concatenate) strings. Adding
a number and a string will return a string.
• Logical Operators8
• Operator Description
• && logical and
• || logical or
• ! logical not
<p id="op"></p>
<p id="st"></p>
<script>
let x = 5, y=10;
let str1='Res', str2="ult=";
let female=10, male=30;
//total = female + male + " students";
total = "students=" + female + male; // evaluating expressions left to right
str3=str1+str2; //Concatenation
// z = x + y; //Arithmetic Operator
// z=x<=y; // Comparision operator
// z = (x<y ? x : y); // ternary operator
z= !((x<y) && (y>x)); //Logical operator
document.getElementById("op").innerHTML = str3+z;
document.getElementById("st").innerHTML = total;
</script>
• JavaScript arrays are written with square brackets.
• Array items are separated by commas.
• The following code declares (creates) an array called cars, containing three items (car
names):
const cars = ["Saab", "Volvo", "BMW"];
• Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
• JavaScript objects are written with curly braces {}.
• Object properties are written as name:value pairs, separated by commas.
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
• The object (person) in the example above has 4 properties: firstName, lastName, age, and
eyeColor.
• You can use the JavaScript typeof operator to find the type of a JavaScript variable.
• The typeof operator returns the type of a variable or an expression:
typeof "" // Returns "string“
typeof 314 // Returns "number"
<p id="dtype"></p>
<script>
const person = {firstName:"John", lastName:"Doe"};
document.getElementById("dtype").innerHTML=typeof person;
</script>
JavaScript Functions
html>
<head>
<title></title>
</head>
<body>
<button onmouseover="document.getElementById('dt').innerHTML =
Date();">The time is:</button>
<p id="dt"> </p>
</body>
</html>
JavaScript String Methods
<p id="str"></p>
<script>
let n="Software Engineering";
document.getElementById("str").innerHTML = n.slice(0,10); // end included but not the start
document.getElementById("str").innerHTML = n.slice(10);
document.getElementById("str").innerHTML = n.substring(0,10); //The difference is that start and end values
// less than 0 are treated as 0 in
substring()
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
document.getElementById("str").innerHTML = newText;
document.getElementById("str").innerHTML = newText.toUpperCase();
document.getElementById("str").innerHTML = newText.toLowerCase();
document.getElementById("str").innerHTML = "Hello".concat(" ","World");
document.getElementById("str").innerHTML = " Hellow ".trim();
document.getElementById("str").innerHTML = "5".padStart(4,"x");
document.getElementById("str").innerHTML = "software".charAt(3);
document.getElementById("str").innerHTML = "software".charCodeAt(3);
Conditional Statements
• Very often when you write code, you want to perform different actions for
different decisions.
• You can use conditional statements in your code to do this.
• Use if to specify a block of code to be executed, if a specified condition is true
• Syntax:
• if (condition) {
// block of code to be executed if the condition is true
}
<!DOCTYPE html>
<html>
<body>
<p>Display "Good day!" if the hour is less than 18:00:</p>
<p id="demo">Good Evening!</p>
<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>
</body>
</html>
<p id="demo"></p>
<script>
let day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
}
document.getElementById("demo").innerHTML = "Today is " + day;
JavaScript Loops
With statement saves a lot of typing when properties of same object have to be
accessed. For example, it is common to work with deeply nested object hierarchies.
Example:
<html>
<head>
<title>WITH statement </title>
</head>
<body>
<script>
with(document){
write("Writing using with");
}
</script>
</body>
</html>
JavaScript String Search
<p id="demo"></p>
<script>
let text = "Please LOCATE where 'Locate' occurs!";
let findex = text.indexOf("locate");
let lindex = text.lastIndexOf("locate");
let lindex2=text.lastIndexOf("locate",5);
let indexs=text.search("locate");
let indexs2=text.search(/locate/);
// g indicates all possible matches. i indicates case insensetive
const myArr = text.match(/oc/gi);
let swith = text.startsWith("Please");
let ewith = text.endsWith("occurs");
//document.getElementById("demo").innerHTML = lindex;
//document.getElementById("demo").innerHTML = lindex;
//document.getElementById("demo").innerHTML = indexs;
//document.getElementById("demo").innerHTML = indexs2;
//document.getElementById("demo").innerHTML = myArr.length + " " + myArr;
//document.getElementById("demo").innerHTML = swith;
//document.getElementById("demo").innerHTML = ewith;
</script>
JavaScript Numbers
<p id="demo"></p>
<script>
let x = 123.123;
//document.getElementById("demo").innerHTML = x.toString();
//document.getElementById("demo").innerHTML = x.toExponential();
//document.getElementById("demo").innerHTML = x.toExponential();
//document.getElementById("demo").innerHTML = x.toExponential(4);
//document.getElementById("demo").innerHTML = x.toFixed(2);
//document.getElementById("demo").innerHTML = Number("10");
//document.getElementById("demo").innerHTML = x.valueOf();
let d = new Date("1970-01-02");
document.getElementById("demo").innerHTML = Number(d);
</script>
JavaScript Array Methods
<script>
let my=["home","car","marriage"];
let your=["job","education"];
const x = [[1,2],[3,4],[5,6]];
document.getElementById("demo").innerHTML = my.toString(); //converts an array to a string
document.getElementById("demo").innerHTML = my.join("*"); //you can specify the separator
//document.getElementById("demo").innerHTML = my.pop(); //removes the last element
document.getElementById("demo").innerHTML = my.push("home");//adds a new element
document.getElementById("demo").innerHTML = my.shift(); //pop the first element
document.getElementById("demo").innerHTML = my.concat(your); //merging arrays
document.getElementById("demo").innerHTML = x.flat(); //reducing the dimensionality
document.getElementById("demo").innerHTML = your.splice(1,0,"sport");//position and removed elements
document.getElementById("demo").innerHTML = your;
document.getElementById("demo").innerHTML = my.sort();
document.getElementById("demo").innerHTML = my.reverse();
</script>
<p id="demo"></p>
<script> JavaScript Date Objects
const d = new Date()
document.getElementById("demo").innerHTML = d;
document.getElementById("demo").innerHTML = d.getMonth();
document.getElementById("demo").innerHTML = d.getFullYear();
document.getElementById("demo").innerHTML = d.getDate();
document.getElementById("demo").innerHTML = d.getDay();
document.getElementById("demo").innerHTML = d.getHours();
document.getElementById("demo").innerHTML = d.getMinutes();
document.getElementById("demo").innerHTML = d.getSeconds();
document.getElementById("demo").innerHTML = d.getMilliseconds();
document.getElementById("demo").innerHTML = d.getTime();
document.getElementById("demo").innerHTML = d;
</script>
JavaScript Random
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random()*10);
</script>
</body>
</html>
JavaScript Classes