Javascript
Javascript
JAVASCRIPT
WT - Kirti Sharma
- JavaScript is the world's most popular programming language.
- JavaScript is the programming language of the Web.
- JavaScript is easy to learn.
Why Study 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
WT - Kirti Sharma
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":
<!DOCTYPE html>
<html> JavaScript accepts both
<body> double and single quotes:
<button type="button"
onclick='document.getElementById("demo").innerHTML =
"Hello JavaScript!"'>Click Me!</button>
</body>
</html>
WT - Kirti Sharma
JavaScript Can Change HTML Attribute Values
In this example JavaScript changes the value of the src (source) attribute of an <img> tag:
<!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>
</body>
</html>
WT - Kirti Sharma
JavaScript Can Change HTML Styles (CSS)
Changing the style of an HTML element, is a variant of changing an HTML attribute:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
WT - Kirti Sharma
JavaScript Can Hide HTML Elements
Hiding HTML elements can be done by changing the display style:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
WT - Kirti Sharma
JavaScript Can Show HTML Elements
Showing hidden HTML elements can also be done by changing the display style:
<!DOCTYPE html>
<!DOCTYPE html> <html>
<html> <body>
<body>
<h2>What Can JavaScript Do?</h2>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can show hidden HTML elements.</p>
<p>JavaScript can show hidden HTML elements.</p>
<p id="demo" style="display:block">Hello
<p id="demo" style="display:none">Hello JavaScript!</p> JavaScript!</p>
<p id="test" style="display:none">this is hidden!</p>
<button type="button"
onclick="document.getElementById('demo').style.display <button type="button"
='block'">Click Me!</button> onclick="document.getElementById('demo').style.displa
y='none';
</body>
</html> document.getElementById('test').style.display='block'">
Click Me!</button>
</body>
</html>
WT - Kirti Sharma
The <script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags.
JavaScript in <head> or <body>
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.
JavaScript Functions and Events
A JavaScript function is a block of JavaScript code, that can be executed when "called" for.
For example, a function can be called when an event occurs, like when the user clicks a button.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
<!DOCTYPE html> <!DOCTYPE html>
<html>
<html> <head>
<body> <script>
<h2>JavaScript in Body</h2> function myFunction() {
<p id="demo"></p> document.getElementById("demo").innerHTML = "Paragraph changed.";
}
<script> </script></head>
document.getElementById("demo").innerHTML = <body>
"My First JavaScript"; <h2>Demo JavaScript in Head</h2>
<p id="demo">A Paragraph.</p>
</script> <button type="button" onclick="myFunction()">Try it</button>
</body></html> </body></html>
WT - Kirti Sharma
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:
<!DOCTYPE html>
<html>
<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script></body></html>
WT - Kirti Sharma
External JavaScript
Scripts can also be placed in external files:
By FILE PATH
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body></html>
WT - Kirti Sharma
Using document.write()
For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
<html> Using document.write() after an HTML
<body>
document is loaded, will delete all
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
existing HTML:
<p>Never call document.write after the document has finished
loading.
It will overwrite the whole document.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 + 6)">Try
it</button>
</body>
</html>
WT - Kirti Sharma
Using window.alert()
You can use an alert box to display data:
<!DOCTYPE html>
<html> You can skip the window keyword.
<body> In JavaScript, the window object is the global scope
<h2>My First Web Page</h2> object, that means that variables, properties, and
<p>My first paragraph.</p> methods by default belong to the window object. This
<script> also means that specifying the window keyword is
window.alert(5 + 6); optional:
</script>
</body>
<!DOCTYPE html>
</html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script>
alert(5 + 6);
</script>
</body>
</html>
WT - Kirti Sharma
Using console.log()
For debugging purposes, you can call the console.log() method in the browser to display data.
<!DOCTYPE html>
<html>
<body> JavaScript Print
<h2>Activate Debugging</h2> - JavaScript does not have any print object or print
<p>F12 on your keyboard will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p> methods.
<p>Then click Run again.</p> - You cannot access output devices from JavaScript.
<script> - The only exception is that you can call
console.log(5 + 6);
</script>
the window.print() method in the browser to print the
</body> content of the current window.
</html>
<!DOCTYPE html>
<html>
<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>
WT - Kirti Sharma
JavaScript Statements
JavaScript statements are composed of:
- Values, Operators, Expressions, Keywords, and Comments.
- This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":
- Most JavaScript programs contain many JavaScript statements.
- The statements are executed, one by one, in the same order as they are written.
- JavaScript programs (and JavaScript statements) are often called JavaScript code.
<!DOCTYPE html>
<html> <!DOCTYPE html>
<body> <html>
<h2>JavaScript Statements</h2> <body>
<p>In HTML, JavaScript statements are executed by the browser.</p>
<p id="demo"></p> <h2>JavaScript Statements</h2>
<script> <p>Multiple statements on one line are allowed.</p>
document.getElementById("demo").innerHTML = "Hello Dolly."; <p id="demo1"></p>
</script>
</body>
<script>
</html> let a, b, c;
a = 5; b = 6; c = a + b;
Semicolons ; document.getElementById("demo1").innerHTML = c;
Semicolons separate JavaScript statements. </script></body></html>
Add a semicolon at the end of each
executable statement. When separated by
semicolons, multiple statements on one line
are allowed. WT - Kirti Sharma
JavaScript White Space
JavaScript ignores multiple spaces. You can <!DOCTYPE html>
add white space to your script to make it more <html>
readable. A good practice is to put spaces <body>
around operators ( = + - * / ) <h2>JavaScript Statements</h2>
<p>JavaScript code blocks are written between { and }</p>
JavaScript Code Blocks <button type="button" onclick="myFunction()">Click
- JavaScript statements can be grouped Me!</button>
together in code blocks, inside curly brackets <p id = "demo1"></p>
{...}. <p id="demo2"></p>
- The purpose of code blocks is to define <script>
statements to be executed together. function myFunction() {
- One place you will find statements grouped document.getElementById("demo1").innerHTML =
together in blocks, is in JavaScript functions. "Hello Dolly!";
document.getElementById("demo2").innerHTML =
"How are you?";
}
</script>
</body>
</html>
WT - Kirti Sharma
WT - Kirti Sharma
JAVASCRIPT SYNTAX JavaScript Literals
The two most important syntax rules for fixed
values are:
1. Numbers are written with or without
decimals.
2. Strings are text, written within double or
single quotes.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Numbers</h2>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Expressions</h2>
<p>Expressions compute to values.</p>
<p id="demo"></p>
<p id='test'></p>
<p id='test1'></p>
<script>
document.getElementById("demo").innerHTML = 5 * 10;
var x;
x = 5;
document.getElementById("test").innerHTML = x * 10;
document.getElementById("test1").innerHTML = "John" + " " + "Doe";
</script>
</body>
</html>
WT - Kirti Sharma
JavaScript Keywords
- JavaScript keywords are used to identify actions to be performed.
- The let keyword tells the browser to create variables.
- The var keyword tells the browser to create variables.
<h2>The <b>let</b> Keyword Creates Variables</h2> <h2>The var Keyword Creates Variables</h2>
<script> <script>
let x, y; var x, y;
x = 5 + 6; x = 5 + 6;
y = x * 10; y = x * 10;
document.getElementById("demo").innerHTML = y; document.getElementById("demo").innerHTML = y;
</script> </script>
</body> </body>
</html> </html>
WT - Kirti Sharma
JavaScript Comments
Not all JavaScript statements are "executed". JavaScript is Case Sensitive
Code after double slashes // or All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different
between /* and */ is treated as a comment.
variables:
Comments are ignored, and will not be
executed:
JavaScript Identifiers / Names Rules:
<!DOCTYPE html> Identifiers are JavaScript names.
<html> Identifiers are used to name variables and
<body> keywords, and functions.
The rules for legal names are the same in most
<h2>JavaScript Comments are NOT Executed</h2> programming languages.
A JavaScript name must begin with:
<p id="demo"></p> •A letter (A-Z or a-z)
•A dollar sign ($)
<script> •Or an underscore (_)
let x; Subsequent characters may be letters, digits,
x = 5; underscores, or dollar signs.
// x = 6; I will not be executed Numbers are not allowed as the first character in
document.getElementById("demo").innerHTML = x; names.
</script>
</body>
</html> WT - Kirti Sharma
JavaScript and Camel Case
Historically, programmers have used different ways of joining multiple words into one variable
name:
Hyphens:
first-name, last-name, master-card, inter-city.
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore:
first_name, last_name, master_card, inter_city.
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
JavaScript programmers tend to use camel case that starts with a lowercase letter:
firstName, lastName, masterCard, interCity.
WT - Kirti Sharma
JavaScript Variables
4 Ways to Declare a JavaScript Variable:
•Using var
•Using let
•Using const
•Using nothing
What are Variables?
- Variables are containers for storing data (storing
data values).
WT - Kirti Sharma
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<h1>JavaScript Variables</h1> <h2>JavaScript Variables</h2>
<p>In this example, x, y, and z are variables.</p> <p>In this example, x, y, and z are variables.</p>
<p id="demo"></p> <p id="demo"></p>
<script> <script>
var x = 5; let x = 5;
var y = 6; let y = 6;
var z = x + y; let z = x + y;
document.getElementById("demo").innerHTML ="The document.getElementById("demo").innerHTML =
value of z is: " + z; "The value of z is: " + z;
</script></body></html> </script></body></html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>In this example, price, price2, and total are
variables.</p>
<p id="demo"></p>
<script>
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
document.getElementById("demo").innerHTML =
"The total is: " + total;
WT - Kirti Sharma
</script></body></html>
JavaScript Identifiers
WT - Kirti Sharma
JavaScript Data Types
- JavaScript variables can hold numbers like 100 and text values like "John Doe".
- In programming, text values are called text strings.
- JavaScript can handle many types of data, but for now, just think of numbers and strings.
- Strings are written inside double or single quotes. Numbers are written without quotes.
- If you put a number in quotes, it will be treated as a text string.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>Strings are written with quotes.</p>
<p>Numbers are written without quotes.</p>
<p id="demo"></p>
<script>
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';
document.getElementById("demo").innerHTML =
pi + "<br>" + person + "<br>" + answer;
</script></body></html>
WT - Kirti Sharma
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1> <!DOCTYPE html>
<p>Create a variable, assign a value to it, and display it:</p> <html>
<p id="demo"></p> <body>
<script> <h1>JavaScript Variables</h1>
let carName = "Volvo"; <p>A variable without a value has the value of:</p>
document.getElementById("demo").innerHTML = carName; <p id="demo"></p>
</script> <script>
</body> let carName;
</html> document.getElementById("demo").innerHTML =
carName;
One Statement, Many Variables </script></body></html>
You can declare many variables in one statement.
Start the statement with var and separate the variables by comma.
Value = undefined
In computer programs, variables are often declared without a value. The
value can be something that has to be calculated, or something that will be
provided later, like user input.
A variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of
this statement: WT - Kirti Sharma
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable declared with var, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of these statements:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>If you re-declare a JavaScript variable, it will not lose its
value.</p>
<p id="demo"></p>
<script>
var carName = "Volvo";
var carName;
document.getElementById("demo").innerHTML = carName;
</script></body></html>
WT - Kirti Sharma
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +.
You can also add strings, but strings will be concatenated.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>The result of adding "5" + 2 + 3 is:</p>
<p id="demo"></p>
<p id="test"></p>
<p id="test1"></p>
<p id="test2"></p>
<script>
let x = "5" + 2 + 3;
let y = 5 + 2 + 3;
let z = "John" + " " + "Doe";
let a = 2 + 3 + "5";
document.getElementById("demo").innerHTML = x;
document.getElementById("test").innerHTML = y;
document.getElementById("test1").innerHTML = z;
document.getElementById("test2").innerHTML = a;
</script></body></html> WT - Kirti Sharma
JavaScript Dollar Sign $
Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names.
Using the dollar sign is not very common in JavaScript, but professional programmers often use it
as an alias for the main function in a JavaScript library.
In the JavaScript library jQuery, for instance, the main function $ is used to select HTML elements.
In jQuery $("p"); means "select all p elements".
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>The dollar sign is treated as a letter in JavaScript
names.</p>
<p id="demo"></p>
<script>
let $$$ = 2;
let $myMoney = 5;
document.getElementById("demo").innerHTML = $$$ +
$myMoney;
</script>
</body>
</html>
WT - Kirti Sharma
JavaScript let
WT - Kirti Sharma
Block Scope
- JavaScript had only Global Scope and Function Scope.
- two important new JavaScript keywords: let and const.
- These two keywords provide Block Scope in JavaScript.
- Variables declared inside a { } block cannot be accessed from outside the block.
WT - Kirti Sharma
WT - Kirti Sharma
WT - Kirti Sharma
JavaScript const
Variables defined with const cannot be
Redeclared.
Variables defined with const cannot be
Reassigned.
Variables defined with const have Block Scope.
Cannot be Reassigned
A const variable cannot be reassigned:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript const</h2>
<p id="demo"></p>
When to use JavaScript const?
<script>
As a general rule, always declare a variable
try { with const unless you know that the value will change.
const PI = 3.141592653589793; Use const when you declare:
PI = 3.14; •A new Array
} •A new Object
catch (err) { •A new Function
document.getElementById("demo").innerHTML = err; •A new RegExp
}
</script></body></html> WT - Kirti Sharma
Constant Objects and Arrays
The keyword const is a little misleading.
It does not define a constant value. It defines a constant reference to a value.
Because of this you can NOT:
•Reassign a constant value <!DOCTYPE html>
•Reassign a constant array <html>
•Reassign a constant object <body>
But you CAN: <h2>JavaScript const</h2>
•Change the elements of constant array <p>Declaring a constant array does NOT make the elements
•Change the properties of constant object unchangeble:</p>
<p id="demo"></p>
<script>
// Create an Array:
Constant Arrays const cars = [“Celerio", "Volvo", "BMW"];
You can change the elements of a constant array. // Change an element:
cars[0] = "Toyota";
// Add an element:
cars.push("Audi");
// Display the Array:
document.getElementById("demo").innerHTML = cars;
</script></body></html>
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body> But you can NOT reassign the array.
<h2>JavaScript const</h2>
<p>You can NOT reassign a constant array:</p>
<p id="demo"></p>
<script>
try {
const cars = [“Celerio", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"];
}
catch (err) {
document.getElementById("demo").innerHTML = err;
}
</script></body></html>
WT - Kirti Sharma
Constant Objects But you can NOT reassign the
You can change the properties of a constant object:
object:
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<h2>JavaScript const</h2> <h2>JavaScript const</h2>
<p>Declaring a constant object does NOT make the objects <p>You can NOT reassign a constant object:</p>
properties unchangeable:</p>
<p id="demo"></p>
<p id="demo"></p> <script>
<script> try {
// Create an object: const car = {type:"Fiat", model:"500", color:"white"};
const car = {type:"Fiat", model:"500", color:"white"}; car = {type:"Volvo", model:"EX60", color:"red"};
// Change a property: }
car.color = "red"; catch (err) {
// Add a property: document.getElementById("demo").innerHTML = err;
car.owner = "Johnson"; }
// Display the property: </script></body></html>
document.getElementById("demo").innerHTML = "Car
owner is " + car.owner;
</script></body></html>
WT - Kirti Sharma
Block Scope
Declaring a variable with const is similar
to let when it comes to Block Scope.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
document.getElementById("demo").innerHTML = "x is " +
x;
</script></body></html>
WT - Kirti Sharma
WT - Kirti Sharma
DIY
WT - Kirti Sharma
DIY
WT - Kirti Sharma
DIY
WT - Kirti Sharma
DIY
WT - Kirti Sharma
JavaScript Data Types
WT - Kirti Sharma
JavaScript Types are Dynamic JavaScript Strings
JavaScript has dynamic types. This means that - A string (or a text string) is a series of characters
the same variable can be used to hold different like "John Doe".
data types: - Strings are written with quotes. You can use
single or double quotes
<!DOCTYPE html> - You can use quotes inside a string, as long as
<html> they don't match the quotes surrounding the
<body> string.
<h2>JavaScript Data Types</h2>
<p>JavaScript has dynamic types. This means that the JavaScript Numbers
same variable can be used to hold different data - JavaScript has only one type of numbers.
types:</p> - Numbers can be written with, or without
<p id="demo"></p> decimals.
<script> - Extra large or extra small numbers can be
let x; // Now x is undefined written with scientific (exponential) notation.
x = 5; // Now x is a Number
x = "John"; // Now x is a String
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
WT - Kirti Sharma
JavaScript Booleans
- Booleans can only have two
values: true or false.
- Booleans are often used in conditional <!DOCTYPE html>
testing. <html>
<body>
<h2>JavaScript Arrays</h2>
<p>Array indexes are zero-based, which means the first item is
[0].</p>
<p id="demo"></p>
JavaScript Arrays
<script>
JavaScript arrays are written with square
const cars = [“Celerio","Volvo","BMW"];
brackets.
document.getElementById("demo").innerHTML = cars[0];
Array items are separated by commas.
</script>
Array indexes are zero-based, which means
</body>
the first item is [0], second is [1], and so
</html>
on.
WT - Kirti Sharma
JavaScript Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by commas.
The object (person) in the example has 4 properties: firstName, lastName, age, and eyeColor.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
const person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
WT - Kirti Sharma
The typeof Operator
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.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript typeof</h2>
<p>The typeof operator returns the type of a variable or an expression.</p>
<p id="demo"></p>
<p id="test"></p>
<script>
document.getElementById("demo").innerHTML =
typeof 0 + "<br>" +
typeof 314 + "<br>" +
typeof 3.14 + "<br>" +
typeof (3) + "<br>" +
typeof (3 + 4);
document.getElementById("test").innerHTML =
typeof "" + "<br>" +
typeof "John" + "<br>" +
typeof "John Doe";
</script></body></html>
WT - Kirti Sharma
Undefined Empty Values
In JavaScript, a variable without a value, has An empty value has nothing to do with undefined.
the value undefined. The type is An empty string has both a legal value and a type.
also undefined.
<!DOCTYPE html>
<!DOCTYPE html> <html>
<html> <body>
<body>
<h2>JavaScript</h2>
<h2>JavaScript</h2> <p>An empty string has both a legal value and a type:</p>
<p>Variables can be emptied if you set the value to <p id="demo"></p>
<b>undefined</b>.</p> <script>
<p id="demo"></p> let car = "";
<script> document.getElementById("demo").innerHTML =
let car ; "The value is: " +
document.getElementById("demo").innerHTML = car car + "<br>" +
+ "<br>" + typeof car; "The type is: " + typeof car;
</script> </script>
</body> </body>
</html> </html>
WT - Kirti Sharma
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).
WT - Kirti Sharma
Function Invocation
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
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the
invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller“.
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.
Returning a value
WT - Kirti Sharma
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<html>
<body>
<body>
<h2>JavaScript Functions</h2>
<h2>JavaScript Functions</h2>
<p>This example calls a function to convert from
<p>Accessing a function without () will return the function
Fahrenheit to Celsius:</p>
definition instead of the function result:</p>
<p id="demo"></p>
<p id="demo"></p>
<script>
<script>
function toCelsius(f) {
function toCelsius(f) {
return (5/9) * (f-32);
return (5/9) * (f-32);
}
}
document.getElementById("demo").innerHTML =
document.getElementById("demo").innerHTML = toCelsius;
toCelsius(77);
</script></body></html>
</script></body></html>
WT - Kirti Sharma
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<h2>JavaScript Functions</h2>
<p id="demo"></p> <h2>JavaScript Functions</h2>
<script> <p>Outside myFunction() carName is undefined.</p>
document.getElementById("demo").innerHTML = <p id="demo1"></p>
"The temperature is " + toCelsius(77) + " Celsius"; <p id="demo2"></p>
function toCelsius(fahrenheit) { <script>
return (5/9) * (fahrenheit-32); myFunction();
} function myFunction() {
</script></body></html> let carName = "Volvo";
document.getElementById("demo1").innerHTML =
typeof carName + " " + carName;
Since local variables are only recognized }
inside their functions, variables with the document.getElementById("demo2").innerHTML =
same name can be used in different typeof carName;
functions. </script></body></html>
Local variables are created when a
function starts, and deleted when the
function is completed.
WT - Kirti Sharma
JavaScript Objects
Objects are variables too. But objects can contain many values.
The values are written as name:value pairs (name and value separated by a
colon).
It is a common practice to declare objects with the const keyword.
WT - Kirti Sharma
Object Definition
You define (and create) a JavaScript object with an object literal.
Spaces and line breaks are not important. An object definition can span multiple lines.
JavaScript objects are containers for named values called properties.
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>There are two different ways to access an object property.</p>
<p>You can use person.property or person["property"].</p>
<p id="demo"></p>
<p id="text"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566
};
// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
document.getElementById("text").innerHTML =
person["firstName"] + " " + person["lastName"];
</script></body></html>
WT - Kirti Sharma
A method is a function stored as a property.
WT - Kirti Sharma
this is not a variable. It is a keyword. You
cannot change the value of this.
The this Keyword
In a function definition, this refers to the "owner" of the function.
In the example above, this is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored as a
property value.</p>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML =
person.fullName();
</script></body></html>
WT - Kirti Sharma
If you access a method without the <!DOCTYPE html>
() parentheses, it will return <html>
the function definition: <body>
<h2>JavaScript Objects</h2>
<p>If you access an object method without (), it will return
the function definition:</p>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML =
person.fullName;
</script></body></html>
WT - Kirti Sharma
WT - Kirti Sharma
JavaScript Events
HTML 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.
WT - Kirti Sharma
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<html>
<body>
<body>
<button
<h2>JavaScript HTML Events</h2>
onclick="document.getElementById('demo').innerHTML=Date
<button onclick="this.innerHTML=Date()">The time is?
()">The time is?</button>
</button>
<p id="demo"></p>
</body>
</body>
</html>
</html>
In the above example, the code
In the example above, the JavaScript code changes the content of its own
changes the content of the element with element (using this.innerHTML):
id="demo".
<!DOCTYPE html>
<html><body>
<h2>JavaScript HTML Events</h2>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body></html> WT - Kirti Sharma
WT - Kirti Sharma
JavaScript Strings
JavaScript strings are for storing and manipulating text.
A JavaScript string is zero or more characters written inside quotes.
You can use single or double quotes.
String Length
To find the length of a string, use the built-in length property.
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>The escape sequence \" inserts a double quote in a
string.</p>
<p id="demo"></p>
<script>
let text = "We are the so-called \"Vikings\" from the north.";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
WT - Kirti Sharma
Javascript objects cannot be compared.
JavaScript String Methods
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
</body>
</html>
WT - Kirti Sharma
The replace() method does not change the string it is called on.
The replace() method returns a new string.
The replace() method replaces only the first match
By default, the replace() method replaces only the first match.
By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case) will not
work.
WT - Kirti Sharma
WT - Kirti Sharma
WT - Kirti Sharma
The two
methods, indexOf() and search(),
are equal?
They accept the same arguments
(parameters), and return the same
value?
The two methods are NOT equal.
These are the differences:
•The search() method cannot take a
second start position argument.
•The indexOf() method cannot take
powerful search values (regular
expressions).
WT - Kirti Sharma
The startsWith() method is case sensitive.
WT - Kirti Sharma
The endsWith() method is case sensitive.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Numbers</h2>
<p id="demo"></p>
<script>
var x = 10;
var y = 20;
document.getElementById("demo").innerHTML =
"The result is: " + x + y;
</script></body></html>
WT - Kirti Sharma
JavaScript will try to convert strings to numbers in
<!DOCTYPE html>
all numeric operations:
<html>
<body> <!DOCTYPE html>
<h2>JavaScript Numbers</h2> <html>
<p id="demo"></p> <body>
<script>
let myNumber = 32;
document.getElementById("demo").innerHTML =
"32 = " + "<br>" +
" Decimal " + myNumber.toString(10) + "<br>" +
" Hexadecimal " + myNumber.toString(16) + "<br>" +
" Octal " + myNumber.toString(8) + "<br>" +
" Binary " + myNumber.toString(2);
</script></body></html>
WT - Kirti Sharma
WT - Kirti Sharma
WT - Kirti Sharma
WT - Kirti Sharma
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Methods</h2>
<h2>shift()</h2>
<p>The shift() method removes the first element of an array (and "shifts" the other elements to the left):</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.shift();
document.getElementById("demo2").innerHTML = fruits;
</script></body></html>
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Methods</h2>
<h2>unshift()</h2>
<p>The unshift() method adds new elements to the beginning of an array:</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.unshift("Lemon");
document.getElementById("demo2").innerHTML = fruits;
</script></body></html>
WT - Kirti Sharma
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Methods</h2>
<h2>splice()</h2>
<p>The splice() method adds new elements to an array:</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Methods</h2>
<h2>splice()</h2>
<p>The splice() methods can be used to remove array elements:</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.splice(0, 1);
document.getElementById("demo2").innerHTML = fruits;
</script></body></html> WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Methods</h2>
<h2>slice()</h2>
<p>This example slices out a part of an array starting from
array element 1 ("Orange"):</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Lemon", "Apple",
The slice() method creates a new array. "Mango"];
const citrus = fruits.slice(1);
The slice() method does not remove any
document.getElementById("demo").innerHTML = fruits +
elements from the source array. "<br><br>" + citrus;
</script></body></html>
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>Sort the array in ascending order:</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;
WT - Kirti Sharma
<!DOCTYPE html>
<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>
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<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>
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="demo"></p>
<script>
const time = new Date().getHours();
let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML =
greeting;
</script></body></html>
WT - Kirti Sharma
<!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";
This is how it works: break;
case 4:
•The switch expression is evaluated once.
day = "Thursday";
•The value of the expression is compared with the break;
values of each case. case 5:
•If there is a match, the associated block of code is day = "Friday";
break;
executed. case 6:
•If there is no match, the default code block is day = "Saturday";
executed. }
document.getElementById("demo").innerHTML = "Today is " +
day;
WT - Kirti Sharma
</script></body></html>
WT - Kirti Sharma
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Loop</h2>
<p id="demo"></p>
<script>
let text = "";
<script>
const person = {fname:"John", lname:"Doe",
age:25};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML =
txt;
</script></body></html>
WT - Kirti Sharma
<!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];
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript While Loop</h2>
<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML =
text;
</script></body></html>
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Do While Loop</h2>
<p id="demo"></p>
<script>
let text = ""
let i = 0;
do {
text += "<br>The number is " + i;
i++;
}
while (i < 10);
document.getElementById("demo").innerHTML = text;
</script></body></html> WT - Kirti Sharma
WT - Kirti Sharma
WT - Kirti Sharma
WT - Kirti Sharma
In the example above, getElementById is a method, while innerHTML is a property.
WT - Kirti Sharma
WT - Kirti Sharma
WT - Kirti Sharma
If the element is found, the method will return the element as an object (in element).
If the element is not found, element will contain null.
WT - Kirti Sharma
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<script>
const element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>
</body>
</html>
WT - Kirti Sharma
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
</body>
</html> WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Validation</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script></body></html> WT - Kirti Sharma
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML Events</h2>
<h2 onclick="this.innerHTML='Ooops!'">Click on this
text!</h2>
</body>
</html>
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<script>
function upperCase() {
const x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
WT - Kirti Sharma
WT - Kirti Sharma
WT - Kirti Sharma
Child Nodes and Node Values
WT - Kirti Sharma
All the (3) following examples retrieves the text of an <h1> element and copies it into a <p> element:
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<h1 id="id01">My First Page</h1> <h1 id="id01">My First Page</h1>
<p id="id02"></p> <p id="id02"></p>
<script> <script>
document.getElementById("id02").innerHTML document.getElementById("id02").innerHTML =
= document.getElementById("id01").firstChild.nodeValue;
document.getElementById("id01").innerHTML; </script>
</script> </body>
</body> </html>
</html>
<!DOCTYPE html>
<html>
<body>
<h1 id="id01">My First Page</h1>
<p id="id02"></p>
<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").childNodes[0].nodeValue;
</script></body></html>
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTMLDOM</h2>
<p>Displaying document.body</p>
<p id="demo"></p> <!DOCTYPE html>
<script> <html>
document.getElementById("demo").innerHTML = <body>
document.body.innerHTML; <h1 id="id01">My First Page</h1>
</script></body></html> <p id="id02"></p>
<!DOCTYPE html> <script>
<html> document.getElementById("id02").innerHTML =
<body> document.getElementById("id01").nodeName;
<h2>JavaScript HTMLDOM</h2> </script></body></html>
<p>Displaying document.documentElement</p>
<p id="demo"></p>
nodeName always contains the
<script>
document.getElementById("demo").innerHTML =
uppercase tag name of an HTML
document.documentElement.innerHTML; element.
</script></body></html> WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Add a new HTML Element.</p>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
const element = document.getElementById("div1");
element.appendChild(para);
</script>
</body>
</html>
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<div>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<button onclick="myFunction()">Remove
Element</button>
<script>
function myFunction() {
document.getElementById("p1").remove();
}
</script>
</body>
</html>
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<h3>Replace an HTML Element.</h3>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is a paragraph.</p>
</div>
<script>
const parent = document.getElementById("div1");
const child = document.getElementById("p1");
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
parent.replaceChild(para,child);
</script></body></html>
WT - Kirti Sharma
The Browser Object Model – BOM
The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Window</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Browser inner window width: " + window.innerWidth + "px<br>" +
"Browser inner window height: " + window.innerHeight + "px";
</script>
</body>
</html>
WT - Kirti Sharma
WT - Kirti Sharma
WT - Kirti Sharma
JavaScript Window Location
The window.location object can be used to get the current page address (URL) and to redirect the
browser to a new page.
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<script>
document.getElementById("demo").innerHTML =
"The full URL of this page is:<br>" + window.location.href;
</script></body></html>
WT - Kirti Sharma
WT - Kirti Sharma
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<script>
function newDoc() {
window.location.assign("https://www.google.com/")
}
</script>
</body>
</html>
WT - Kirti Sharma
Window History Back
WT - Kirti Sharma
Window History Forward JavaScript Window Navigator
The window.navigator object contains information
about the visitor's browser.
Browser Cookies
The cookieEnabled property returns true if cookies are enabled,
otherwise false:
<!DOCTYPE html>
<html>
<body>
<h2>The Navigator Object</h2>
<p>The cookieEnabled property returns true if cookies are
enabled:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"navigator.cookieEnabled is " + navigator.cookieEnabled;
WT - Kirti Sharma </script></body></html>
Browser Application Name Browser Application Code Name
The appName property returns the application name of The appCodeName property returns the application code
the browser: name of the browser:
WT - Kirti Sharma
The Browser Platform
The platform property returns the browser
platform (operating system):
<!DOCTYPE html>
<html>
<body>
WT - Kirti Sharma
2. Confirm Box
JavaScript Popup/Dialog Boxes A confirm box is often used if you want the user to verify or
JavaScript has three kind of popup boxes: accept something.
When a confirm box pops up, the user will have to click either
Alert box, Confirm box, and Prompt box.
"OK" or "Cancel" to proceed.
1. Alert Box If the user clicks "OK", the box returns true. If the user clicks
"Cancel", the box returns false.
An alert box is often used if you want to make sure
information comes through to the user. Syntax
When an alert box pops up, the user will have to click window.confirm("sometext");
"OK" to proceed.
The window.confirm() method can be written without
Syntax the window prefix.
window.alert("sometext"); <!DOCTYPE html>
<html>
The window.alert() method can be written without the <body>
window prefix. <h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<!DOCTYPE html> <script>
<html> function myFunction() {
<body> var txt;
if (confirm("Press a button!")) {
<h2>JavaScript Alert</h2>
txt = "You pressed OK!";
<button onclick="myFunction()">Try it</button> } else {
<script> txt = "You pressed Cancel!";
function myFunction() { }
document.getElementById("demo").innerHTML = txt;
alert("I am an alert box!"); }
} </script></body></html>
WT - Kirti Sharma
</script></body></html>
3. Prompt Box <!DOCTYPE html>
A prompt box is often used if you want the user to <html>
input a value before entering a page. <body>
When a prompt box pops up, the user will have to click <h2>JavaScript Prompt</h2>
either "OK" or "Cancel" to proceed after entering an
<button onclick="myFunction()">Try it</button>
input value.
If the user clicks "OK" the box returns the input value.
<p id="demo"></p>
If the user clicks "Cancel" the box returns null. <script>
function myFunction() {
Syntax let text;
window.prompt("sometext","defaultText"); let person = prompt("Please enter your name:", "Harry
Potter");
The window.prompt() method can be written without if (person == null || person == "") {
the window prefix.
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = text;
}
</script></body></html>
WT - Kirti Sharma