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

JS

Uploaded by

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

JS

Uploaded by

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

WEB PROGRAMMING

JAVASCRIPT LECTURES
First semester
Stage:4
Time: Morning

Proposed by: Chra Abdulahad


Outline
 JavaScript
 JavaScript Syntax
 JavaScript Output
 JavaScript Comments
 JavaScript Values
 Strings are text
 JavaScript Variables
 JavaScript Operators
 JavaScript Identifiers
 Incrementing
 Decrementing
 JavaScript Functions
 String Length
 JavaScript Arrays
 Array Methods
 JavaScript type of
 Conditional Statements
 JavaScript Switch Statement
 Different Kinds of Loops
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.
What is a web page?
Content Structure Style Behaviour

Words and HTML CSS Javascript


images
JavaScript
JavaScript is the world's most popular programming language.

JavaScript is the programming language of the Web.

JavaScript is easy to learn.

A scripting language is a lightweight programming language.

JavaScript enhances web pages with dynamic and interactive


features.

JavaScript is runs in client software.


First Example
Let us write our class example to print out "Hello World".
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" language="javascript">
document.write("HelloWord");
</script>
</body>
</html>
Applying JavaScript
You can add JavaScript to your page in three ways:

1. Embed the JavaScript in the page.

2. Place the JavaScript in the document head.

3. Link to JavaScript stored in another file.


Embedding JavaScript
If you’re adding a fairly short JavaScript, your best bet is to
embed it in the HTML document in the code that the
JavaScript affects.

When users open your page, their browsers read your


HTML

source document line by line.

 If your HTML code includes JavaScript within the document


body, the browser perform the actions as it reads the page.
Example
<html>
<head>
<title></title>
</head>
<body>
Today's date is:
<script type="text/javascript" language="javascript">
document.write(Date());
</script>
</body>
</html>

9
Adding JavaScript in the head
If you repeatedly use JavaScript within documents,
consider placing it in the document head element.
Collecting individual statements in one place creates a
function.

You include the JavaScript function command in the


document head element and then run the function from
the document body by calling just its name.
Example
<html>
<head>
<title>Place the JavaScript in the head</title>
<script type="text/javascript" language="javascript">
function printDate()
{
document.write(Date());
}
</script>
</head>
<body>
Today's date is:
<script type="text/javascript" language="javascript">
printDate();
</script>
</body>
</html>.
Linking JavaScript

If you plan to use script functions in several documents,


consider placing them in a separate file and referring to
that file from your document.
The linked document is simply a text file that includes all
your variable definitions and functions. It doesn’t need any
special headings or elements
Example
<html>
<head>
<title>Linking JavaScript</title>
<script src="date.js" type="text/javascript" language="javascript">
</script>
</head>
<body>
<script type="text/javascript" language="javascript">
printDate();
</script>
</body>
</html>
Date.js
function printDate()
{
document.write(Date());
}
JavaScript Syntax
A JavaScript consists of JavaScript statements that are
placed within the <script>... </script> HTML tags in a web
page.

simple syntax of your JavaScript will be as follows


<script ...>
JavaScript code
</script>
The script tag takes two important
attributes:
language: This attribute specifies what scripting language
you are using.
type: This attribute is what is now recommended to indicate
the scripting language in use and its value should be set to
"text/javascript".

So your JavaScript segment will look like:


<script language="javascript" type="text/javascript">
JavaScript code
</script>
JavaScript Can Change HTML Content

One of many JavaScript HTML methods


is getElementById().
The example below "finds" an HTML element (with
id="demo"), and changes the element content (innerHTML)
to "Hello JavaScript":
<html>
<head><title>wellcome</title></head>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button"
onclick='document.getElementById("demo").
innerHTML = "Hello JavaScript!"'>Click Me!</button>

</body>
</html>
JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of


changing an HTML attribute:

document.getElementById("demo").style.fontSize = "35px";
<html>
<head><title>wellcome</title></head>

<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>
JavaScript Can Hide HTML Elements

Hiding HTML elements can be done by changing


the display style:

document.getElementById("demo").style.display = "no
ne";
<html>
<head><title>wellcome</title></head>

<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>
JavaScript Can Show HTML Elements

Showing hidden HTML elements can also be done by


changing the display style:

