Java Script
Java Script
Java Script
HTML JavaScript
JavaScript helps in making HTML pages more interactive and dynamic.
JavaScript is one of the 3 languages all web developers must learn:
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>
</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>
<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>
</body>
</html>
JavaScript Can Change HTML Styles (CSS)
<!DOCTYPE html>
<html>
<body>
</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.
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.
<!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:
function myFunction() {
External scripts are practical when the same code is used in many different web pages.
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>
The script will behave as if it was located exactly where the <script> tag is located.
<!DOCTYPE html>
<html>
<body>
<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.
<!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>
</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() {
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
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:
Syntax:
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>
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:
fruits.pop();
Array shift()
The shift() method removes the first array element and "shifts" all other elements
to a lower index.
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
<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>
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.
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.
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).
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:
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.
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)
7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):
new Date(dateString)
new Date(dateString) creates a new date object from a date string:
new Date(milliseconds)
new Date(milliseconds) creates a new date object as zero time plus milliseconds:
The toUTCString() method converts a date to a UTC string (a date display standard).
const d = new Date();
d.toUTCString();
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.
Examples:
Date.parse() returns the number of milliseconds between the date and January 1, 1970:
Method Description
Method Description
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.
<script>
function myFunction() {
alert('Hello');
}
</script>
The clearTimeout() method stops the execution of the function specified in setTimeout().
window.clearTimeout( timeoutVariable)
If the function has not already been executed, you can stop the execution by calling the
clearTimeout() method.
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)
Example:
<p id="demo"></p>
<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 =
</script>
Output:
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.
In the following examples, an onclick attribute (with code), is added to a <button> element:
Event Description
Onmouseout The user moves the mouse away from an HTML element
<script>
function myFunction(val) {
alert("The input value has changed. The new value is: " + val);
}
</script>
onsubmit Event:
<form onsubmit="myFunction()">
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
<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.
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:
"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."