Javascript (1)
Javascript (1)
What is JavaScript?
It is a scripting language that is used to develop
websites.
It adds functionality and behaviour to a website,
allowing visitors to interact with the content.
Its an object oriented programming language that uses
JIT compiler
It is easy, simple and very compatible with HTML-CSS
It is must to have skill for any software engineer role,
there are many jobs that are hiring JavaScript
developers.
JavaScript Types are Dynamic
◦ Text Editor
For writing and editing of JS code, we need a simple editor
which can be notepad too.
There are other powerful editors which provide additional
functionalities like autocomplete, indentation, highlights etc.
Example: Visual Studio Code, Sublime text, Atom etc.
◦ Browser
All browsers come with an inbuilt JS engine.
They are used for executing JS code and also for debugging
purposes.
ECMA
ECMA stands for European Computer Manufacturers
Association
It maintains the standardization of JavaScript
Any modification or update is drafted and sent to the
committee
They do the discussion and decide whether to include
it or not
If passes it is added as the new update in the latest
released version
Latest version is ES2020 released in June 2020
JavaScript Code
Lets understand different ways to write JS code,
before jumping into coding
JS basically gets merged into html which is a skeleton
of web page
We can write JS in 3 ways
◦ Console
◦ Script Tag
◦ External JS file
JavaScript via console
Press Ctrl + Shift + I to open the console or right
click and then go to inspect
In console you can start writing code
console.log is used to print content on console
JavaScript via Script Tag
<script> tag is used for writing JavaScript in HTML
directly
Every console.log() will print the output in console of
browser
Here we are using sublime editor
Open sublime
Output:
JavaScript Properties
JS is dynamically typed- it doesn’t has to specify the type of
the variable explicitly.
◦ There is no need to define the data type for variable like int,
float etc.
◦ Only let, var and const is used for variable declaration
Example:
var myName = “Nihal”
myName = 32
let Name = “hello”
const pi = 3.14
var x; // declaring a variable x
console.log(x)
Output: undefined
x = 10; //Assigning 10 to x which was already declared
console.log(x)
Output: 10
var y = 4; // assigning a value 4 to a variable y
lowercase letter:
firstName, lastName, masterCard, interCity.
let and var
Variables defined with let cannot be Redeclared.
Variables defined with let must be Declared before use.
Example:
let x = "John Doe";
let x = 0;
// SyntaxError: 'x' has already been declared
JavaScript.
Variables declared inside a { } block cannot be accessed from
let x = 2;
}
// x cannot be used here
Variables declared with the var keyword can NOT have block
scope.
Variables declared inside a { } block can be accessed from
{
var x = 2;
// Here x is 2
}
// Here x is 2
Redeclaring a variable using the let keyword can solve this
problem.
Redeclaring a variable inside a block will not redeclare the
Variables defined with var are hoisted to the top and can be
initialized at any time.
You can use the var variable before it is declared.
Example:
carName = "Volvo";
var carName;
Output: "Volvo"
Variables defined with let are also hoisted to the top of the block,
but not initialized.
let variable before it is declared will result in a ReferenceError.
Example:
carName = “Uber";
let carName = "Volvo";
Output: ReferenceError: Cannot access 'carName' before initialization
Const
Variables defined with const cannot be Redeclared.
Variables defined with const cannot be Reassigned.
Variables defined with const have Block Scope.
Note: Declaring a variable with const is similar to let when it comes to Block
Scope.
const variable before it is declared will result in ReferenceError.
Always declare a variable with const unless you know that the
value will change.
Use const when you declare:
◦ A new Array
◦ A new Object
◦ A new Function
◦ A new RegExp
Data Types
JavaScript is a dynamically typed language.
It does not need to specify data type of the variable explicitly
at the time of declaration.
Example:
yet.
◦ A var may be undefined because its value is not known.
◦ Example: var z;
console.log(z)
Output: undefined
Primitive Data Type- null
◦ It is used to explicitly specify that the value of the variable is
null.
◦ Example: var x = null;
console.log(x)
Output: null
Difference Between Undefined and Null
let car = ""; // The value is "", the typeof is "string "
// An empty string has both a legal value and a type.
Primitive Data Type - Symbol
It is used for creating unique properties of objects.
Example:
let sym1 = Symbol(‘foo’);
let sym2 = Symbol(‘foo’);
sym1 === sym2
Output: false
Declaring String Variable
Strings are written inside quotes and can use single or double quote
Example:
var firstName = "John" ; var lastName = "Carnes"
len = firstName.length; //to return length of string
console.log(firstName+lastName)
console.log(firstName+ " "+ lastName)
console.log(len)
Output: "JohnCarnes" //Concatenate strings with + operator
"John Carnes“
4
One Statement, Many Variables
You can declare many variables in one statement, separate the
variables by comma.
var person = "John Doe", carName = "Volvo", price = 200;
Escaping Literal Quotes in Strings
Escape Character
var myStr = "Good \"morning!!!\" Have a good day"
console.log(myStr)
Output:
Good "morning!!!" Have a good day
Note: Shows quotation mark without backslash
Escape Character
Because strings must be written within quotes, JavaScript will
misunderstand this string. The solution to avoid this problem,
is to use the backslash escape character.
The backslash (\) escape character turns special characters into
string characters.
var Str =
"<a href=\"http:\\www.example.com\" target = \"_blank\"> Link</a> “
var Str1 =
`'<a href="http:\\www.example.com" target = "_blank"> Link</a>'`
console.log(Str)
console.log(Str1)
Output:
Double quotes ( \" ) must escape a double quote and vice versa
single quotes ( \' ) must escape a single quote.
let x = "John";
let y = new String("John");
console.log(x==y)
Output: true
in a new string.
The method takes 2 parameters: the start position, and the end
If you omit the second parameter, substring() will slice out the rest of the
string.
substr() Method
substr() is similar to slice().
The difference here is the second parameter specifies the length of the
extracted part.
Example:
let str = "Apple, Banana, Kiwi";
let part = console.log(str.substr(4,13));
Output:
"e, Banana, Ki"
If you omit the second parameter, substr() will slice out the rest
of the string.
Example:
let str = "Apple, Banana, Kiwi";
let part =console.log(str.substr(7));
Output:
"Banana, Kiwi“
If the first parameter is negative, the position counts from the end
of the string.
Example:
let str = "Apple, Banana, Kiwi";
let part =console.log(str.substr(-8));
Output:
"na, Kiwi"
Replacing String Content
replace() method
replace() method replaces a specified value with another value
in a string.
replace() method does not change the string it is called on. It
Example:
let text = "Good Morning!";
let newText = console.log(text.replace("Morning", "Evening"));
Output:
"Good Evening!“
replace() method replaces only the first match
Example:
let text = "Good Morning and Good Evening!";
let newText = console.log(text.replace("Good", "Great"));
Output:
"Great Morning and Good Evening!“
Example:
let text = "Good Morning!";
let newText = console.log(text.replace(/GOOD/i, "Great"));
Output: "Great Morning!“
Example:
let text1 = "Hello World!";
let text2 = console.log(text1.toUpperCase());
let text3 = console.log(text1.toLowerCase());
Output:
"HELLO WORLD!“
"hello world!“
concat() Method
concat() joins two or more strings.
Example:
let text1 = "Hello";
let text2 = "World";
let text3 = console.log(text1.concat(text2));
let text4 = console.log(text1.concat(" ", text2));
Output:
"HelloWorld"
"Hello World“
original string.
Strings are immutable. Strings cannot be changed, only
replaced.
String.trim()
trim() method removes whitespace from both sides of a string
Example:
let text = " Hello ";
console.log(text.trim())
Output:
"Hello"
Property Access:
Example:
let text = "HELLO WORLD";
let char = console.log(text[6]);
Output: "W"
Note:
It is read only. str[0] = "A" gives no error (but does not work!)
Example:
let text = "Hello";
let myArr = console.log(text.split(""));
Output: ["H", "e", "l", "l", "o"]
String Search
JavaScript methods for searching strings:
String.indexOf()
returns the position of the first occurrence of a specified text.
String.lastIndexOf()
returns the index of the last occurrence of a specified text in a string.
String.startsWith()
returns true if a string begins with a specified value, otherwise false.
String.endsWith()
returns true if a string ends with a specified value, otherwise false.
String.includes()
The includes() method returns true if a string contains a specified value
String.search()
The search() method searches a string for a specified value and returns the
function.
Example: var fruits = {
'apple' : 'red',
'mango' : 'yellow',
'guava' : 'green'
}
console.log(fruits['apple'])
Output: "red"
// Example2: create object inside object
let person = {
name : 'John',
tech : 'JS',
laptop : {
cpu : 'i7',
ram : '4GB',
brand : 'dell'
}
}
console.log(person) // to print entire object
console.log(person.tech) // to print tech
console.log(person.laptop.brand) // to print brand of the laptop
console.log(person.laptop.brand.length) // to print length of brand of the laptop
Array are special type of objects and new keyword can be used to
create array.
Example:
let arr = new Array(12,'apple', new Object());
console.log(arr)
console.log(typeof(arr))
Output: [12, "apple", { ... }]
"object"
Spaces and line breaks are not important. A declaration can
span multiple lines.
const cars = ["Saab", "Volvo", "BMW"];
You can also create an array, and then provide the elements.
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
The following example also creates an Array, assigns values to
it using new keyword.
const cars = new Array("Saab", "Volvo", "BMW");
Changing an Array Element
Example:
const fruits = ["orange", "apple", "cherry"];
fruits[0] = "mango";
console.log(fruits)
Output:
["mango", "apple", "cherry"]
Example:
const person = ["John", "Doe", 40];
console.log(person[1])
Output:
"Doe"
person[1] returns Doe
length Property
length property of an array returns the length of an array.
The length property is always one more than the highest array
index.
Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
console.log(length)
Output: 4
Array Methods
push and pop:
They are used to add and delete elements from last
respectively.
Example:
let arr1 = [1,2,3];
arr1.push(4);
console.log(arr1)
arr1.pop();
console.log(arr1)
Output: [1, 2, 3, 4]
[1, 2, 3]
Unshift and shift
They are used to add and delete elements from front respectively.
The unshift() method adds a new element to an array (at the
Example:
let arr2 = [3,4,6];
arr2.unshift(9);
console.log(arr2)
arr2.shift();
console.log(arr2);
Output: [9, 3, 4, 6]
[3, 4, 6]
Splice
Splice is used to add new elements in the array from specified to
existing arrays.
concat() method does not change the existing arrays. It always
Sorting an Array
The sort() method sorts an array alphabetically.
Example:
const fruits1 = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits1.sort())
console.log(fruits1.reverse())
Output:
Increment:
◦ To increase the value by 1
◦ Postfix : first assign and then increment
◦ Prefix : first increment and then assign
Example:
var a =2;
console.log(a++); //here a = 2
console.log(a); // here a=3
Decrement:
◦ To decrease the value by 1
◦ Postfix : first assign and then decrement
◦ Prefix : first decrement and then assign
Arithmetic operators
It comprises of all binary arithmetic operations like add,
subtract, multiply, divide, modulus and exponent.
Modulus operator returns the remainder when a is divided by
b i.e., (a%b).
Exponent operator returns the a to the power b i.e., (a**b)
Example:
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
console.log(x ,y ,z)
Output: 10, "55", "Hello5“
Note: If you add a number and a string, the result will be string.
let x = 16 + 4 + "Volvo";
Output: 20Volvo
// JavaScript treats 16 and 4 as numbers, until it reaches "Volvo"
let x = "Volvo" + 16 + 4;
Output: Volvo164
// the first operand is a string, all operands are treated as strings.
Note: JavaScript evaluates expressions from left to right.
Formatting numbers
toString() Method
converts a number to a string
specified length
Example:
let p = 9.656;
console.log(p.toPrecision());
console.log(p.toPrecision(2));
console.log(p.toPrecision(4));
console.log(p.toPrecision(6));
Output:
"9.656"
"9.7"
"9.656"
"9.65600"
valueOf() Method
valueOf() returns a number as a number.
Example:
let xx = 555;
console.log(xx.valueOf());
console.log((555).valueOf());
Output:
555
555
valueOf() method is used internally in JavaScript to convert
Example:
console.log(Number(true)); 1
console.log(Number(false)); 0
console.log(Number("10")); 10
console.log(Number(" 10")); 10
console.log(Number("10 ")); 10
console.log(Number(" 10 ")); 10
console.log(Number("10.33")); 10.33
console.log(Number("10,33")); NaN
console.log(Number("10 33")); NaN
console.log(Number("John")); NaN
parseInt() Method
parseInt() parses a string and returns a whole number. Spaces are
returned.
Example:
console.log(parseInt("-10")); -10
console.log(parseInt("-10.33")); -10
console.log(parseInt("10")); 10
console.log(parseInt("10.33")); 10
console.log(parseInt("10 20 30")); 10
console.log(parseInt("10 years")); 10
console.log(parseInt("years 10")); NaN
parseFloat() Method
parseFloat() parses a string and returns a number. Spaces are
returned
Example:
console.log(parseFloat("10")); 10
console.log(parseFloat("10.33")); 10.33
console.log(parseFloat("10 20 30")); 10
console.log(parseFloat("10 years")); 10
console.log(parseFloat("years 10")); NaN
Number Properties
MAX_VALUE
Returns the largest number
MIN_VALUE
Returns the smallest number
POSITIVE_INFINITY
Represents infinity (returned on overflow)
NEGATIVE_INFINITY
Represents negative infinity (returned on overflow)
NaN
Represents a "Not-a-Number" value
◦ = =allow type coercion i.e., one type can change into another at the
time of comparison
◦ === does not allow type coercion
◦ == equal value and === equal value and equal type
Note: console.log(NaN==NaN)
false
console.log(NaN===NaN)
false
console.log(+0 == -0)
true
console.log(+0 === -0)
true
Type Coercion
Type coercion -when we are comparing 2 values of different types, the
one type will force other to change it type as well so that comparison
can be made possible.
=== can stop coercion
if(1){} //1 will be converted to true
Object.is(param1,param2) is similar to === but it is different for some
cases such as
console.log(+0 == = -0)
◦ true
console.log(Object.is(+0,-0))
◦ false
console.log(NaN==NaN)
◦ false
console.log(Object.is(NaN , NaN))
◦ true
Example:
Output
a&&b : false
a||b : true
!a : false
Assignment and Ternary Operators
Assignment operator(=):
It is used to assign right hand side value to left hand side variable.
Ternary operator(?:):
It is an alternative of if else.
Condition is placed before ? and if evaluates to true then LHS of
colon gets executed else RHS of colon will.
Example:
var a=2;
console.log('a=2 : '+ (a=2));
console.log((a= =2) ? console.log("ok") : console.log("not ok"));
Output
a=2 : 2
ok
Special Operators
Operator Description
, Comma operator allows multiple expressions to be
evaluated as single statement
delete Delete operator deletes a property from the object
in In operator checks if object has the given property
instanceof Checks if the object is an instance of given type
new Creates an instance(object)
typeof Checks the type of a JavaScript variable
void It discards the expression’s return value
The typeof Operator
provides methods to get and set day, month, year, hour, minute
and seconds.
Constructor
You can use 4 variant of Date constructor to create date object.
Date()
Date(milliseconds)
Date(date String)
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. ECMAScript 5.
Example:
getTime()
The getTime() function returns the number of milliseconds
since then.
const d = new Date();
d.getTime();
Output: 1644040713710
The internal clock in JavaScript counts from midnight January
1, 1970.
getFullYear()
const d = new Date();
console.log(d.getFullYear());
Output: 2022
Set Date Methods
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)
Example:
Set Date methods let you set date values (years, months, days, hours,
minutes, seconds, milliseconds) for a Date Object.
setFullYear()
const d = new Date();
d.setFullYear(2020, 11, 3); console.log(d)
Output:
Thu Dec 03 2020 11:37:51 GMT+0530 (India Standard Time)
The setFullYear() method can optionally set month and day.
Please note that month counts from 0. December is month 11:
setDate()
d.setDate(d.getDate() + 50); console.log(d)
Output:
Fri Jan 22 2021 11:37:51 GMT+0530 (India Standard Time)
The setDate() method can be used to add days to a date.
// print date/month/year
<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script>
or
console.log("Date is: "+day+"/"+month+"/"+year);
Output:
Date is: 5/2/2022
built-in Math functions
Math Properties (Constants)
Syntax :
Math.property
Number to Integer:
There are 4 common methods to round a number to an integer
Math.sign(-4); //-1
Math.sign(0); //0
Math.sign(4); //1
Math.pow()
Math.pow(x, y) returns the value of x to the power of y
Math.sqrt(81); //9
Math.abs()
Math.abs(x) returns the absolute (positive) value of x
Math.abs(-5.98); //5.98
Math.min() and Math.max()
Math.min() and Math.max() can be used to find the lowest or
◦ 0.03817147708679558
◦ Note: Everytime when click on "Run" change the value
Math.random() always returns a number lower than 1
Random Integers
Math.floor(Math.random() * 10);
returns a random integer between 0 and 9 (both included)
9
Math.floor(Math.random() * 100);
returns a random integer between 0 and 99 (both included)
Math.floor(Math.random() * 10) + 1 ;
returns a random integer between 1 and 10 (both included)
Conditional Statements
It consist of 2 keywords- if and else
It is used when there are 2 paths possible depending upon a
condition.
If condition is true then if gets executed otherwise code in else
will get executed.
There can be multiple else if statements , if there are multiple
path of actions to be executed.
Syntax: if(condition) {
}
else if(condition) {
}
else {
}
<script type = "text/javaScript">
if (i < 15)
document.write("10 is less than
15");
else
document.write("I am Not in if");
</script>
<script type = "text/javaScript">
if (i == 10) {
// First if statement
if (i < 15)
document.write("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
document.write("i is smaller than 12 too");
else
document.write("i is greater than 15");
}
</script>
<script type = "text/javaScript">
if (i == 10)
document.write("i is 10");
else if (i == 15)
document.write("i is 15");
else if (i == 20)
document.write("i is 20");
else
document.write("i is not present");
</script>
JavaScript - if statement
var a =1 , b=6;
if(a+b == 11)
console.log("Equal to 11");
else if(a+b > 11)
console.log("more than 11");
else
console.log("Less than 11");
Output:
Good day
Nested if and else are possible
Syntax:
if(condition) {
if(condition) {
}
else {
}
}
switch (i)
{
case 0:
console.log("i is zero.");
break;
case 1:
console.log("i is one.");
break;
case 2:
console.log("i is two.");
break;
default:
console.log("i is greater than 2.");
}
</script>
The switch expression is evaluated once, depending upon the
answer evaluated by the condition, case code gets executed.
The value of the expression is compared with the values of each
case.
If there is a match, the associated block of code is executed.
If there is no match, the default code block is executed.
Output:
"current value of i : 0"
"current value of i : 1"
"current value of i : 2"
"current value of i : 3"
"current value of i : 4"
Note: Modify the above program to print even and odd numbers
for in
for in statement loops through the properties of an object.
Syntax:
for (key in object) {
Example:
Example:
let fruits = ['apple', 'orange', 'mango']
fruits.forEach(item => console.log(item));
Output:
"apple"
"orange"
"mango"
<p id="demo"></p>
<script>
const numbers = [45, 49, 16];
let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value) {
txt += value + "<br>";
}
</script>
Output:
45
49
16
for of
The for of statement loops through the values of an iterable object.
for of is used for iterables i.e., arrays and strings
Syntax:
for (variable of iterable) {
// code block to be executed
}
variable - For every iteration the value of the next property is assigned to the
variable. Variable can be declared with const, let, or var.
iterable - An object that has iterable properties.
Example:
let fruits = ['apple', 'orange', 'mango']
for(item of fruits) {
console.log(item);
}
Output:
"apple"
"orange"
"mango"
<p id="demo"></p>
<script>
let language = "Java";
let text = "";
for (let x of language) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
Output:
J
a
v
a
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:
while (i < 10) {
text += "The number is " + i;
i++;
}
the code in the loop will run, over and over again, as long as a variable
never end.
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);
The loop will always be executed at least once, even if the
Syntax:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
invoked.
Inside the function, the arguments (the parameters) behave as local
variables.
When JavaScript reaches a return statement, the function will stop
executing.
Accessing a function without () will return the function object instead of
function myFunction(a, b) {
return a / b; // Function returns the division of a and b
}
console.log(x)
Output: 1.3333333333333333
Local and Global variables
The scope of variables can be defined with their declaration, and
variables are declared mainly in two ways:
Global variables are mostly used in programming and useful for cases
function myFunction() {
console.log(typeof petName + "- " + "My pet name is " +
petName);
}
Local variables.
These variables can only be accessed within the function in which they are
declared.
The lifetime of the local variable is within its function only, which means
the variable exists till the function executes. Once function execution is
completed, local variables are destroyed and no longer exist outside the
function.
Example:
myfunction();
function myfunction() {
var petName = "Sizzer"; // local variable
console.log(typeof petName + " " + petName);
}
Variable petName is declared inside the function
Use Strict
Defines that JavaScript code should be executed in "strict
mode".
The purpose of "use strict" is to indicate that the code should
be executed in "strict mode".
With strict mode you cannot use undeclared variables.
All modern browsers support "use strict" except Internet
Explorer 9 and lower.
It is not a statement, but a literal expression, ignored by earlier
versions of JavaScript.
It helps you to write cleaner code, like preventing you from
using undeclared variables.
"use strict" is just a string, so IE 9 will not throw an error even
if it does not understand it.
Declaring Strict Mode
Example1:
"use strict";
x = 3.14; // This will cause an error because x is not declared
Example2:
"use strict";
myFunction();
function myFunction() {
y = 3.14; // This will also cause an error because y is not declared
}
Declared inside a function, it has local scope.
Only the code inside the function is in strict mode.
Example3:
x = 3.14; // This will not cause an error.
myFunction();
function myFunction() {
"use strict";
y = 3.14; // This will cause an error
}
JavaScript Window –
The Browser Object Model
Screen :
Information about the display capabilities of the client PC
Location :
Information on current URL.
Document :
Represents the current web page- the DOM.
The Window Object
Window is a global object, which means you don’t need to use its name to
access its properties and methods.
Example:
alert() is a method of the browser’s window object.
You can call alert() either with:
window.alert(“Hello”);
or just
alert(“Hello”);
Window Size
Two properties can be used to determine the size of the browser
window.
Both properties return the sizes in pixels:
(in pixels)
window.innerWidth - the inner width of the browser window
(in pixels)
Example
let w = window.innerWidth; console.log(w);
close()
closes the current window
moveTo()
move the current window
resizeTo()
resize the current window
alert()
displays the alert box containing message with ok button.
confirm()
displays the confirm dialog box containing message with ok and cancel button.
prompt()
displays a dialog box to get input from the user.
setTimeout()
performs action after specified time like calling function, evaluating
expressions
Window Screen
Properties:
screen.width : returns the width of the screen
screen.height : returns the height of the screen
screen.availWidth : returns the available width, in pixels, minus interface
features like the Windows Taskbar.
screen.availHeight : returns the available height, in pixels, minus interface
features like the Windows Taskbar.
screen.colorDepth : returns the color depth, i.e., number of bits used to
display one color
screen.pixelDepth : returns the pixel depth
Note: For modern computers, Color Depth and Pixel Depth are equal.
Window Location
Example:
window.location.assign("https://www.google.com")
reload() : reloads the current document
window.location.href:
returns the href (URL) of the current page
window.location.pathname:
returns the path and filename of the current page
window.location.protocol:
returns the web protocol used (http: or https: )
Window History
history object represents an array of URLs visited by the user i.e.,
contains the browsers history.
The window.history object can be written without the window prefix.
To protect the privacy of the users, there are limitations to how
JavaScript can access this object.
history methods:
history.back() - same as clicking back in the browser.
Navigator method:
javaEnabled()
The javaEnabled() method returns true if Java is enabled.
Popup Boxes
proceed.
The window.alert() method can be written without the window
prefix.
Syntax:
window.alert("sometext");
Confirm box
A confirm box is 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.
The window.confirm() method can be written without the
window prefix.
Syntax:
window.confirm("sometext");
Prompt box
A prompt box is used if you want the user to input a
in setTimeout().
window.clearTimeout(timeoutVariable)
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Timing</h2>
<p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>
<button onclick="setTimeout(myFunction, 3000);">Try it</button>
<script>
function myFunction() {
alert('Hello');
}
</script>
</body>
</html>
HTML- Hyper Text Markup Language
HTML is the standard markup language for Web pages.
With HTML you can create your own Website.
Elements.
HTML DOM properties are values (of HTML Elements) that you
programming languages.
In DOM, all HTML elements are defined as objects.
object.
A property is a value that you can get or set (like changing the
element).
With the object model, JavaScript gets all the power it needs
to create dynamic HTML:
◦ Document.getElementById Method
◦ innerHTML Property
◦ In the example above the getElementById method
used id="demo" to find the element.
getElementById() – Method
It is the fundamental method within the DOM for accessing
innerHTML - Property
It is the easiest way to get the content of an element.
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name Find elements by class name
)
Changing HTML Elements
Property Description
element.innerHTML = new html Change the inner HTML of an
content element
element.attribute = new value Change the attribute value of an
HTML element
element.style.property = new style Change the style of an HTML element
Method Description
element.setAttribute(attribute, value) Change the attribute value of an
HTML element
Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output
stream
<body>
<h2>JavaScript HTML DOM</h2>
<script>
const element = document.getElementsByTagName("p");
<body>
<p id="demo"></p>
<script>
const x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
</script>
</body>
Finding HTML elements by CSS selectors
To find all HTML elements that match a specified CSS selector (id, class
names, types, attributes, values of attributes, etc), use
the querySelectorAll() method.
This example returns a list of all <p> elements with class="intro".
<body>
<p class="intro">Hello World!.</p>
<p class="intro">This example demonstrates the <b>querySelectorAll</b>
method.</p>
<script>
const x = document.querySelectorAll("p.intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
</script>
</body>
Changing HTML Content
Content of an HTML element is modified by using
innerHTML property.
syntax:
document.getElementById(id).innerHTML = new HTML
Example1: changes the content of a <p> element
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>