Java Script

Download as pdf or txt
Download as pdf or txt
You are on page 1of 101

JavaScript

HTML JavaScript
JavaScript helps in making HTML pages more interactive and dynamic.
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

JavaScript is already running in the browser, no need to download.


The <script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags.

The HTML <script> tag is used to define a client-side script, such as a JavaScript.
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<script>
document.getElementById("demo1").innerHTML = "Hello";
</script>
</body>
</html>
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().

<!DOCTYPE html>
<html>
<body>

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

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

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello


JavaScript!"'>Click Me!</button>

</body>
</html>
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>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>
</html>
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>

<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 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> 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 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>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>

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


<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
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>
External JavaScript
Scripts can also be placed in external files:

External file: myScript.js

function myFunction() {

document.getElementById("demo").innerHTML = "Paragraph changed.";

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of a
<script> tag.
<!DOCTYPE html>
<html>
<body>
<h2>Demo External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>

<script src="myScript.js"></script>
</body>
</html>

We can place an external script reference in <head> or <body>.

The script will behave as if it was located exactly where the <script> tag is located.

External scripts cannot contain <script> tags.


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 innerHTML
To access an HTML element, JavaScript can use the document.getElementById(id)
method.
The id attribute defines the HTML element. The innerHTML property defines the HTML
content:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

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

<script>
document.getElementById("demo").innerHTML = “Hello”;
</script>

</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write() :
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(“hello”);
</script>
</body>
</html>

Using document.write() after an HTML document is loaded, will delete all existing
HTML.
The document.write() method should only be used for testing.
Using window.alert()
You can use an alert box to display data:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
In JavaScript, the window object is the global scope object, that means that variables,
properties, and methods by default belong to the window object. That is, specifying the
window keyword is optional.

That means instead of window.alert(5 + 6), we can use alert(5 + 6).


Using console.log()
For debugging purposes, you can call the console.log() method in the browser to display
data.

<!DOCTYPE html>

<html>

<body>

<script>

console.log(5 + 6);

</script>

</body>

</html>
JavaScript 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.

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a computer. In a
programming language, these programming instructions are called statements. A JavaScript
program is a list of programming statements. In HTML, JavaScript programs are executed by
the web browser.

JavaScript Statements
JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and
Comments.
The following statement tells the browser to write "Hello Dolly" inside an HTML element with
id="demo":
document.getElementById("demo").innerHTML = "Hello Dolly";
Most JavaScript programs contain many JavaScript statements. The statements are
executed, one by one, in the same order as they are written.
JavaScript Code Blocks
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together. One place you
will find statements grouped together in blocks, is in JavaScript functions:

function myFunction() {

document.getElementById("demo1").innerHTML = "Hello Dolly!";

document.getElementById("demo2").innerHTML = "How are you?";}

JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed. JavaScript keywords are reserved words. Reserved words cannot be used as
names for variables.
JavaScript Variables
In a programming language, variables are used to store data values. JavaScript uses the
keywords var, let and const to declare variables.

<html>
<body>
<h2>JavaScript Variables</h2>
<p id="demo"></p>
<script>
let x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
JavaScript Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic on numbers.
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
– Decrement

Example: let x = 100 + 50;


Assignment Operators
Assignment operators assign values to JavaScript variables. Assignment operators are =,
+=, -=, *=, /=, %=, **= etc.

Example: let x = 10;


x += 5;

Comparison Operators
Operator Description
== equal to
!= not equal
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Logical Operators
Operator Description
&& logical and
|| logical or
! logical not

Bitwise Operators
Bit operators work on 32 bits numbers. Any numeric operand in the operation is converted
into a 32 bit number. The result is converted back to a JavaScript number.
Operator Description
& AND
| OR
~ NOT
^ XOR
<< left shift
>> right shift
Example:
<html>
<body>
<h2>JavaScript Operators</h2>
<p id="demo"></p>

<script>
let a = 3;
let x = (100 + 50) * a;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
JavaScript Data Types
JavaScript variables can hold different data types: numbers, strings, objects and more:
let length = 16; // Number
let lastName = "Johnson"; // String
let x = {firstName:"John", lastName:"Doe"}; // Object

JavaScript has dynamic types. This means that the same variable can be used to hold
different data types:
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String

Strings:
A string (or a text string) is a series of characters. Strings are written either in single quotes
or in double quotes.
let carName1 = "Volvo XC60"; // Using double quotes
let carName2 = 'Volvo XC60'; // Using single quotes
Numbers:
JavaScript has only one type of numbers. Numbers can be written with, or without decimals.
let x1 = 34.00; // Written with decimals
let x2 = 34; // Written without decimals
Extra large or extra small numbers can be written with scientific (exponential) notation.
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123

Booleans:
Booleans can only have two values: true or false.
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
Arrays
An array is a special variable, which can hold more than one value:

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

Syntax:

const array_name = [item1, item2, ...];

Using the JavaScript Keyword new:


The following example also creates an Array, and assigns values to it:

const cars = new Array("Saab", "Volvo", "BMW");

Note:The two examples above do exactly the same.

There is no need to use new Array() .

For simplicity, readability and execution speed, use the array literal (first) method.
An array element can be accessed by referring to the index number:
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
Note: Array indexes start with 0.

With JavaScript, the full array can be accessed by referring to the array name.
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>

Output: JavaScript Arrays


Saab,Volvo,BMW
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods.

The length Property


The length property of an array returns the length of an array (the number of array
elements).

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

let length = fruits.length;


Looping Array Elements
One way to loop through an array, is using a for loop:
Example:
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;
let text ="";
for (let i = 0; i < fLen; i++) {
text += fruits[i]+",";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
You can also use the Array.forEach() function:
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>Array.forEach() calls a function for each array element.</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let text = "";
fruits.forEach(myFunction);
document.getElementById("demo").innerHTML = text;
function myFunction(value) {
text += value + ",";
}
</script>
</body>
</html>
Adding Array Elements
The easiest way to add a new element to an array is using the push() method.
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon"); // Adds a new element (Lemon) to fruits

JavaScript new Array()


JavaScript has a built in array constructor new Array() .
But you can safely use [] instead.

The following two different statements both create a new empty array named points
const points = new Array();
const points = [];

These two different statements both create a new array containing 6 numbers:
const points = new Array(40, 100, 1, 5, 25, 10);
const points = [40, 100, 1, 5, 25, 10];
Converting Arrays to Strings
The JavaScript method toString() converts an array to a string of (comma separated)
array values.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:
Banana,Orange,Apple,Mango

The join() method also joins all array elements into a string.

It behaves just like toString() , but in addition you can specify the separator:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
Result:
Banana * Orange * Apple * Mango
Array pop()
The pop() method removes the last element from an array:

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

fruits.pop();

Array shift()
The shift() method removes the first array element and "shifts" all other elements
to a lower index.

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

fruits.shift();
Array unshift()
The unshift() method adds a new element to an array (at the beginning), and "unshifts"
older elements:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
Merging (Concatenating) Arrays
The concat() method creates a new array by merging (concatenating) existing arrays.
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);

The concat() method does not change the existing arrays. It always returns a new array.
The concat() method can take any number of array arguments
const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin", "Morgan"];
const myChildren = arr1.concat(arr2, arr3);
Splicing and Slicing Arrays
The splice() method adds new items to an array.
The slice() method slices out a piece of an array.

Array splice()
The splice() method can be used to add new items to an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
The splice() method returns an array with the deleted items.
<html>
<body>
<h2>JavaScript Array Methods</h2>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.splice(2, 0, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = fruits;
</script>
</body>
</html>
Output: JavaScript Array Methods
Banana,Orange,Apple,Mango

Banana,Orange,Lemon,Kiwi,Apple,Mango
<html>
<body>
<h2>JavaScript Array Methods</h2>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = "Original Array:<br> " + fruits;
let removed = fruits.splice(2, 2, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = "New Array:<br>" + fruits;
document.getElementById("demo3").innerHTML = "Removed Items:<br> " + removed;
</script>
</body>
</html>
Output: JavaScript Array Methods
Original Array:
Banana,Orange,Apple,Mango
New Array:
Banana,Orange,Lemon,Kiwi
Removed Items:
Apple,Mango
Array slice()
The slice() method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1 ("Orange"):
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1);
Example:

<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1);
document.getElementById("demo").innerHTML =fruits +"<br>"+ citrus;
</script>
Output: Banana,Orange,Lemon,Apple,Mango
Orange,Lemon,Apple,Mango
Note:The slice() method creates a new array.
The slice() method does not remove any elements from the source array.

The slice() method can take two arguments like slice(1, 3).
The method then selects elements from the start argument, and up to (but not
including) the end argument.
Example:

p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1,3);
document.getElementById("demo").innerHTML = fruits + "<br>" + citrus;
</script>