document.getElementById("demo").style.display = "block";
<html>
<head><title>wellcome</title></head>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can show hidden HTML elements.</p>

<p id="demo" style="display:none">Hello JavaScript!</p>

<button type="button"
onclick='document.getElementById('demo').style.display='block'">Click
Me!</button>

</body>
</html>
JavaScript Output

JavaScript Display Possibilities


JavaScript can "display" data in different ways:

Writing into an HTML element, using innerHTML.


Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
Using inner HTML

To access an HTML element, JavaScript can use


The id attribute defines the HTML element.
The innerHTML property defines the HTML content:
<html>
<head><title>wellcome</title></head>
<body>

<h2>My First Web Page</h2>


<p>My First Paragraph.</p>

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

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

</body>
</html>
Using document.write()

For testing purposes, it is convenient to use document.write():


<html>
<head><title>wellcome</title></head>
<body>
<h2>My First Web Page</h2>
<script>
document.write(5 + 6);
</script>
</body>
</html>
<html>
<head><title>wellcome</title></head>
<body>

<h2>My First Web Page</h2>

<button type="button" onclick="document.write(5 + 6)">Try


it</button>

</body>
</html>

Using document.write() after an HTML document is loaded,


will delete all existing HTML:
Using window.alert()

You can use an alert box to display data:


<html>
<head><title>wellcome</title></head>
<body>

<h2>My First Web Page</h2>


<p>My first paragraph.</p>

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

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

<p>Click the button to display an alert box.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
alert("Hello! I am an alert box!");
}
</script>

</body>
</html>
Using console.log()
For debugging purposes, you can call the console.log() method in the browser to
display data.
<html>
<head><title>wellcome</title></head>
<body>

<h2>Activate Debugging</h2>
<p>F12 on your keybord will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>

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

</body>
window.print()
JavaScript does not have any print object or print methods.
You cannot access output devices from JavaScript.
The only exception is that you can call
the window.print() method in the browser to print the
content of the current window.
<html>
<head><title>wellcome</title></head>
<body>

<h2>The window.print() Method</h2>

<p>Click the button to print the current page.</p>

<button onclick="window.print()">Print this page</button>

</body>
</html>
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.
Single Line Comments

Single line comments start with //.


Any text between // and the end of the line will be ignored
by JavaScript (will not be executed).
This example uses a single-line comment before each code
line:

This example uses a single line comment at the end of


each line to explain the code:
<body>

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
// Change heading:
document.getElementById("myH").innerHTML = "JavaScript
Comments";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

</body>
</html>
Multi-line Comment

Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript.

This example uses a multi-line comment (a comment


block) to explain the code:
<body>

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myH").innerHTML = "JavaScript Comments";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

</body>
</html>
Using Comments to Prevent Execution
<body>

<h2>JavaScript Comments</h2>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

<p>The line starting with // is not executed.</p>

</body>
</html>
JavaScript Values

The JavaScript syntax defines two types of values:


Fixed values
Variable values

Ex:
10.50

1001
Strings are text
written within double or single quotes
<body>

<h2>JavaScript Variables</h2>

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

<script>
var pi = 3.14;
var person = "chra";
var answer = 'Yes I am';

document.getElementById("demo").innerHTML =
pi + "<br>" + person + "<br>" + answer;
</script>

</body>
JavaScript Variables
There are 3 ways to declare a JavaScript variable:
1. Using var
2. Using let
3. Using const

 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.

 In this example, x is defined as a variable. Then, x is assigned (given) the value 6:


let x;
x = 6;
JavaScript Variables
Variables are containers for storing data (values).
In this example, x, y, and z, are variables, declared with
the var keyword:
Example
var x = 5;
var y = 6;
var z = x + y;
x stores the value 5
y stores the value 6
z stores the value 11
<body>

<h2>JavaScript Variables</h2>

<p>In this example, x is defined as a variable.


Then, x is assigned the value of 6:</p>

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

<script>
let x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>

</body>
JavaScript Operators

JavaScript uses arithmetic operators ( + - * / ) to compute values:


EX:
<body>

<h2>JavaScript Operators</h2>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = (5 + 6) * 10;
</script>

</body>
operator ( = )
 JavaScript uses an assignment operator ( = ) to assign values to
variables:
<body>
<h2>Assigning JavaScript Values</h2>
<p id="demo"></p>
<script>
var x, y;
x = 5;
y = 6;
document.getElementById("demo").innerHTML = x + y;
</script>
</body>
JavaScript Expressions

 An expression is a combination of values, variables, and operators,


which computes to a Value. The computation is called an
evaluation.
<body>
<h2>JavaScript Expressions</h2>

<p id="demo"></p>
<script>
var x;
x = 5;
document.getElementById("demo").innerHTML = x * 10;
</script>
</body>
JavaScript Expressions
The values can be of various types, such as numbers and
strings.

For example, “Chra" + " " + “Abdulla", evaluates to “Chra


Abdulla":
JavaScript Keywords

JavaScript keywords are used to identify actions to be


performed.
The var keyword tells the browser to create variables:

 using var or let will produce the same result.


You will learn more about var and let later in this tutorial.

var x, y;
x = 5 + 6;
y = x * 10;
<body>

<h2>The <b>let</b> Keyword Creates Variables</h2>

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

<script>
var x, y;
x = 5 + 6;
y = x * 10;
document.getElementById("demo").innerHTML = y;
</script>

</body>
JavaScript Identifiers

 Identifiers are names. All JavaScript variables must be identified with unique
names.
 In JavaScript, identifiers are used to name variables (and keywords, and
functions, and labels).
 The rules for legal names are much the same in most programming languages.
 In JavaScript, the first character must be a letter, or an underscore (_), or a
dollar sign ($).
 Subsequent characters may be letters, digits, underscores, or dollar signs.
 A letter (A-Z or a-z)
 A dollar sign ($)
 Or an underscore (_)
Numbers are not allowed as the first character.
This way JavaScript can easily distinguish identifiers from numbers.
One Statement, Many Variables

You can declare many variables in one statement.


Start the statement with var and separate the variables
by comma:
Ex:
var person = “chra", carName = "Volvo", price = 200;
A declaration can span multiple lines:
EX:
var person = “chra",
carName = "Volvo",
price = 200;
Adding Strings and Numbers

Adding two numbers, will return the sum, but adding a


number and a string will return a string:
Example
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;

The result of x, y, and z will be:


10
55
Hello5
Incrementing

The increment operator (++) increments numbers.

<body>

<h3>The ++ Operator</h3>

<script>
let x = 5;
x++;
let z = x;
document.write(z);
</script>

</body>
Decrementing

The decrement operator (--) decrements numbers.


Example

let x = 5;
x--;
let z = x;
Exponentiation

The exponentiation operator (**) raises the first operand to


the power of the second operand.

Example

let x = 5;
let z = x ** 2;
// result is 25
JavaScript Assignment Operators

Operator Example Same As

= x=y x=y

+= x += y x=x+y

-= x -= y x=x-y

*= x *= y x=x*y

/= x /= y x=x/y
<body>
<h3>The += Operator</h3>
<p id="demo"></p>

<script>
var x = 10;
x += 5;
document.getElementById("demo").innerHTML = x;
</script>
</body>
// The result :
 The += Operator
 15
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).
<html>
<body>

<h2>JavaScript Functions</h2>

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

<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>

</body>
</html>
JavaScript Function Syntax
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: {}
JavaScript Function Syntax

function name(parameter1, parameter2, parameter3)

{
// code to be executed
}
Why Functions?

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.
String Length

The length property returns the length of a string:

let txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


let length = txt.length;
<html>
<body>

<h2>JavaScript String Properties</h2>

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

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

</body>
</html>
Extracting String Parts

There are 3 methods for extracting a part of a string:


slice(start, end)
substring(start, end)
substr(start, length)
The slice() Method

slice() extracts a part of a string and returns the extracted


part in a new string.
The method takes 2 parameters: the start position, and the
end position (end not included).
This example slices out a portion of a string from position 6
to position 12
Remember: JavaScript counts positions from zero.
First position is 0.
<html>
<body>

<h2>JavaScript String Methods</h2>


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

<script>
let str = "Apple,Banana,Kiwi";
document.getElementById("demo").innerHTML = str.slice(6,12);
</script>

</body>
</html>
The substr() Method

substr() is similar to slice().


The difference is that the second parameter specifies
the length of the extracted part.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
JavaScript Arrays

