0% found this document useful (0 votes)
3 views26 pages

Chapter 4

Chapter 4 discusses client-side programming with JavaScript, a core web technology used by 98% of websites for dynamic behavior. It covers the basics of JavaScript, including its syntax, variables, and how to manipulate HTML elements through the Document Object Model (DOM). The chapter also highlights the differences between JavaScript and Java, the use of external scripts, and various methods for outputting data.

Uploaded by

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

Chapter 4

Chapter 4 discusses client-side programming with JavaScript, a core web technology used by 98% of websites for dynamic behavior. It covers the basics of JavaScript, including its syntax, variables, and how to manipulate HTML elements through the Document Object Model (DOM). The chapter also highlights the differences between JavaScript and Java, the use of external scripts, and various methods for outputting data.

Uploaded by

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

CHAPTER 4: CLIENT-SIDE PROGRAMMING –JAVASCRIPT

4.1. Introduction
JavaScript often abbreviated as JS, is a programming language that is one of the core technologies of the
World Wide Web, alongside HTML and CSS. 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).

JavaScript engines were originally used only in web browsers, but are now core components of some
servers and a variety of applications. The most popular runtime system for this usage is [Link]. 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. In this
aspect, JavaScript is very different from another language called Java.

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.
4.2. Starting with JavaScript
In HTML, JavaScript code is inserted between <script> and </script> tags. Old JavaScript examples
may use a type attribute: <script type="text/javascript">. The type attribute is not required. JavaScript
is the default scripting language in HTML.
You can place any number of scripts in an HTML document. Scripts can be placed in the <body>, or in
the <head> section of an HTML page, or in both. Placing scripts at the bottom of the <body> element
improves the display speed, because script interpretation slows down the display. 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 a <script> tag:
<script src="[Link]"></script>
You can place an external script reference in <head> or <body> as you like. The script will behave as if it
was located exactly where the <script> tag is located. External scripts cannot contain <script> tags. Placing
scripts in external files has some advantages:
 It separates HTML and code
 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads
To add several script files to one page - use several script tags.
<script src="[Link]"></script>
<script src="[Link]"></script>

Example 1 - JavaScript Can Change HTML Content


One of many JavaScript HTML methods is getElementById().
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='[Link]("demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>
</body>
</html>
Example 2 - JavaScript Can Change HTML Attributes
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>
<button onclick="[Link]('myImage').src='pic_bulbon.gif'">Turn on the
light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button onclick="[Link]('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="[Link]('demo').[Link]='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="[Link]('demo').[Link]='none'">Click Me!</button>
</body>
</html>
4.3. JavaScript HTML DOM
With the HTML DOM, JavaScript can access and change all the elements of an HTML document. When a
web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is
constructed as a tree of Objects:
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. If you want to access any element in an HTML page, you always start
with accessing the document object.

Method Description
[Link](id) Find an element by element id
[Link](name) Find elements by tag name
[Link](name) Find elements by class name

Property Description
[Link] = new html content Change the inner HTML of an element
[Link] = new value Change the attribute value of an HTML element
[Link] = new style Change the style of an HTML element
Method Description
[Link](attribute, value) Change the attribute value of an HTML element

Method Description
[Link](element) Create an HTML element
[Link](element) Remove an HTML element
[Link](element) Add an HTML element
[Link](new, old) Replace an HTML element
[Link](text) Write into the HTML output stream

Method Description
[Link](id).onclick = function(){code} Adding event handler code to an onclick event

Property Description
[Link] Returns all <a> elements that have a name attribute
[Link] Returns the absolute base URI of the document
[Link] Returns the <body> element
[Link] Returns the document's cookie
[Link] Returns the document's doctype
[Link] Returns the <html> element
[Link] Returns the mode used by the browser
[Link] Returns the URI of the document
[Link] Returns the domain name of the document server
[Link] Returns all <embed> elements
[Link] Returns all <form> elements
[Link] Returns the <head> element
[Link] Returns all <img> elements
[Link] Returns the DOM implementation
[Link] Returns the document's encoding (character set)
[Link] Returns the date and time the document was updated
[Link] Returns all <area> and <a> elements that have a href attribute
[Link] Returns the (loading) status of the document
[Link] Returns the URI of the referrer (the linking document)
[Link] Returns all <script> elements
[Link] Returns if error checking is enforced
[Link] Returns the <title> element
[Link] Returns the complete URL of the document

4.4. JavaScript Output


JavaScript can "display" data in different ways:
 Writing into an HTML element, using innerHTML.
 Writing into the HTML output using [Link]().
 Writing into an alert box, using [Link]().
 Writing into the browser console, using [Link](). You open the console using F12.
4.4.1. Using innerHTML
To access an HTML element, JavaScript can use the [Link] (id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML content. The
document object represents a HTML document and it allows one to access all the elements in a HTML
document.

4.4.2. Using [Link]()


For testing purposes, it is convenient to use [Link]().Using [Link]() after an HTML
document is loaded, will delete all existing HTML. The [Link]() method should only be used for
testing.

You can skip the window keyword. In JavaScript, the window object is the global scope object. This means
that variables, properties, and methods by default belong to the window object. This also means that
specifying the window keyword is optional.

4.4.3. Using [Link]()


For debugging purposes, you can call the [Link]() method in the browser to display data.

Example:
<html>
<head>
<title>Java</title>
</head>
<body>
<p id="demo"> </p>
<script>
[Link]("demo").innerHTML=5+6;
alert("I am alerting. You got this?");
[Link]("Hi");
</script>
<button type="button" onclick="[Link]('The write property');">Click here</button>
</body>
</html>
4.5. JavaScript Statements
A computer program is a list of "instructions" to be "executed" by a computer. In a programming
language, these programming instructions are called statements. A JavaScript program is a list of
programming statements. JavaScript statements are composed of: Values, Operators, Expressions,
Keywords, and Comments. Most JavaScript programs contain many JavaScript statements. The
statements are executed, one by one, in the same order as they are written. Semicolons separate
JavaScript statements. Add a semicolon at the end of each executable statement. When separated by
semicolons, multiple statements on one line are allowed. Ending statements with semicolon is not
required, but highly recommended.

JavaScript ignores multiple spaces. You can add white space to your script to make it more readable. For
best readability, programmers often like to avoid code lines longer than 80 characters. If a JavaScript
statement does not fit on one line, the best place to break it is after an operator.

JavaScript statements can be grouped together in code blocks, inside curly brackets {...}. The purpose of
code blocks is to define statements to be executed together. One place you will find statements grouped
together in blocks, is in JavaScript functions.

JavaScript statements often start with a keyword to identify the JavaScript action to be performed.

Here is a list of some of the keywords:


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
4.6. 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
o 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
o 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.
4.7. JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more readable. JavaScript
comments can also be used to prevent execution, when testing alternative code.

 In Single Line Comments, that start with //, Any text between // and the end of the line will be
ignored by JavaScript (will not be executed).
o Example
// Change heading
 Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored by
JavaScript.
o Example

/*
The code below will change the heading with id = "myH"
and the paragraph with id = "myP" in my web page:
*/

4.8. JavaScript Variables


There are 4 Ways to Declare a JavaScript Variable: Using var, Using let, using const and using nothing.
Always declare JavaScript variables with var, let, or const. The var keyword is used in all JavaScript code
from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code
to run in older browsers, you must use var. If you want a general rule: always declare variables with const.
If you think the value of the variable can change, use let.

Examples:
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. Identifiers are used to name variables and 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.
 JavaScript is Case Sensitive
 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.

Example:

{
let x = 2;
}
// x can NOT be used here

Variables declared with the var keyword can NOT have block scope. Variables declared inside a { } block
can be accessed from outside the block.

Example
{
var x = 2;
}
// x CAN be used here
Variables defined with var are hoisted to the top and can be initialized at any time. You can use the
variable before it is declared.
Example:

carName = "Volvo";
var carName;
JavaScript const variables must be assigned a value when they are declared. A const variable cannot be
reassigned.
Example
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error

Redeclaring an existing var or let variable to const, in the same scope, is not allowed:

Example
var x = 2; // Allowed
const x = 2; // Not allowed
{
let x = 2; // Allowed
const x = 2; // Not allowed
}
{
const x = 2; // Allowed
const x = 2; // Not allowed
}
Reassigning an existing const variable, in the same scope, is not allowed:
Example:
const x = 2; // Allowed
x = 2; // Not allowed
var x = 2; // Not allowed
let x = 2; // Not allowed
const x = 2; // Not allowed

Redeclaring a variable with const, in another scope, or in another block, is allowed.


const x = 2; // Allowed
{
const x = 3; // Allowed
}
{
const x = 4; // Allowed
}
4.9. 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 Operators
Operator Description
&& logical and
|| logical or
! logical not

4.10. JavaScript Data Types


JavaScript has 8 Datatypes
1. String
2. Number
3. Big int
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object
In programming, data types is an important concept. To be able to operate on variables, it is important to
know something about the type.

JavaScript evaluates expressions from left to right. Example: the result


of

let x = 16 + 4 + "Volvo"; is 20Volvo.

JavaScript has dynamic types. This means that the same variable can be used to hold different data types:
Example
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
A string (or a text string) is a series of characters like "John Doe". Strings are written with quotes. You can
use single or double quotes:

Example:

// Using double quotes:


let carName1 = "Volvo XC60";
// Using single quotes:
let carName2 = 'Volvo XC60';
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"];

The JavaScript method toString() converts an array to a string of (comma separated) array values.

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


[Link]("demo").innerHTML = [Link]();

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 "John" // Returns "string"
typeof "John Doe" // Returns "string"
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"

4.11. JavaScript Functions


A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is
executed when "something" invokes it (calls it). A JavaScript function is defined with the function
keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits,
underscores, and dollar signs (same rules as variables). The parentheses may include parameter names
separated by commas: (parameter1, parameter2, ...). The code to be executed, by the function, is placed
inside curly brackets: {}.

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.

The code inside the function will execute when "something" invokes (calls) the function:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self invoked)
Example: the following program adds two numbers using function.
<html>
<head>
<title>JS function</title>
</head>
<body>
<p id="func"></p>
<script>
x=add(4,5);
[Link]("func").innerHTML = x;
function add(a,b){ return a+b; }
</script>
</body>
</html>

 You can reuse code: Define the code once, and use it many times. You can use the same code
