JS
JS
JAVASCRIPT LECTURES
First semester
Stage:4
Time: Morning
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.
<button type="button"
onclick='document.getElementById("demo").
innerHTML = "Hello JavaScript!"'>Click Me!</button>
</body>
</html>
JavaScript Can Change HTML Styles (CSS)
document.getElementById("demo").style.fontSize = "35px";
<html>
<head><title>wellcome</title></head>
<body>
<h2>What Can JavaScript Do?</h2>
<button type="button"
onclick='document.getElementById("demo").style.fontSize="35px"'>
Click Me!
</button>
</body>
</html>
JavaScript Can Hide HTML Elements
document.getElementById("demo").style.display = "no
ne";
<html>
<head><title>wellcome</title></head>
<body>
<button type="button"
onclick=‘document.getElementById('demo').style.display=‘’none'">
Click Me!</button>
</body>
</html>
JavaScript Can Show HTML Elements
document.getElementById("demo").style.display = "block";
<html>
<head><title>wellcome</title></head>
<body>
<button type="button"
onclick='document.getElementById('demo').style.display='block'">Click
Me!</button>
</body>
</html>
JavaScript Output
<p id="demo">hello</p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using document.write()
</body>
</html>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
<html>
<body>
<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>
</body>
</html>
JavaScript Comments
<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
<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>
</body>
</html>
JavaScript 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
JavaScript uses the keywords var, let and const to declare variables.
<h2>JavaScript Variables</h2>
<p id="demo"></p>
<script>
let x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>
</body>
JavaScript Operators
<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
<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.
var x, y;
x = 5 + 6;
y = x * 10;
<body>
<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
<body>
<h3>The ++ Operator</h3>
<script>
let x = 5;
x++;
let z = x;
document.write(z);
</script>
</body>
Decrementing
let x = 5;
x--;
let z = x;
Exponentiation
Example
let x = 5;
let z = x ** 2;
// result is 25
JavaScript Assignment Operators
= 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
<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
{
// 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
<p id="demo"></p>
<script>
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = text.length;
</script>
</body>
</html>
Extracting String Parts
<script>
let str = "Apple,Banana,Kiwi";
document.getElementById("demo").innerHTML = str.slice(6,12);
</script>
</body>
</html>
The substr() Method
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?
<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
<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>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.join(" * "));
</script>
</body>
</html>
Popping and Pushing
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
<h2>JavaScript Comparison</h2>
<script>
let x = 5;
document.write(x == 8);
</script>
</body>
</html>
Logical Operators
|| or (x == 5 || y == 5) is false
<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
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>
<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
<script>
let x = false;
document.write(
"Number : " + Number(x) + "<br>" +
"String : " + String(x) + "<br>" +
"Boolean: " + Boolean(x)
);
</script>
</body>
</html>
Result
<html>
<body>
<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:
Example
Make a "Good day" greeting if the hour is less than 18:00:
<html>
<body>
<h2>JavaScript if</h2>
<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>
</body>
</html>
The else Statement
<script>
const hour = new Date().getHours();
let greeting;
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
<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.
<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
<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
<script>
let text = " ";
document.write(text);
</script>
</body>
</html>
JavaScript While Loop
while (condition) {
// code block to be executed
}
Example
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};
document.write(text);
</script>
</body>
</html>
Result
J
a
v
a
S
c
r
i
p
t
JavaScript Break and Continue
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