An array is a special variable, which can hold more than one


value
An array can hold many values under a single name, and
you can access the values by referring to an index number.

Ex:
var stage = [“one", “two", “three"];
<html>
<body>

<h2>JavaScript Arrays</h2>

<script>
var cars = ["Saab", "Volvo", "BMW"];
document.write(cars);
</script>

</body>
</html>
Why Using an Array?

If you have a list of items (a list of car names, for example),


storing the cars in single variables could look like this:
var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";

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


Creating an Array

Using an array literal is the easiest way to create a


JavaScript Array.
Syntax:
var array_name = [item1, item2, ...];
These two different statements both create a new array
containing 6 numbers:
var points = new Array(40, 100, 1, 5, 25, 10);
var points = [40, 100, 1, 5, 25, 10];
Accessing Array Elements

You access an array element by referring to the index


number:
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];

Note: Array indexes start with 0.


[0] is the first element. [1] is the second element.
Changing an Array Element

This statement changes the value of the first element


in cars:

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


cars[0] = "Opel";
<html>
<body>

<h2>JavaScript Arrays</h2>

<script>
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
document.write(cars);
</script>

</body>
</html>
Arrays are Objects
Arrays are a special type of objects.
Arrays use numbers to access its "elements". In this
example, person[0] returns John:
Ex
const person = ["John", "Doe", 46];
Objects use names to access its "members". In this
example, person.firstName returns John:
const person = {firstName:"John",lastName:"Doe", age:46};
<html>
<body>

<h2>JavaScript Objects</h2>

<script>
const person = {firstName:"John", lastName:"Doe", age:46};
document.write( person.firstName);
</script>

</body>
</html>
The length Property

The length property of an array returns the length of an


array (the number of array elements).
Example

var fruits=["Banana", "Orange", "Apple", "Mango"];


let length = fruits.length;
<html>
<body>

<h2>JavaScript Arrays</h2>
<p>The length property returns the length of an array.</p>

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

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.length);
</script>

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

 <h2>JavaScript Arrays</h2>

 <p> array elements are accesses using numeric indexes (starting from 0).</p>

 <script>
 const fruits = ["Banana", "Orange", "Apple", "Mango"];
 document.write(fruits[0]);
 </script>

 </body>
 </html>
Array Methods
The join() method also joins all array elements into a string.
<html>
<body>

<h2>JavaScript Array Methods</h2>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.join(" * "));
</script>

</body>
</html>
Popping and Pushing

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.
Popping

The pop() method removes the last element from an array:


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();

The pop() method returns the value that was "popped out"
<html>
<body>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.pop();
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>
Pushing
 The push() method adds a new element to an array (at the end):
<html>
<body>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.push("Kiwi");
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>
Shifting Elements

Shifting is equivalent to popping, working on the first


element instead of the last.
The shift() method removes the first array element and
"shifts" all other elements to a lower index.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
Sorting an Array

The sort() method sorts an array alphabetically:


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Script Comparison and Logical Operator

Comparison and Logical operators are used to test


for true or false.
Comparison operators are used in logical statements to
determine equality or difference between variables or values.
Given that x = 5, the table below explains the comparison
operators:
Operator Description Comparing Returns
== equal to x == 8 false
x == 5 true
x == "5" true
=== equal value and equal x === 5 true
type
x === "5" false
!= not equal x != 8 true
!== not equal value or not x !== 5 false
equal type
x !== "5" true
x !== 8 true
> greater than x>8 false
< less than x<8 true
>= greater than or equal to x >= 8 false
<= less than or equal to x <= 8 true
<html>
<body>

<h2>JavaScript Comparison</h2>

<script>
let x = 5;
document.write(x == 8);
</script>

</body>
</html>
Logical Operators

Logical operators are used to determine the logic between


variables or values.
Given that x = 6 and y = 3, the table below explains the
logical operators:
Operator Description Example

&& and (x < 10 && y > 1) is true

|| or (x == 5 || y == 5) is false

! not !(x == y) is true


<html>
<body>

<h2>JavaScript Comparison</h2>

<p>The AND operator (&&) returns true if both expressions are true, otherwise it returns
false.</p>

<script>
let x = 6;
let y = 3;

document.write(
(x < 10 && y > 1) + "<br>" +
(x < 10 && y < 1));
</script>

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