many times with different arguments, to produce different results.
 Variables declared within a JavaScript function, become LOCAL to the function. Local variables can
only be accessed from within the function. Since local variables are only recognized inside their
functions, variables with the same name can be used in different functions. Local variables are
created when a function starts, and deleted when the function is completed.

4.12. JavaScript Events


HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML pages,
JavaScript can "react" on these events. An HTML event can be something the browser does, or
something a user does. Here are some examples of HTML events:

 An HTML web page has finished loading


 An HTML input field was changed
 An HTML button was clicked
Often, when events happen, you may want to do something. JavaScript lets you execute code when
events are detected. HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements.

Here is a list of some common HTML events:


Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
Example: The following program displays date on mouse over.
html>
<head>
<title></title>
</head>
<body>
<button onmouseover="[Link]('dt').innerHTML = Date();">The time
is:</button>
<p id="dt"> </p>
</body>
</html>
4.13. JavaScript String Methods
 String length  String concat()
 String slice()  String trim()
 String substring()  String trimStart()
 String substr()  String trimEnd()
 String replace()  String padStart()
 String replaceAll()  String padEnd()
 String toUpperCase()  String charAt()
 String toLowerCase()  String charCodeAt()
 String split()

The following Example illustrates the use of all the string methods:
<html>
<head>
<title></title>
</head>
<body>
<p id="str"></p>
<script>
let n="Software Engineering";
[Link]("str").innerHTML = [Link](0,10);
[Link]("str").innerHTML = [Link](10);
[Link]("str").innerHTML = [Link](0,10); //The difference is that start and end values
// less than 0 are treated as 0 in substring()
let text = "Please visit Wachemo!";
let newText = [Link]("Wachemo", "Hossana");
[Link]("str").innerHTML = newText;
[Link]("str").innerHTML = [Link]();
[Link]("str").innerHTML = [Link]();
[Link]("str").innerHTML = "Hello".concat(" ","World");
[Link]("str").innerHTML = " Hellow ".trim(); // removes white space
[Link]("str").innerHTML = "5".padStart(4,"x");
[Link]("str").innerHTML = "software".charAt(3);
[Link]("str").innerHTML = "software".charCodeAt(3);
</script>
</body>
</html>

4.14. 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
}

Example:
<!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) {
[Link]("demo").innerHTML = "Good day!";
}
</script>
</body>
</html>
 Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example:
<script>
const hour = new Date().getHours();
let greeting;
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
[Link]("demo").innerHTML = greeting;
</script>
 The switch statement is used to perform different actions based on different conditions. Use the
switch statement to select one of many code blocks to be executed. The switch expression is
evaluated once. The value of the expression is compared with the values of each case. If there is a
match, the associated block of code is executed. If there is no match, the default code block is
executed.
o Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript switch</h2>
<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;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
[Link]("demo").innerHTML = "Today is " + day;
</script>
</body>
</html>

4.15. JavaScript Loops


 The for statement creates a loop with 3 optional expressions:
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let text = "";
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
[Link]("demo").innerHTML = text;
}
</script>
</body>
</html>
 The JavaScript for in statement loops through the properties of an Object:
Syntax:

