Eth Presentation Java Script
Eth Presentation Java Script
Java Script
What is JavaScript?
● 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
● [Link] is used to print content on console
JavaScript via Script Tag
● <script> tag is used for writing JavaScript in HTML directly
● Every [Link]() will print the output in console of browser
● Here we are using sublime editor
● Open sublime
● Save file as .html extension
● Type html and press tab, it will display skeleton of html
● Include <script> tag
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> JS </title>
</head>
<h1> "First JS code" </h1>
<script type="text/javascript">
[Link](".....hello world!!!. .... ");
</script>
<body>
</body>
</html>
JavaScript via External File
● JavaScript code is written in a separate file and is incorporated
in the html using <script> tag.
● This is the most efficient way.
● It enforces reusability and keeps code short, simple and easy to
understand
● <script> tag can be added in head section (JavaScript file will
be loaded earlier than webpage) or body section (JavaScript file
will be rendered after your webpage is loaded)
-----html file----- Output:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> JS </title>
</head>
<h1> "first file" </h1>
<script type="text/javascript“ src="homefi[Link]">
</script>
<body>
</body>
</html>
-----JavaScript file-----
[Link]("connected with external javascript file ");
Online Editors
● [Link]
● [Link]
● [Link]
Output:
JavaScript Properties
Example:
var myName = “Nihal”
myName = 32
let Name = “hello”
const pi = 3.14
var x; // declaring a variable x
[Link](x)
Output: undefined
x = 10; //Assigning 10 to x which was already declared
[Link](x)
Output: 10
● var y = 4; // assigning a value 4 to a variable y
{
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 variable outside the block:
Example:
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
With let, redeclaring a variable in the same block is NOT
allowed.
Example:
var x = 2; // Allowed
let x = 3; // Not allowed
{
let x = 2; // Allowed
let x = 3 // Not allowed, we will get SyntaxError
}
Redeclaring a variable with let, in another block, is allowed:
Example:
let x = 2; // Allowed
{
let x = 3; // Allowed
}
{
let x = 4; // Allowed
}
Let Hoisting
● 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.
let car = ""; // The value is "", the typeof is "string "
// An empty string has both a legal value and a type.
Primitive Data Type - Symbol
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 = fi[Link]; //to return length of string
[Link](firstName+lastName)
[Link](firstName+ " "+ lastName)
[Link](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.
Escaping Literal Quotes in Strings
Escape Character
var myStr = "Good \"morning!!!\" Have a good day"
[Link](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.
Code Result Description
\' ' inserts a Single quote in a
\" " string. a Double quote in a
inserts
\\ \ string. a Backslash in a
inserts
string.
Quoting Strings with Single Quotes
var Str =
"<a href=\"http:\\[Link]\" target = \"_blank\"> Link</a>“
var Str1 =
`'<a href="http:\\[Link]" target = "_blank"> Link</a>'`
[Link](Str)
[Link](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");
[Link](x==y)
Output: true
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 = [Link]([Link](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 =[Link]([Link](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 =[Link]([Link](-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 returns a new string.
Example:
let text = "Good Morning!";
let newText = [Link]([Link]("Morning", "Evening"));
Output:
"Good Evening!“
● replace() method replaces only the first match
Example:
let text = "Good Morning and Good Evening!";
let newText = [Link]([Link]("Good", "Great"));
Output:
"Great Morning and Good Evening!“
Example:
let text1 = "Hello World!";
let text2 = [Link]([Link]());
let text3 = [Link]([Link]());
Output:
"HELLO WORLD!“
"hello world!“
concat() Method
● concat() joins two or more strings.
● The concat() method can be used instead of the plus operator.
Example:
let text1 = "Hello";
let text2 = "World";
let text3 = [Link]([Link](text2));
let text4 = [Link]([Link](" ", text2));
Output:
"HelloWorld"
"Hello World“
[Link]()
● trim() method removes whitespace from both sides of a string
Example:
let text = " Hello ";
[Link]([Link]())
Output:
"Hello"
Property Access:
Example:
let text = "HELLO WORLD";
let char = [Link](text[6]);
Output: "W"
Note:
It is read only. str[0] = "A" gives no error (but does not work!)
Example:
const person = ["John", "Doe", 40];
[Link](person[1])
Output:
"Doe"
● person[1] returns Doe
● Arrays use numbers to access its "elements"
Arrays are Objects
Sorting an Array
● The sort() method sorts an array alphabetically.
Example:
const fruits1 = ["Banana", "Orange", "Apple", "Mango"];
[Link]([Link]())
[Link]([Link]())
● Output:
["Apple", "Banana", "Mango", "Orange"]
["Orange", "Mango", "Banana", "Apple"]
Array printing
● Array can be printed using for, for each, for in , for of.
For
arr = [23,5,45,12]
for(let i=0 ; i< [Link] ; i++)
[Link](arr[i]+" ");
Output:
23
5
45
12
Example 2:
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<[Link];i++){
[Link](emp[i] + " ");}
Output:
Arun
Varun
John
Operators
JavaScript operators are symbols that are used to
perform
operations on operands.
Unary
Arithmetic
Shift
Relational
Bitwise
Logical
Assignment
Ternary
Unary Operators
Increment:
● To increase the value by 1
● Postfix : first assign and then increment
● Prefix : first increment and then assign
Example:
var a =2;
[Link](a++); //here a = 2
[Link](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
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
● All number methods can be used on any type of
numbers (literals, variables, or expressions)
Example:
let d = 369;
[Link]([Link]());
[Link]((369).toString());
[Link]((300 + 69).toString());
Output:
"369"
"369"
"369"
toExponential() Method
● toExponential() returns a string, with a number
rounded and written using exponential notation.
Example:
let f = 9.656;
[Link]([Link](2));
[Link]([Link](4));
[Link]([Link](5));
Output:
"9.66e+0"
"9.6560e+0"
"9.65600e+0"
toFixed() Method
● toFixed() returns a string, with the number written with a
specified number of decimals.
Example:
let m = 8.658;
[Link]([Link](0));
[Link]([Link](2));
[Link]([Link](4));
Output:
"9"
"8.66"
"8.6580"
toPrecision() Method
● toPrecision() returns a string, with a number written with a
specified length
Example:
let p = 9.656;
[Link]([Link]());
[Link]([Link](2));
[Link]([Link](4));
[Link]([Link](6));
Output:
"9.656"
"9.7"
"9.656"
"9.65600"
valueOf() Method
● valueOf() returns a number as a number.
Example:
let xx = 555;
[Link]([Link]());
[Link]((555).valueOf());
Output:
555
555
● valueOf() method is used internally in JavaScript to
convert Number objects to primitive values.
● There is no reason to use it in your code.
Converting Variables to Numbers
Example:
[Link](parseInt("-10")); -10
[Link](parseInt("-10.33")); -10
[Link](parseInt("10")); 10
[Link](parseInt("10.33")); 10
[Link](parseInt("10 20 30")); 10
[Link](parseInt("10 years")); 10
[Link](parseInt("years 10")); NaN
parseFloat() Method
● parseFloat() parses a string and returns a number.
Spaces are allowed. Only the first number is returned.
● If the number cannot be converted, NaN (Not a Number)
is returned
Example:
[Link](parseFloat("10")); 10
[Link](parseFloat("10.33")); 10.33
[Link](parseFloat("10 20 30")); 10
[Link](parseFloat("10 years")); 10
[Link](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
● NaN is a reserved word indicating that a number is not a legal
number.
● Trying to do arithmetic with a non-numeric string will result in
NaN
Example:
● [Link](x = 1 / 0);
Infinity
● [Link](x = -1 / 0);
-Infinity
● [Link](x = Number.POSITIVE_INFINITY);
Infinity
● [Link](x = Number.NEGATIVE_INFINITY);
-Infinity
● Using a Number property on a variable, expression, or
value, will return undefined
Compound Assignment with Augmented arithmetic
operation
● var a = 5;
● var b = 3;
● var c = 8;
● a = a+10; can be written as a+=10
● b = b-2; can be written as b-=2
● c = c * 5; can be written as c*=5
● a = a /5; can be written as a/=5
Shift operators
● Shift operator shift the bits by specified number of times
in either left or right direction
● Two variations of shift are possible left and right shift
left shift: shift bits in left direction for specified value
right shift: shift bits in right direction for specified value
● Example:
var a=8,b=2;
[Link]("a<<b : "+ (a<<b)); // multiply by 2, left shift
[Link]("a>>b : "+ (a>>b)); // divide by 2, right shift
Output
a<<b : 32
a>>b : 2
Relational operators
● It comprises operators for comparisons. Output will be in
Boolean format.
● There are operators to check inequality i.e., < ,>, <=, >=
● For equality check, we have 2 operators i.e., = = and !=
● Difference between = = and = = =
● = =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: [Link](NaN==NaN)
false
[Link](NaN===NaN)
false
[Link](+0 == -0)
true
[Link](+0 === -0)
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
● [Link](param1,param2) is similar to === but it is
different for some cases such as
● [Link](+0 == = -0)
● true
● [Link]([Link](+0,-0))
● false
● [Link](NaN==NaN)
● false
● [Link]([Link](NaN , NaN))
● true
Example:
[Link]('2= ="2" : '+ (2= ="2"));
[Link]('2= = ="2" : '+ (2= = ="2"));
[Link]('2!="2" : '+ (2!="2"));
[Link]('2!= ="2" : '+ (2!= ="2"));
[Link]('2>"2" : '+ (2>"2"));
[Link]('2>="2" : '+ (2>="2"));
[Link]('2<"2" : '+ (2<"2"));
[Link]('2<="2" : '+ (2<="2"));
Output
2=="2" : true
2==="2" : false
2!="2" : false
2!=="2" : true
2>"2" : false
2>="2" : true
2<"2" : false
Bitwise Operators
● It computes by going bit by bit
● Bits of both operand is checked irrespective of what first
operand bit is. 4 major bit operators are:
● & -bitwise and, returns 1 if both bits are 1 else 0.
● | -bitwise or, returns 1 if either of bits is 1 else 0.
● ^ -bitwise xor, returns 1 if both bits are different else 0.
● ~ -bitwise not, changes 1 to 0 and vice versa.
Example:
var a=8,b=2;
[Link]('a & b : '+ (a&b)); // “ a & b : 0”
[Link]('a|b : '+ (a|b)); // “a | b : 10”
[Link]('a^b : '+ (a^b)); // “ a^ b : 10”
[Link]('~a : '+ (~a)); //”~a : -9”
Logical Operators
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;
[Link]('a=2 : '+ (a=2));
[Link]((a= =2) ? [Link]("ok") : [Link]("not
ok"));
Output
a=2 : 2
ok
Special Operators
Operator Description
, Comma operator allows multiple expressions
delete to be evaluated
Delete operator as
deletes
singlea statement
property from the
in object
In operator checks if object has the given
propertyif the object is an instance of given
Checks
instanceof
new type
Creates an instance(object)
typeof Checks the type of a JavaScript variable
void It discards the expression’s return value
The typeof Operator
● the typeof operator is used to find the data type of a
JavaScript variable.
Example:
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John',age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object"
Note:
● The data type of NaN is number
● The data type of an array is object
● The data type of a date is object
● The data type of null is object
● The data type of an undefined variable is
undefined *
● The data type of a variable that has not been
assigned a value is also undefined *
Date Object
● date object can be used to get year, month and day.
● You can display a timer on the webpage by the help of
JavaScript date object.
● You can use different Date constructors to create date
object. It 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)
● Date(year, month, day, hours, minutes, seconds,
milliseconds)
Date Methods
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,
getDay() 1970)
Get the weekday as a number (0-6)
[Link]() Get the time. ECMAScript 5.
Example:
getTime()
● The getTime() function returns the number of
milliseconds since then.
const d = new Date();
[Link]();
Output: 1644040713710
● The internal clock in JavaScript counts from midnight
January 1, 1970.
getFullYear()
const d = new Date();
[Link]([Link]());
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();
[Link](2020, 11, 3); [Link](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()
[Link]([Link]() + 50); [Link](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=[Link]();
var month=[Link]()+1;
var year=[Link]();
[Link]("<br>Date is: "+day+"/"+month+"/"+year);
</script>
or
[Link]("Date is: "+day+"/"+month+"/"+year);
Output:
Date is: 5/2/2022
built-in Math functions
Syntax:
[Link](number)
Number to Integer:
● There are 4 common methods to round a number to an integer
● Math.floor([Link]() * 10);
returns a random integer between 0 and 9 (both included)
9
● Math.floor([Link]() * 100);
returns a random integer between 0 and 99 (both included)
● Math.floor([Link]() * 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)
[Link]("10 is less than 15");
else
[Link]("I am Not in if");
</script>
<script type = "text/javaScript">
if (i == 10) {
// First if statement
if (i < 15)
[Link]("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
[Link]("i is smaller than 12 too");
else
[Link]("i is greater than 15");
}
</script>
<script type = "text/javaScript">
if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present");
</script>
JavaScript - if statement
● It evaluates the content only if expression is true.
Syntax:
if(expression){
//content to be evaluated
}
Example:
var a1=20;
if(a1>10){
[Link]("value of a is greater than 10");
}
Output:
"value of a is greater than 10"
JavaScript - if...else Statement
● It evaluates the content whether condition is true of false.
Syntax:
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Example:
var a=18;
if(a%2==0){
[Link]("a is even number");
}
else{
[Link]("a is odd number");
}
Output: "a is even number"
JavaScript if...else if statement
● It evaluates the content only if expression is true from several expressions.
Syntax:
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
Example:
var a =1 , b=6;
if(a+b == 11)
[Link]("Equal to 11");
else if(a+b > 11)
[Link]("more than 11");
else
[Link]("Less than 11");
Output:
Good day
● Nested if and else are possible
● Syntax:
if(condition) {
if(condition) {
}
else {
}
}
switch (i)
{
case 0:
[Link]("i is zero.");
break;
case 1:
[Link]("i is one.");
break;
case 2:
[Link]("i is two.");
break;
default:
[Link]("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.
for(var i=0;i<5;i++)
[Link]("current value of i : "+i);
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) {
// code block to be executed
}
Example:
const person = {fname:"John", lname:"Doe", age:25};
let text = "";
for (let x in person) {
text += person[x]+" ";
}
[Link](text)
Output: "John Doe 25 "
● for in loop iterates over a person object.
● Each iteration returns a key (x)
● The key is used to access the value of the key
● The value of the key is person[x]
● Example:
let fruits = ['apple', 'orange', 'mango']
for(item in fruits) {
[Link](item);
}
Output:
"0"
"1"
"2"
let person = {
name : 'John',
tech : 'JS',
laptop : {
cpu : 'i7',
ram : '4GB',
brand : 'dell'
}
}
// to access all the properties of person
for(let key in person)
[Link](key, person[key])
Example:
let fruits = ['apple', 'orange', 'mango']
for(item of fruits) {
[Link](item);
}
Output:
"apple"
"orange"
"mango"
<p id="demo"></p>
<script>
let language = "Java";
let text = "";
for (let x of language) {
text += x + "<br>";
}
[Link]("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 (i) is less than 10.
● If you forget to increase the variable used in the condition, the
loop will 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 condition is false, because the code block is
executed before the condition is tested.
Example:
do {
text += "The number is " + i;
i++;
}
while (i < 10);
Output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
Break
● The break statement "jumps out" of a loop.
Example:
for (let i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
Output:
The number is 0
The number is 1
The number is 2
Note:
the break statement ends the loop, when the loop counter,
i is 3.
Continue
● The continue statement "jumps over" one iteration in
the loop.
Example:
for (let i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
Output:
The number is 0
The number is 1
The number is 2
The number is 4
Note:
A loop will skip the step when i = 3.
Exception handling
● When executing code, different errors can occur.
● Errors can be coding errors made by the programmer,
errors due to wrong input, and other unforeseeable
things.
● Exception handling is a process or method used for
handling the abnormal statements in the code and
executing them. It also enables to handle the flow
control of the code/program.
● For example, the Division of a non-zero value with
zero will result into infinity always, and it is an
exception. Thus, with the help of exception handling,
it can be executed and handled.
Types of Errors:
While coding, there can be three types of errors in the code:
Syntax:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
function myFunction(a, b) {
return a / b; // Function returns the division of a
and b
}
[Link](x)
Local and Global variables
function myFunction() {
[Link](typeof petName + "- " + "My pet name is " +
petName);
}
function myfunction() {
var petName = "Sizzer"; // local variable
[Link](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
● Strict mode is declared by adding "use strict"; to the beginning
of a script or a function.
● Declared at the beginning of a script, it has global scope.
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
● 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:
[Link](“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:
● [Link] - the inner height of the browser window
(in pixels)
● [Link] - the inner width of the browser window
(in pixels)
Example
● let w = [Link]; [Link](w);
let h = [Link]; [Link](h);
Output:
578
248
Window Methods
open()
● opens a new window
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()
Window Screen
● The [Link] object contains information about the user's
screen. The [Link] object can be written without the
window prefix.
● It can be used to display screen width, height, colorDepth,
pixelDepth etc.
Properties:
[Link] : returns the width of the screen
[Link] : returns the height of the screen
[Link] : returns the available width, in pixels, minus
interface features like the Windows Taskbar.
[Link] : returns the available height, in pixels, minus
interface features like the Windows Taskbar.
[Link] : returns the color depth, i.e., number of bits used
to display one color
[Link] : returns the pixel depth
Window Location
● [Link]:
returns the href (URL) of the current page
● [Link]:
returns the path and filename of the current page
● [Link]:
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 [Link] 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:
● [Link]() - same as clicking back in the browser.
- method loads the previous URL in the history list.
● [Link]() - same as clicking forward in the browser
- method loads the next URL in the history list.
Note:
There are only 1 property of history object.
● length- returns the length of the history URLs.
Window Navigator
● navigator object is used for browser detection. It can be used
to get browser information such as appName,
appCodeName, userAgent etc.
● The [Link] object contains information about the
visitor's browser and can be written without window prefix.
Navigator properties:
[Link]: returns true if cookies are enabled.
[Link]: returns application name of the browser.
- "Netscape" is the application name for both IE11, Chrome,
Firefox, and Safari.
[Link]: returns the application code name of
the browser.
- "Mozilla" is the application code name for both Chrome,
Firefox, IE, Safari, and Opera.
[Link]: returns the product name of the browser
engine.
- Most browsers returns "Gecko" as product name !!
[Link]: returns version information about the
browser.
[Link]: returns the user-agent header sent by the
browser to the server.
[Link]: returns the browser platform (operating
system).
[Link]: returns the browser's language
[Link]: returns true if the browser is online
Navigator method:
javaEnabled()
Popup Boxes
JavaScript has three kind of popup boxes:
1. Alert box
2. Confirm box
3. Prompt box
Alert box
● An alert box is 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.
● The [Link]() method can be written without the window
prefix.
Syntax:
[Link]("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 [Link]firm() method can be written without the
window prefix.
Syntax:
[Link]firm("sometext");
Prompt box
● A prompt box is 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:
[Link]("sometext","defaultText");
Note:
Line Breaks
● To display line breaks inside a popup box, use a back-slash followed by
the character n.
Example:
alert("Hello\nHow are you?");
Output:
Hello
How are you?
Timing Events
● JavaScript can be executed in time-intervals. This is called timing
events.
● The window object allows execution of code at specified time
intervals.
● [Link] 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 elements on the page.
● Accesses any element on the page via its ID attribute.
● The most common way to access an HTML element is to
use the id of the element.
● This method will returns single element.
innerHTML - Property
● It is the easiest way to get the content of an element.
● It is used to get and replace the content of HTML
elements
HTML DOM Document
● The HTML DOM document object is the owner of all other
objects in web page.
● The document object represents your web page.
● If you want to access any element in an HTML page, you
always start with accessing the document object.
Finding HTML Elements
Method Description
[Link](id) Find an element by element id
[Link](na Find elements by tag name
me)
[Link](na Find elements by class name
me)
Changing HTML Elements
Property Description
[Link] = new html Change the inner HTML of an
content
[Link] = new value element
Change the attribute value of an
[Link] = new style HTML
Changeelement
the style of an HTML
Method element
Description
[Link](attribute, Change the attribute value of an
value) HTML element
Adding and Deleting Elements
Method Description
[Link](elem Create an HTML element
ent)
[Link](elemen Remove an HTML element
t)
[Link](elemen Add an HTML element
t)
[Link](new, Replace an HTML element
old)
[Link](text) Write into the HTML output
stream
<body>
<h2>JavaScript HTML DOM</h2>
<script>
const element = [Link]("p");
<body>
<p id="demo"></p>
<script>
const x = [Link]("intro");
[Link]("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
</script>
</body>
Finding HTML elements by CSS selectors
<body>
<p class="intro">Hello World!.</p>
<p class="intro">This example demonstrates the
<b>querySelectorAll</b> method.</p>
<script>
const x = [Link]("[Link]");
[Link]("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' +
x[0].innerHTML;
Changing HTML Content
● Answer:
c) It will throw an errorExplanation:
Variables declared with var inside a function have function scope, so they can’t be
accessed outside
Page #:
Quiz Question
● Priya wrote a loop using var i. Later she logs i outside the loop
and sees it prints a [Link] she used let instead, what would
happen?
a) i is still accessible and prints value
b) i will throw ReferenceError
c) i will be null
d) i will reset to 0
● Answer:
b) i will throw ReferenceError
Explanation: let has block scope unlike var.
Page #:
Quiz Question
● Anil writes:
[Link](a);
var a = 10;
What will be logged?
a) 10
b) Undefined
c) Error
d) null
● Answer:
b) undefined
Explanation: var is hoisted but initialized with undefined.
Page #:
Quiz Question
● Answer:
b) It works due to hoisting
Explanation: Function declarations are hoisted.
Page #:
Quiz Question
● Answer: b)
Arrow functions use lexical this.
Page #:
Quiz Question
● Answer: b) pop()
Page #:
Quiz Question
Page #:
Quiz Question
● Ravi writes:
const obj = {name:"JS"};
[Link] = "JavaScript";
What happens?
a) Error: Cannot reassign constant
b) Value updates to "JavaScript“
c) Undefined
d) Runtime crash
Page #:
Quiz Question
● Meera gets API response:
{"name":"Raj","age":25}
How should she convert this string into an object?
a) toJSON()
b) [Link]()
c) [Link]()
d) parseJSON()
● Answer: c) [Link]()
Page #:
Quiz Question
● Rahul writes:
[Link]("title").innerHTML = "Hello";
Page #:
QUESTIONS?
Page #:
Page #: