JavaScript Basics and Applications Guide
JavaScript Basics and Applications Guide
Outline:
Introduction to JavaScript If statements, switch case
Position of JavaScript in
HTML document
JavaScript Output
Data types
Variables
Operators
Introduction to JavaScript
JavaScript is a scripting language which is used to
enhance the functionality and appearance of web pages.
JavaScript is a dynamic computer programming
language.
It is lightweight and most commonly used as a part of
web pages, whose implementations allow client-side
script to interact with the user and make dynamic
pages.
It is an interpreted programming language with
object-oriented capabilities.
Advantages of JavaScript
Script result
JS First Program
Often, JavaScript appear in the <head> section of the HTML document
The browser interprets the contents of the <head> section first
In HTML, the JavaScript code is inserted between <script> and
</script> tags.
A string of characters can be contained between double quotation (") marks
(also called a string literal)
JavaScript is a case-sensitive language.
It is a good programming practice to use semicolons.
Comments
<script language = "javascript" type = "text/javascript">
<!--
// This is a comment. It is similar to comments in java
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in java
*/
//-->
</script>
<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>
<p>JavaScript can change the content of an HTML element:</p>
<button type="button" Me!</button>
<p id="demo">This is a demonstration.</p>
<script>
function myFunction() {
[Link]("demo").innerHTML = "Hello JavaScript!";
}
</script>
</body>
</html>
JS and HTML Content
What JavaScript can do:
JS can change HTML attributes :
<html>
<body>
<h1>My First JavaScript</h1>
<p>Here, a JavaScript changes the value of the src (source) attribute of an image.</p>
<script>
function light(sw) {
var pic;
if (sw == 0) {
pic = "[Link]"
} else {
pic = "[Link]"
}
[Link]('myImage').src = pic;
}
</script>
<img id="myImage" src="[Link]" width="100" height="180">
<p>
<button type="button" > <button type="button" > </p>
</body>
</html>
JS and HTML Content
What JavaScript can do:
JS can change styles :
<html>
<body>
<h1>My First JavaScript</h1>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<script>
function myFunction() {
[Link]("demo").[Link] = "25px";
[Link]("demo").[Link] = "red";
[Link]("demo").[Link] = "yellow";
}
</script>
<button type="button" Me!</button>
</body>
</html>
JS and HTML Content
What JavaScript can do:
JS can writes into an HTML element with id:
<!DOCTYPE html>
<html>
<body>
<h2>Use JavaScript to Change Text</h2>
<p>This example writes "Hello JavaScript!" into an HTML element with id="demo":</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
</html>
JS and HTML Content
What JavaScript can do:
JS can defines an alternate content to be displayed to users that
have disabled scripts in their browser or have a browser that doesn't
support scripts :
<html>
<body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello JavaScript!";
</script>
<noscript>
Sorry, your browser does not support JavaScript!
</noscript>
<p>A browser without support for JavaScript will show
the text written inside the noscript element.</p>
</body>
</html>
JS and HTML Content
What JavaScript can do:
JS Can Show HTML Elements:
<!DOCTYPE html>
<html>
<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" Me!
</button>
</body>
</html>
JavaScript Output
JavaScript Display Possibilities
And use the innerHTML property to change the inner text of the HTML
element:
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "<h2>Hello World</h2>";
</script>
</body>
</html>
JavaScript Output
Using innerText
To access an HTML element, use the [Link](id) method.
Then use the innerText property to change the inner text of the HTML
element:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
[Link]("demo").innerText = "Hello World";
</script>
</body>
</html>
JavaScript Output
Using [Link]()
For testing purposes, it is convenient to use [Link]():
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
Using [Link]() after an HTML document is loaded, will delete all
existing HTML:
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<button type="button" + 6)">Try it</button>
</body>
</html>
JavaScript Output
Using [Link]()
We can use an alert box to display data:
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
[Link](5 + 6);
</script>
</body>
</html>
JavaScript Output
JavaScript Print
JS does not have any print object or print methods.
The only exception is that we can call the [Link]() method in the
browser to print the content of the current window.
<!DOCTYPE html>
<html>
<body>
<h2>The [Link]() Method</h2>
<p>Click the button to print the current page.</p>
<button this page</button>
</body>
</html>
Data types
JavaScript has the following Data types:
String let color = "Yellow";
Number let length = 16;
Bigint let x = BigInt("123456789012345678901234567890");
Boolean let x = true;
Undefined let car;
Null let car=“”
Object const person = {firstName:“Ali", lastName:“Gad"};
Data types
The Concept of Data Types:
let x = 16 + "Volvo"; ≡ let x = "16" + "Volvo";
let x = "Volvo" + 16 ; ≡ let x = "Volvo" + "16" ;
let x = 16 + 4 + "Volvo"; ≡ let x = 20 + "Volvo" ;
let x = "Volvo" + 16 + 4; ≡ let x = "Volvo" + “16” + “4” ;
// With decimals:
let x1 = 34.00;
// Without decimals:
let x2 = 34;
Variables declared inside a { } block cannot be accessed from outside the block:
{
let x = 2;
}
// x can NOT be used here
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Variables
JavaScript var
Variables declared with the var always have Global Scope.
Variables declared inside a { } block cannot be accessed from outside the block:
{
var x = 2;
}
// x can be used here
<html>
<body>
<h1>JavaScript Operators</h1>
<h2>The delete Operator</h2>
<p>The delete operator deletes a property from an object:</p>
<p id="demo"></p>
<script>
const person = {
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};
delete [Link];
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>
</body>
</html>
Operators
JavaScript supports the following types of operators.
Arithmetic Operators
Assignment Operators
Comparison Operators
String Operators
Logical Operators
Bitwise Operators
Ternary Operators
Type Operators
Operators
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
Operators
Assignment Operators
!= not equal
Operator Description
== equal to
!= not equal
? ternary operator
Operators
Logical Operators
Operator Description
Logical AND
&& If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
Logical OR
|| If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
Logical NOT
Reverses the logical state of its operand. If a condition is true, then the Logical
! NOT operator will make it false.
Ex:! (A && B) is false.
Operators
Bitwise Operators
Syntax:
Example:
function getFee(isMember) {
return isMember ? "$2.00" : "$10.00";
}
[Link](getFee(true)); // Expected output: "$2.00“
[Link](getFee(false)); // Expected output:"$10.00“
[Link](getFee(null)); // Expected output: "$10.00"
Operators
Ternary Operators Conditional chains
The ternary operator is right-associative, which means it can be "chained" in
the following way, similar to an if … else if … else if … else chain:
Syntax:
function example() {
if (condition1) {
return value1;
function example() { } else if (condition2) {
return condition1 ? value1 return value2;
: condition2 ? value2
: condition3 ? value3
: value4;
≡ } else if (condition3) {
return value3;
} } else {
return value4;
}
}
Operators
Ternary Operators Conditional chains
The ternary operator is right-associative, which means it can be "chained" in
the following way, similar to an if … else if … else if … else chain:
Example:
<html>
<body>
<script type="text/javascript">
var age = 26;
var beverage = (age >= 21) ? "Beer" : "Juice";
[Link](beverage);
</script>
</body>
</html>
The following flow chart shows how the if-else statement works.
if statement
if...else statement
let count = 1;
let number = 1;
do {
[Link]("Number is:", number);
number++;
} while (number <= 3);
Loops
Do-while Loop
Functions
A JavaScript function is a block of code designed to perform a
particular task. It is reusable code which can be called anywhere in
your program. This eliminates the need of writing the same code again
and again.
You have seen functions like alert() and write() in the earlier part.
Example:
Property Description
closed Returns a boolean true if a window is closed.
console Returns the Console Object for the window.
See also The Console Object.
document Returns the Document object for the window.
See also The Document Object.
Window
Window Object Methods
Property Description Example
addEventListener() Attaches an event handler to [Link](event, function)
the window
alert() Displays an alert box with a alert("Hello! I am an alert box!!");
message and an OK button
confirm() Displays a dialog box with a confirm("Press a button!");
message and an OK and a Cancel
button
console() [Link]("You made a mistake");
print() Prints the content of the <button this
current window page</button>
prompt() Displays a dialog box that let stdName= prompt("What's yourname?", “ali");
prompts the visitor for input
stop() Stops the window from loading [Link]();
resizeBy() Resizes the window by the
specified pixels
resizeTo() Resizes the window to the
specified width and height
Window
Prompt method <html>
<body>
Example: <h1>The Window Object</h1>
<h2>The prompt() Method</h2>
<p>Click the button to ask for your favorite drink.</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text;
let favDrink = prompt("What's your favorite drink?", "Coca-Cola");
switch(favDrink) {
case "Coca-Cola":
text = "Excellent choice. Coca-Cola is good for your soul.";
break;
case "Pepsi":
text = "Pepsi is my favorite too!";
break;
case "Sprite":
text = "Really? Are you sure the Sprite is your favorite?";
break;
default:
text = "I have never heard of that one..";
}
[Link]("demo").innerHTML = text;
}
</script>
</body>
</html>
Events
The structure of an HTML document as a tree-like structure, allowing
developers to access, manipulate, and update the elements, attributes, and
content of the document dynamically.
HTML allows JavaScript to react to HTML events by any element in the tree:
Events
A JavaScript can be executed when an event occurs, like when a user clicks
on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an
HTML event attribute: > <html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
<h2 on this text!</h2>
</body>
</html>
Examples of HTML events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
When a user strokes a key
Events
Mouse Events:
Window Events
Simple Syntax:
[Link](event, function)
Example:
[Link]("click", myFunction);
function myFunction() {
[Link]("demo").innerHTML = "Hello World";
}
Document addEventListener()
<html>
<body>
<h1>The Document Object</h1>
<h2>The addEventListener() Method</h2>
<p>This example adds many events on the document.</p>
<p id="demo"></p>
<script>
[Link]("mouseover", myFunction);
[Link]("click", mySecondFunction);
[Link]("mouseout", myThirdFunction);
function myFunction() {
[Link]("demo").innerHTML = "Moused over!"
}
function mySecondFunction() {
[Link]("demo").innerHTML = "Clicked!<br>"
}
function myThirdFunction() {
[Link]("demo").innerHTML = "Moused out!<br>"
}
</script>
</body>
</html>
Element addEventListener()
Add a click event to the document:
Simple Syntax:
[Link](event, function)
Example:
[Link]("click", myFunction);
function myFunction() {
[Link]("demo").innerHTML = "Hello World";
}
[Link]("click", myFunction() {
[Link]("demo").innerHTML = "Hello World";
}
Element addEventListener()
Example: add many events on the same element (button).
<html>
<body>
<h1>The Element Object</h1>
<p>Attach a click event to a button:</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
const element = [Link]("myBtn");
[Link]("mouseover", myFunction);
[Link]("click", mySecondFunction);
[Link]("mouseout", myThirdFunction);
function myFunction() {
[Link]("demo").innerHTML = "Moused over!"}
function mySecondFunction() {
[Link]("demo").innerHTML = "Clicked!<br>"}
function myThirdFunction() {
[Link]("demo").innerHTML = "Moused out!<br>"}
</script>
</body>
</html>
Element addEventListener()
Example: add many events on the same element (button).
<html>
<body>
<h1>The Element Object</h1>
<p>Attach a click event to a button:</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
const element = [Link]("myBtn");
[Link]("mouseover",
function(){[Link]("demo").innerHTML = "Moused over!";});
[Link]("click",
function(){[Link]("demo").innerHTML = "Clicked!<br>";})
[Link]("mouseout",
function(){[Link]("demo").innerHTML = "Moused out!<br>";})
</script>
</body>
</html>
Quiz
Create HTML file that display counter (press +/- button increment/decrement counter)
<html >
<head> </style>
<title>Counter</title> </head>
<style> <body>
body{ <section id="counter">
font-family: sans-serif; <div>
background-color: black; <h1 id="counterDisplay">0</h1>
} <div id="counterControls">
#counter { <button id="counterAdd">+</button>
display: flex; <button id="counterSub">-</button>
width: 100%; </div>
justify-content: center; </div>
} </section>
#counterDisplay { <script>
font-size: 4 rem; var total=0
text-align: center; const element =
color: white; [Link]("counterAdd");
} [Link]("click",
#counter button {
border: 0; function(){[Link]("counterDisplay").inne
padding: 0.5rem 1rem; rHTML = total++;});
font-size: 2rem; const element1 =
cursor: pointer; [Link]("counterSub");
} [Link]("click",
#counterAdd {
background-color: green; function(){[Link]("counterDisplay").inne
} rHTML = --total;});
#counterSub { </script>
background-color:brown; </body>
} </html> [Link]
Quiz
Build a working calculator that can do addition, subtraction, multiplication, and division
between two numbers.
Quiz
Build a working calculator that can do addition, subtraction, multiplication, and division
between two numbers.
<html>
<head>
<title>Simple Calculator</title>
<style>
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.calculator {
background-color: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
text-align: center;
width: 300px;
}
input[type="number"] {
width: 80%;
padding: 8px;
margin: 10px 0;
font-size: 16px;
}
Quiz
Build a working calculator that can do addition, subtraction, multiplication, and division
between two numbers.
select, button {
padding: 10px;
margin-top: 10px;
font-size: 16px;
width: 85%;
}
#result {
margin-top: 20px;
font-size: 18px;
color: #333;
font-weight: bold;
}
</style>
</head>
<body>
<div class="calculator">
<h2>Simple Calculator</h2>
<input type="number" id="num1" placeholder="Enter first number"><br>
<input type="number" id="num2" placeholder="Enter second number"><br>
<select id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br>
<button > Quiz
Build a working calculator that can do addition, subtraction, multiplication, and division
between two numbers.
<div id="result"></div>
</div>
<script>
function calculate() {
const num1 = parseFloat([Link]("num1").value);
const num2 = parseFloat([Link]("num2").value);
const operator = [Link]("operator").value;
const resultDisplay = [Link]("result");
if (isNaN(num1) || isNaN(num2)) {
[Link] = "Please enter valid numbers.";
[Link] = "red";
return;
}
let result;
if (operator === "/" && num2 === 0) {
[Link] = "Cannot divide by zero";
[Link] = "red";
return;
}
Quiz
Build a working calculator that can do addition, subtraction, multiplication, and division
between two numbers.
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
[Link] = "Result: " + result;
[Link] = "#333";
}
</script>
</body>
</html>
JavaScript Global Methods and Properties
The JavaScript global properties and methods can be used with all
JavaScript objects.
Since these methods are global, and global the object is the browser window,
these methods are actually window methods:
isNaN() is the same as [Link]().
Name Description
Infinity A numeric value that represents positive/negative infinity
isFinite() Determines whether a value is a finite, legal number
isNaN() Determines whether a value is an illegal number
NaN "Not-a-Number" value
Number() Converts an object's value to a number
parseFloat() Parses a string and returns a floating point number
parseInt() Parses a string and returns an integer