for (key in object) {


// code block to be executed
}
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const person = {fname:"John", lname:"Doe", age:25};
let txt = "";
for (let x in person)
{
txt += person[x] + " ";
}
[Link]("demo").innerHTML = txt;
</script>
</body>
</html>

o The JavaScript for in statement can also loop over the properties of an Array:

for (variable in array) {


code
}
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For In</h2>
<p>The for in statement can loops over array values:</p>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
for (let x in numbers) {
[Link](numbers[x]);
}
</script>
</body>
</html>
 The forEach() method calls a function (a callback function) once for each array element.

<!DOCTYPE html>
<html>
<body>
<script>
const numbers = [45, 4, 9, 16, 25];
[Link](myFunction);
function myFunction(v) {
[Link](v);
}
</script>
</body>
</html>
 The while loop statement is simpler than the for loop. It consists of a condition and block
statement. The condition is evaluated before each pass through the loop. If the condition is true
then it executes block statement.
The Syntax is:
while (condition)
{
statements
}
<html>
<head>
<title>JS while</title>
</head>
<body>
<script>
let i=0;
while(i<6){
[Link](i);
[Link]("</br>");
i++;
}
</script>
</body>
</html>
 The do...while loop is much like a while loop. It will repeat the loop until the specified condition is
false. This loop will always be executed at least once, even if the condition is false, because the
block of statements is executed before the condition is tested. In this loop statement, curly braces
are optional.
Example:

<html>
<head>
<title>JS dowhile</title>
</head>
<body>
<script>
let i=0;
do{
[Link](i);
[Link]("</br>");
i++;
} while(i<6);
</script>
</body>
</html>
 Break statement is used to exit from the innermost loop, switch statement, or from the statement
named by label. It terminates the current loop and transfers control to the statement following
the terminated loop. The continue statement skips the statement following it and executes the
loop with next iteration. It is used along with an if statement inside while, do-while, for, or label
statements. The continue statement does not terminate the loop. Instead, in a while loop, it jumps
back to the condition and in a for loop, it jumps to the update expression.
<html>
<head>
<title>JS break continue</title>
</head>
<body>
<script>
for(let i=0;i<=10;i++){
if(i==4)
//continue;
break;
[Link](i);
[Link]("<br>");
}
</script>
</body>
</html>
4.16. JavaScript WITH statement
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>
4.17. JavaScript String Search
 JavaScript String indexOf()
The indexOf() method returns the index (position) the first occurrence of a string in a string.
JavaScript counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is the
third, ...
 JavaScript String lastIndexOf()
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string.

Both indexOf(), and lastIndexOf() return -1 if the text is not found. Both methods accept a second
parameter as the starting position for the search. The lastIndexOf() methods searches backwards
(from the end to the beginning), meaning: if the second parameter is 15, the search starts at
position 15, and searches to the beginning of the string.
 JavaScript String search()
The search() method searches a string for a string (or a regular expression) and returns the
position of the match. The search() method cannot take a second start position argument whereas
the indexOf() method cannot take powerful search values (regular expressions).
 JavaScript String match()
The match() method returns an array containing the results of matching a string against a string
(or a regular expression).
 JavaScript String startsWith()
The startsWith() method returns true if a string begins with a specified value. Otherwise it returns
false:
 JavaScript String endsWith()
The endsWith() method returns true if a string ends with a specified value. Otherwise it returns
false.
Example:
<p id="demo"></p>
<script>
let text = "Please LOCATE where 'Locate' occurs!";
let findex = [Link]("locate");
let lindex = [Link]("locate");
let lindex2=[Link]("locate",5);
let indexs=[Link]("locate");
let indexs2=[Link](/locate/);
// g indicates all possible matches. i indicates case insensetive
const myArr = [Link](/oc/gi);
let swith = [Link]("Please");
let ewith = [Link]("occurs");
//[Link]("demo").innerHTML = lindex;
//[Link]("demo").innerHTML = lindex;
//[Link]("demo").innerHTML = indexs;
//[Link]("demo").innerHTML = indexs2;
//[Link]("demo").innerHTML = [Link] + " " + myArr;
//[Link]("demo").innerHTML = swith;
//[Link]("demo").innerHTML = ewith;
</script>

4.18. JavaScript Numbers


JavaScript has only one type of number. Numbers can be written with or without decimals. Unlike
many other programming languages, JavaScript does not define different types of numbers, like
integers, short, long, floating-point etc. JavaScript numbers are always stored as double precision
floating point numbers.
 The toString() method returns a number as a string. All number methods can be used on any type
of numbers (literals, variables, or expression).
 toExponential() returns a string, with a number rounded and written using exponential notation. A