<h2>JavaScript Comparison</h2>

<p>The OR operator (||) returns true if one or both expressions are true, otherwise it returns false.</p>

<script>
let x = 6;
let y = 3;

document.write(
(x == 5 || y == 5) + "<br>" +
(x == 6 || y == 0) + "<br>" +
(x == 0 || y == 3) + "<br>" +
(x == 6 || y == 3)
);
</script>

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

<h2>JavaScript Comparison</h2>

<p>The NOT operator (!) returns true for false statements and false for true statements.</p>

<script>
let x = 6;
let y = 3;

document.write(
!(x === y) + "<br>" +
!(x > y)
);
</script>

</body>
</html>
<html>
<body>
<h2>*JavaScript Comparison*</h2>
<script>
document.write( "2" > "12");
</script>
</body>
</html>
When comparing two strings, "2" will be greater than
"12", because (alphabetically) 1 is less than 2.
<html>
<body>

<h2>JavaScript</h2>

<p id="demo"></p>
<script>
let x = 16 + 4 + "Volvo";
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Output:20Volvo
<html>
<body>

<h2>JavaScript</h2>

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

<script>
let x = "Volvo" + 16 + 4;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>

Output:Volvo164
JavaScript type of

There are 6 types of objects:


1. Object
2. Date
3. Array
4. String
5. Number
6. Boolean
JavaScript type
And 2 data types that cannot contain values:

1. null
2. undefined
JavaScript type
The type of Operator

You can use the type of operator to find the data type of a
JavaScript variable.
<html>
<body>

<h2>The JavaScript typeof Operator</h2>

<script>
document.write(
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof function test () {} + "<br>" +
typeof myCar
);
</script>

</body>
</html>
Result
The JavaScript typeof Operator
string
number
boolean
object
function
undefined
JavaScript Type Conversion Table

This table shows the result of converting different


JavaScript values to Number, String, and Boolean:
Original Converted Converted Converted
Value to Number to String to Boolean
false 0 "false" false
true 1 "true" true
0 0 "0" false
1 1 "1" true
<html>
<body>

<h2>JavaScript Type Conversions</h2>

<p>Converting false to other types:</p>

<script>
let x = false;
document.write(
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x)
);
</script>

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

<h2>JavaScript Type Conversions</h2>

<p>Converting the number 0 to other types:</p>

<p id="demo" style="font-family:courier"></p>

<script>
let x = 0;
document.getElementById("demo").innerHTML =
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x);
</script>

</body>
</html>
Result
Conditional Statements
In JavaScript we have the following conditional statements:

Use if to specify a block of code to be executed, if a


specified condition is true
Use else to specify a block of code to be executed, if the
same condition is false
Use else if to specify a new condition to test, if the first
condition is false
Use switch to specify many alternative blocks of code to
be executed
The if Statement

Use the if statement to specify a block of JavaScript code to


be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
The if Statement

Note that if is in lowercase letters. Uppercase letters (If or


IF) will generate a JavaScript error.

Example
Make a "Good day" greeting if the hour is less than 18:00:
<html>
<body>

<h2>JavaScript if</h2>

<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>
The else Statement

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
}
<html>
<body>
<p id="demo"></p>

<script>
const hour = new Date().getHours();
let greeting;

if (hour < 18) {


greeting = "Good day";
} else {
greeting = "Good evening";
}

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

</body>
</html>
The else if Statement

Syntax
if (condition1) {
// block of code to be executed if condition1 is true
}
else if (condition2) {
// block of code to be executed if the condition1 is false
and condition2 is true
}
else {
// block of code to be executed if the condition1 is false
and condition2 is false
}
The else if Statement
Example

If time is less than 10:00, create a "Good morning"


greeting, if not, but time is less than 20:00, create a "Good
day" greeting, otherwise a "Good evening":
<html>
<body>

<script>
const sara = new Date().getHours();
let chra;
if (sara < 10) {
chra = "Good morning";
} else if (sara < 20) {
chra = "Good day";
} else {
chra = "Good evening";
}
document.write (chra);
</script>

</body>
</html>
The else if Statement
the if statement to alert "Hello World" if x is greater than y,
otherwise alert "Goodbye".