Output: Banana,Orange,Lemon,Apple,Mango
Orange,Lemon
Sorting an Array
The sort() method sorts an array alphabetically:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

Reversing an Array
The reverse() method reverses the elements in an array.
You can use it to sort an array in descending order:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Conditional Statements
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
}
Example

Make a "Good day" greeting if the hour is less than 18:00:

<p id="demo">Good Evening!</p>

<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>

Output: Good day!


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
}
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.
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
}
Example:
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Switch Statement
Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The default keyword specifies the code to run if there is no case match.
<html>
<body>
<h2>JavaScript switch</h2>
<p id="demo"></p>
<script>
let day;
switch (new Date().getDay()) {
case 0: day = "Sunday"; break;
case 1: day = "Monday"; break;
case 2: day = "Tuesday"; break;
case 3: day = "Wednesday"; break;
case 4: day = "Thursday"; break;
case 5: day = "Friday"; break;
case 6: day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>
</body>
</html>
The For Loop
The for statement creates a loop with 3 optional expressions:
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
Example:
<p id="demo"></p>
<script>`
let text = "";
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
Output: The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
Loop Scope
Using var in a loop:
var i = 5;
for (var i = 0; i < 10; i++) {
// some code
}
// Here i is 10
Using let in a loop:
let i = 5;
for (let i = 0; i < 10; i++) {
// some code
}
// Here i is 5
The For In Loop
The JavaScript for in statement loops through the properties of an Object:
Syntax
for (key in object) {
// code block to be executed
}
Example:
<p id="demo"></p>
<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>
Output: John Doe 25
The JavaScript for in statement can also loop over the properties of an Array:
Syntax:
for (variable in array) {
code
}
Example:
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>
The For Of Loop
The JavaScript for of statement loops through the values of an iterable object.
It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and
more:
for (variable of iterable) {
// code block to be executed
}
Looping over an Array
<p id="demo"></p>
<script>
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
Output: BMW
Volvo
Mini
Looping over a String
<p id="demo"></p>
<script>
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
While Loop
The while loop loops through a block of code as long as a specified condition is true.
Syntax:
while (condition) {
// code block to be executed
}

Example:
<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>
Do While Loop
The do while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax:
do {
// code block to be executed
}while (condition);

Example:
<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>
Break and Continue
The break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in the loop.

The Break Statement


You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch() statement.
The break statement can also be used to jump out of a loop:
for (let i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
The Continue Statement
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

This example skips the value of 3:

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


if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
Function
function functionName(parameters) {
// code to be executed
}
Example:
<html>
<body>
<h2>JavaScript Functions</h2>
<p id="demo"></p>
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>
Function Expressions
A JavaScript function can also be defined using an expression.

A function expression can be stored in a variable:

const x = function (a, b) {return a * b};

After a function expression has been stored in a variable, the variable can be used as a function.

Example:
<p id="demo"> </p>
<script>
const x = function (a, b) {return a * b};
document.getElementById("demo").innerHTML = x(4, 3);
</script>
The function above is actually an anonymous function (a function without a name). Functions stored
in variables do not need function names. They are always invoked (called) using the variable name.
The Function() Constructor
Functions can also be defined with a built-in JavaScript function constructor
called Function().
<p id="demo"> </p>
<script>
const myFunction = new Function("a", "b", "return a * b");
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
Functions are Objects
JavaScript functions have both properties and methods.
The arguments.length property returns the number of arguments received
when the function was invoked:
Example
function myFunction(a, b) {
return arguments.length;
}
Classes
Use the keyword class to create a class.
Always add a method named constructor() :
class ClassName {
constructor() { ... }
}
Example:
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
When you have a class, you can use the class to create objects:
let myCar1 = new Car("Ford", 2014);
let myCar2 = new Car("Audi", 2019);
The constructor method is called automatically when a new object is created.

The Constructor Method


The constructor method is a special method:
● It has to have the exact name "constructor"
● It is executed automatically when a new object is created
● It is used to initialize object properties
Class Methods
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
Example:
<p id="demo"></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
let date = new Date();
return date.getFullYear() - this.year;
}
}
let myCar = new Car("Ford", 2014);
document.getElementById("demo").innerHTML =
"My car is " + myCar.age() + " years old.";
</script>
Class Inheritance
To create a class inheritance, use the extends keyword.
A class created with a class inheritance inherits all the methods from another class
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}

class Model extends Car {


constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}

let myCar = new Model("Ford", "Mustang");


document.getElementById("demo").innerHTML = myCar.show();
Objects
In JavaScript, almost "everything" is an object.
● Booleans can be objects (if defined with the new keyword)
● Numbers can be objects (if defined with the new keyword)
● Strings can be objects (if defined with the new keyword)
● Dates are always objects
● Maths are always objects
● Regular expressions are always objects
● Arrays are always objects
● Functions are always objects
● Objects are always objects
All JavaScript values, except primitives, are objects.
JavaScript Primitives
A primitive value is a value that has no properties or methods.

3.14 is a primitive value

A primitive data type is data that has a primitive value.

JavaScript defines 7 types of primitive data types:

Examples
● string
● number
● boolean
● null
● undefined
● symbol
● bigint
Objects are variables which contain many values.

Object values are written as name : value pairs (name and value separated by a
colon).

Example: let person = {firstName:"John", lastName:"Doe", age:50,


eyeColor:"blue"};

A JavaScript object is a collection of named values

It is a common practice to declare objects with the const keyword.

const person = {firstName:"John", lastName:"Doe", age:50,


eyeColor:"blue"};
With JavaScript, you can define and create your own objects.

There are different ways to create new objects:

● Create a single object, using an object literal.


● Create a single object, with the keyword new.
● Define an object constructor, and then create objects of the constructed type.
● Create an object using Object.create() .

Object Literal:const person = {firstName:"John", lastName:"Doe", age:50,


eyeColor:"blue"};
Properties
Properties are the values associated with a JavaScript object.
The syntax for accessing the property of an object is:
objectName.property // person.age
or
objectName["property"] // person["age"]
or
objectName[expression] // x = "age"; person[x]

New Properties:
You can add new properties to an existing object by simply giving it a value.
person.nationality = "English";

Deleting Properties:
The delete keyword deletes a property from an object.
delete person.age; or delete person["age"];
Nested Objects
Values in an object can be another object:
Example
myObj = {
name:"John",
age:30,
cars: {
car1:"Ford",
car2:"BMW",
car3:"Fiat"
}
}

You can access nested objects using the dot notation or the bracket notation:

myObj.cars.car2; or myObj.cars["car2"]; or myObj["cars"]["car2"];


Strings
JavaScript strings are for storing and manipulating text.
A JavaScript string is zero or more characters written inside quotes.
let text = "John Doe";
String Length
To find the length of a string, use the built-in length property.
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Strings as Objects
Normally, JavaScript strings are primitive values, created from literals:
let x = "John";
But strings can also be defined as objects with the keyword new:
let y = new String("John");
Extracting String Parts
There are 3 methods for extracting a part of a string:
● slice(start, end)
● substring( start, end)
● substr(start, length)
String slice():
slice() extracts a part of a string and returns the extracted part in a new string.
let str = "Apple, Banana, Kiwi";
let part = str.slice(7, 13);
Slice out a portion of a string from position 7 to position 13 (13 not included).
substring():
substring() is similar to slice(). The difference is that start and end values less than 0
are treated as 0 in substring() .
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
substr():
substr() is similar to slice(). The difference is that the second parameter specifies the
length of the extracted part.
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
Replacing String Content:
The replace() method replaces a specified value with another value in a string:
let text = "Hi, how are you!";
let newText = text.replace("Hi", "Hello");

Converting to Upper and Lower Case:


A string is converted to upper case with toUpperCase( ). A string is converted to lower case
with toLowerCase() .
let text1 = "Hello World!";
let text2 = text1.toUpperCase();
let text3 = text1.toLowerCase();

String concat():
concat() joins two or more strings:
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
The concat() method can be used instead of the plus operator. These two lines do the same:
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");
String trim():
The trim() method removes whitespace from both sides of a string:
let text1 = " Hello World! ";
let text2 = text1.trim();

String Padding:
ECMAScript 2017 added two String methods: padStart() and padEnd() to support padding
at the beginning and at the end of a string.
The padStart() method pads a string with another string:
let text = "5";
let padded = text.padStart(4,"x");
The padEnd() method pads a string with another string
let text = "5";
let padded = text.padEnd(4,"x");
Extracting String Characters:
There are 3 methods for extracting string characters:

● charAt(position)
● charCodeAt( position)
● Property access [ ]

The charAt() method returns the character at a specified index (position) in a string.

The charCodeAt() method returns the unicode of the character at a specified index.

let text = "HELLO WORLD";

let char1 = text.charAt(0);

let char2 = text.charCodeAt(0);

let char3 = text[0];


JavaScript String split()
A string can be converted to an array with the split() method:
text.split(",") // Split on commas
text.split(" ") // Split on spaces
text.split("|") // Split on pipe

Search Methods
● String indexOf()
● String lastIndexOf()
● String startsWith()
● String endsWith()

The indexOf() method returns the index of (the position of) the first occurrence of a
specified text in a string.
let str = "Please locate where 'locate' occurs!";
str.indexOf("locate") ;

The lastIndexOf() method returns the index of the last occurrence of a specified text in a
string.
let str = "Please locate where 'locate' occurs!";
str.lastIndexOf("locate");
Both indexOf(), and lastIndexOf() return -1 if the text is not found.
Both methods accept a second parameter as the starting position for the search.
The lastIndexOf() methods searches backwards (from the end to the beginning),
meaning: if the second parameter is 15, the search starts at position 15, and searches to
the beginning of the string.

The search() method searches a string for a specified value and returns the position of the
match.
let str = "Please locate where 'locate' occurs!";
str.search("locate");
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).

The match() method searches a string for a match against a regular expression, and
returns the matches, as an Array object.
Search a string for "ain":
let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/g);
The includes() method returns true if a string contains a specified value.
let text = "Hello world, welcome to the universe.";
text.includes("world");

The startsWith() method returns true if a string begins with a specified value, otherwise
false.
let text = "Hello world, welcome to the universe.";
text.startsWith("Hello");

The endsWith() method returns true if a string ends with a specified value, otherwise
false.
Check if a string ends with "Doe":
let text = "John Doe";
text.endsWith("Doe");
Date Objects
By default, JavaScript will use the browser's time zone and display a date as a full text
string.
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
Output: Tue Aug 16 2022 07:33:45 GMT+0530 (India Standard Time)

Creating Date Objects:


Date objects are created with the new Date() constructor.
There are 4 ways to create a new date object:
new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)
new Date(year, month, ...)
new Date(year, month, ...) creates a new date object with a specified date and time.

7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):

const d = new Date(2018, 11, 24, 10, 33, 30, 0);

new Date(dateString)
new Date(dateString) creates a new date object from a date string:

const d = new Date("October 13, 2014 11:13:00");

new Date(milliseconds)
new Date(milliseconds) creates a new date object as zero time plus milliseconds:

const d = new Date(86400000);


Date Methods
When you display a date object in HTML, it is automatically converted to a string, with the
toString() method.
const d = new Date();
d.toString();

The toUTCString() method converts a date to a UTC string (a date display standard).
const d = new Date();
d.toUTCString();

The toDateString() method converts a date to a more readable format.


const d = new Date();
d.toDateString();

The toISOString() method converts a Date object to a string, using the ISO standard
format.
const d = new Date();
d.toISOString();
There are generally 3 types of JavaScript date input formats.

ISO Date "2015-03-25" (The International Standard)

Short Date "03/25/2015"

Long Date "Mar 25 2015" or "25 Mar 2015"

Examples:

const d = new Date("2015-03-25");

const d = new Date("03/25/2015");

const d = new Date("Mar 25 2015");

Date.parse() returns the number of milliseconds between the date and January 1, 1970:

let msec = Date.parse("March 21, 2012");


Get Date Methods
These methods can be used for getting information from a date object.

Method Description

getFullYear() Get the year as a four digit number (yyyy)

getMonth() Get the month as a number (0-11)

getDate() Get the day as a number (1-31)

getHours() Get the hour (0-23)

getMinutes() Get the minute (0-59)

getSeconds() Get the second (0-59)

getMilliseconds() Get the millisecond (0-999)

getTime() Get the time (milliseconds since January 1, 1970)

getDay() Get the weekday as a number (0-6)

Date.now() Get the time.


Set Date Methods
Set Date methods are used for setting a part of a date

Method Description

setDate() Set the day as a number (1-31)

setFullYear() Set the year (optionally month and day)

setHours() Set the hour (0-23)

setMilliseconds() Set the milliseconds (0-999)

setMinutes() Set the minutes (0-59)

setMonth() Set the month (0-11)

setSeconds() Set the seconds (0-59)

setTime() Set the time (milliseconds since January 1, 1970)


Popup Boxes
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box:
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax: window.alert("sometext");
The window.alert() method can be written without the window prefix.
Example: alert("I am an alert box!");

Confirm Box:
A confirm box is often used if you want the user to verify or accept something.When a confirm
box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks
"OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax: window.confirm("sometext");
The window.confirm() method can be written without the window prefix.
Example:
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
Prompt Box:
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed
after entering an input value. If the user clicks "OK" the box returns the input value. If the
user clicks "Cancel" the box returns null.
Syntax: window.prompt(" sometext","defaultText");
The window.prompt() method can be written without the window prefix.
Example:
let person = prompt("Please enter your name", "Harry Potter");
let text;
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
Timing Events
The window object allows execution of code at specified time intervals.
These time intervals are called timing events.
The two key methods to use with JavaScript are:
● setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.

setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.

The setTimeout() Method:


window.setTimeout(function, milliseconds);
The window.setTimeout() method can be written without the window prefix.
The first parameter is a function to be executed.
The second parameter indicates the number of milliseconds before execution.
Example
Click a button. Wait 3 seconds, and the page will alert "Hello":
<button onclick="setTimeout(myFunction, 3000)">Try it</button>

<script>
function myFunction() {
alert('Hello');
}
</script>
The clearTimeout() method stops the execution of the function specified in setTimeout().

window.clearTimeout( timeoutVariable)

The window.clearTimeout() method can be written without the window prefix.

The clearTimeout() method uses the variable returned from setTimeout() .

myVar = setTimeout( function, milliseconds);


clearTimeout(myVar);

If the function has not already been executed, you can stop the execution by calling the
clearTimeout() method.

<button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button>

<button onclick="clearTimeout(myVar)">Stop it</button>


The setInterval() Method
The setInterval() method repeats a given function at every given time-interval.
window.setInterval(function, milliseconds);

The window.setInterval() method can be written without the window prefix.


The first parameter is the function to be executed.
The second parameter indicates the length of the time-interval between each
execution.
Example: This example executes a function called "myTimer" once every second (like a
digital watch).

Display the current time:


setInterval(myTimer, 1000);

function myTimer() {
const d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
The clearInterval() method stops the executions of the function specified in the
setInterval() method.

window.clearInterval( timerVariable)

The window.clearInterval() method can be written without the window prefix.

The clearInterval() method uses the variable returned from setInterval() :

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

<button onclick="clearInterval(myVar)">Stop time</button>

<script>
let myVar = setInterval(myTimer ,1000);
function myTimer() {
const d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
Built-in global functions
isNaN() Determines whether a value is an illegal number
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
String() Converts an object's value to a string

isNaN() method returns true if a value is Not-a-Number. isNaN() converts the value to a number
before testing it.
Example:
<p id="demo"></p>

<script>
let result ="Is '123' NaN? " + isNaN('123') + "<br>" +"Is 'Hello' NaN? " + isNaN('Hello') +
"<br>" +"Is '2005/12/12' NaN? " + isNaN('2005/12/12');

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

Output:
Is '123' NaN? false
Is 'Hello' NaN? true
Is '2005/12/12' NaN? true
The Number() method converts a value to a number. If the value cannot be
converted, NaN is returned.
Note: For booleans, Number() returns 0 or 1.
For dates, Number() returns milliseconds since January 1, 1970 00:00:00.
For strings, Number() returns a number or NaN.
Example:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
Number(true) + "<br>" +
Number(false) + "<br>" +
Number(new Date());
</script>
Output:
1
0
1660705657493
The parseInt method parses a value as a string and returns the first integer.
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
parseInt("10", 10)+ "<br>" +
parseInt("010")+ "<br>" +
parseInt("10", 8)+ "<br>" +
parseInt("0x10")+ "<br>" +
parseInt("10", 16);
</script>

Output:
10
10
8
16
16
The parseFloat() method parses a value as a string and returns the first number.

Example:

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
parseFloat("40.00") + "<br>" +
parseFloat(" 40 ") + "<br>" +
parseFloat("40 years") + "<br>" +
parseFloat("40H") + "<br>" +
parseFloat("H40");
</script>

Output:

40
40
40
40
NaN
The String() method converts a value to a string.

Example:

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

<script>

document.getElementById("demo").innerHTML =

String(new Date()) + "<br>" +String("12345") + "<br>" +String(12345);

</script>

Output:

Wed Aug 17 2022 08:42:01 GMT+0530 (India Standard Time)

12345

12345
Events
HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these 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.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following examples, an onclick attribute (with code), is added to a <button> element:

<button onclick="document.getElementById('demo').innerHTML = Date()">


The time is?</button>

<button onclick="this.innerHTML = Date()">The time is?</button>

<button onclick="displayDate()">The time is?</button>


Common HTML Events
Here is a list of some common HTML events:

Event Description

Onchange An HTML element has been changed

Onclick The user clicks an HTML element

Onmouseover The user moves the mouse over an HTML element

Onmouseout The user moves the mouse away from an HTML element

Onkeydown The user pushes a keyboard key

Onload The browser has finished loading the page

Onblur The event occurs when an element loses focus

Onsubmit The event occurs when a form is submitted


onload Event:
<html>
<body onload="myFunction()">
<h1>Hello World!</h1>
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</body>
onchange Event:
Enter some text: <input type="text" name="txt" value="Hello" onchange="myFunction(this.value)">

<script>
function myFunction(val) {
alert("The input value has changed. The new value is: " + val);
}
</script>
onsubmit Event:
<form onsubmit="myFunction()">

Enter name: <input type="text">


<input type="submit">
</form>

onblur Event:
Enter your name: <input type="text" id="fname" onblur="myFunction()">

<script>

function myFunction() {

var x = document.getElementById("fname");
x.value = x.value.toUpperCase();}

</script>
onclick Event:
In this example, the content of the <h1> element is changed when a user clicks on it
<body>
<h2>JavaScript HTML Events</h2>
<h2 onclick="this.innerHTML='Ooops!'">Click on this text!</h2>
</body>
<body>
Or

<h2>JavaScript HTML Events</h2>


<h2 onclick="changeText(this)">Click on this text!</h2>

<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
Document Object Model(DOM)
With the HTML DOM, JavaScript can access and change all the elements of an HTML
document.

When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:


DOM Nodes
According to the W3C HTML DOM standard, everything in an HTML document is a node:
● The entire document is a document node
● Every HTML element is an element node
● The text inside HTML elements are text nodes
● Every HTML attribute is an attribute node (deprecated)
● All comments are comment nodes
With the HTML DOM, all nodes in the node tree can be accessed by JavaScript.
New nodes can be created, and all nodes can be modified or deleted.

Node Relationships
The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.
● In a node tree, the top node is called the root (or root node)
● Every node has exactly one parent, except the root (which has no parent)
● A node can have a number of children
● Siblings (brothers or sisters) are nodes with the same parent
With the object model, JavaScript gets all the power it needs to create dynamic HTML:

● JavaScript can change all the HTML elements in the page


● JavaScript can change all the HTML attributes in the page
● JavaScript can change all the CSS styles in the page
● JavaScript can remove existing HTML elements and attributes
● JavaScript can add new HTML elements and attributes
● JavaScript can react to all existing HTML events in the page
● JavaScript can create new HTML events in the page

"The W3C Document Object Model (DOM) is a platform and language-neutral interface
that allows programs and scripts to dynamically access and update the content,
structure, and style of a document."

You might also like