parameter defines the number of characters behind the decimal point.
 toFixed() returns a string, with the number written with a specified number of decimals.
 The Number() method can be used to convert JavaScript variables to numbers. If the number
cannot be converted, NaN (Not a Number) is returned. Number() can also convert a date to a
number. Number() can also convert a date to a number. The Date() method returns the number of
milliseconds since 1.1.1970.
 [Link]() Returns true if the argument is an integer
 [Link]()
Returns true if the argument is a safe integer. A safe integer is an integer that can be exactly
represented as a double precision number.
 [Link]() Converts a string to a number
 [Link]() Converts a string to a whole number

Example:

<p id="demo"></p>
<script>
let x = 123.123;
//[Link]("demo").innerHTML = [Link]();
//[Link]("demo").innerHTML = [Link]();
//[Link]("demo").innerHTML = [Link]();
//[Link]("demo").innerHTML = [Link](4);
//[Link]("demo").innerHTML = [Link](2);
//[Link]("demo").innerHTML = Number("10");
//[Link]("demo").innerHTML = [Link]();
let d = new Date("1970-01-02");
[Link]("demo").innerHTML = Number(d);
</script>
4.19. JavaScript Array Methods
 The JavaScript method toString() converts an array to a string of (comma separated) array values.

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


[Link]("demo").innerHTML = [Link]();

 The join() method also joins all array elements into a string. It behaves just like toString(), but in
addition you can specify the separator:

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


[Link]("demo").innerHTML = [Link](" * ");

 When you work with arrays, it is easy to remove elements and add new elements. This is what
popping and pushing is. Popping items out of an array, or pushing items into an array.
The pop() method removes the last element from an array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();

 The push() method adds a new element to an array (at the end):

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


[Link]("Kiwi");

 Shifting is equivalent to popping, but working on the first element instead of the last.

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


[Link]();

 The concat() method creates a new array by merging (concatenating) existing arrays. The concat()
method does not change the existing arrays. It always returns a new array.
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = [Link](myBoys);
 The flat() method creates a new array with sub-array elements concatenated to a specified depth.
Flattening an array is the process of reducing the dimensionality of an array.
const myArr = [[1,2],[3,4],[5,6]];
const newArr = [Link]();
 The splice() method can be used to add new items in to specified index to an array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements should be added (spliced
in). The second parameter (0) defines how many elements should be removed. The rest of
the parameters ("Lemon" , "Kiwi") define the new elements to be added. The splice()
method returns an array with the deleted items.

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


[Link](2, 2, "Lemon", "Kiwi");

 The slice() method can take two arguments like slice(1, 3). The method then selects elements from
the start argument, and up to (but not including) the end argument.
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = [Link](1, 3);
 The sort() method sorts an array alphabetically.

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


[Link]();
 The reverse() method reverses the elements in an array. You can use
it to sort an array in descending order.

4.20. JavaScript Date Objects


Date objects are created with the new Date() constructor. There are 9 ways to create a new date object.

 new Date() creates a date object with the current date and time:
const d = new Date();
Date Get Methods
Method Description
getFullYear() Get year as a four digit number (yyyy)
getMonth() Get month as a number (0-11)
getDate() Get day as a number (1-31)
getDay() Get weekday as a number (0-6)
getHours() Get hour (0-23)
getMinutes() Get minute (0-59)
getSeconds() Get second (0-59)
getMilliseconds() Get millisecond (0-999)
getTime() Get time (milliseconds since January 1, 1970)

4.21. JavaScript Random


[Link]() returns a random number between 0 (inclusive), and 1 (exclusive).

// Returns a random integer from 0 to 9:


[Link]([Link]() * 10);

4.22. JavaScript Classes


JavaScript Classes are templates for JavaScript Objects. Use the keyword class to create a class. Always
add a method named constructor():

class ClassName {
constructor() { ... }
}

class Car {
constructor(name, year) {
[Link] = name;
[Link] = year;
}
}

A JavaScript class is not an object. It is a template for JavaScript objects. The example above creates a
class named "Car". The class has two initial properties: "name" and "year".

When you have a class, you can use the class to create objects:

const myCar1 = new Car("Ford", 2014);


const myCar2 = new Car("Audi", 2019);

The example above uses the Car class to create two Car objects. The constructor method is called
automatically when a new object is created. The constructor method is a special method. It has to have
the exact name "constructor". It is executed automatically when a new object is created It is used to
initialize object properties. If you do not define a constructor method, JavaScript will add an empty
constructor method.
Class methods are created with the same syntax as object methods. Use the keyword class to create a
class. Always add a constructor() method. Then add any number of methods.

You might also like