if (x > y) {
alert("Hello World"); }
else {
alert("Goodbye");
}
JavaScript Switch Statement
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.
JavaScript Switch Statement
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
JavaScript Switch Statement
Example
The getDay() method returns the weekday as a number
between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the
weekday name:
<html>
<body>
<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";
}
document.write("Today is " + day);
</script>
The break Keyword

When JavaScript reaches a break keyword, it breaks out of


the switch block.

It is not necessary to break the last case in a switch block.


The block breaks (ends) there anyway.
The default Keyword
The default keyword specifies the code to run if there is no
case match
Example
The getDay() method returns the weekday as a number
between 0 and 6.
If today is neither Saturday (6) nor Sunday (0), write a
default message:
The default Keyword
switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
The default case does not have to be the last
case in a switch block:
switch (new Date().getDay()) {
default:
text = "Looking forward to the Weekend";
break;
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
}
The default Keyword

The default keyword specifies the code to run if there is no


case match:
Example
The getDay() method returns the weekday as a number
between 0 and 6.
If today is neither Saturday (6) nor Sunday (0), write a
default message:
<html>
<body>

<script>
let text;
switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
document.write(text);
</script>

</body>
The default Keyword
The default case does not have to be the last case in a
switch block:
<html>
<body>

<script>
let text;
switch (new Date().getDay()) {
default:
text = "Looking forward to the Weekend";
break;
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
}
document.write(text);
</script>

</body>
Common Code Blocks

Sometimes you will want different switch cases to use the


same code.
In this example case 4 and 5 share the same code block,
and 0 and 6 share another code block:
<html>
<body>

<script>
let text;
switch (new Date().getDay()) {
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
}
document.write(text);
</script>

</body>
</html>
Different Kinds of Loops
JavaScript supports different kinds of loops:
for - loops through a block of code a number of times
for/in - loops through the properties of an object
for/of - loops through the values of an iterable object
while - loops through a block of code while a specified
condition is true
do/while - also loops through a block of code while a
specified condition is true
JavaScript For Loop

Loops are handy, if you want to run the same code over and
over again, each time with a different value.
The For Loop

The for loop has the following syntax:


for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Example
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
<html>
<body>

<script>
let text = " ";

for (let i = 0; i <5; i++) {


text += i;
}

document.write(text);
</script>

</body>
</html>
JavaScript While Loop

Loops can execute a block of code as long as a specified


condition is true.

while (condition) {
// code block to be executed
}
Example

In the following example, the code in the loop will run,


over and over again, as long as a variable (i) is less than
10:

Example
while (i < 10) {
text += "The number is " + i;
i++;
}
<html>
<body>
<script>
let text = "";
let i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.write(text);
</script>

</body>
</html>
The Do While Loop

Syntax
do {
// code block to be executed
}
while (condition);
Example
<html>
<body>
<script>
let text = ""
let i = 0;

do {
text += "<br>The number is " + i;
i++;
}
while (i < 10);

document.write(text);
</script>

</body>
</html>
Result :
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The JavaScript for in statement loops through the properties of
an Object:
JavaScript For In

Syntax
for (key in object) {
// code block to be executed
}
<html>
<body>
<script>
const person = {fname:"John", lname:"Doe", age:25};

let txt = "";


for (let x in person) {
txt += person[x];
}
document.write( txt);
</script>
</body>
</html>
Result: John Doe 25
The For Of Loop

The JavaScript for of statement loops through the values of


an iterable object.
Syntax
for (variable of iterable) {
// code block to be executed
}
<html>
<body>
<script>
let language = "JavaScript";

let text = "";


for (let x of language) {
text += x + "<br>";
}

document.write(text);
</script>

</body>
</html>
Result
J
a
v
a
S
c
r
i
p
t
JavaScript Break and Continue

The break statement "jumps out" of a loop.

The continue statement "jumps over" one iteration in the


loop.
The Break Statement
<html>
<body>
<script>
let text = "";
for (let i = 0; i < 10; i++) {
if (i == 3) { break; }
text += i + "<br>";
}

document.write(text);
</script>

</body>
</html>
0
1
2
The Continue Statement
<html>
<body>

<script>
let text = "";
for (let i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += i + "<br>";
}
document.write(text);
</script>

</body>
</html>
Result:
0
1
2
4
5
6
7
8
9
Thank you

You might also like