0% found this document useful (0 votes)
2 views

Javascript (1)

JavaScript is a dynamic, object-oriented scripting language primarily used for web development, enabling interactive content on websites. It supports various features such as compatibility with HTML/CSS, multiple data types, and is widely used in web applications and presentations. The language was created by Brendan Eich in 1995 and has evolved with standards maintained by ECMA, with the latest version being ES2020.

Uploaded by

agarwalnaman445
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Javascript (1)

JavaScript is a dynamic, object-oriented scripting language primarily used for web development, enabling interactive content on websites. It supports various features such as compatibility with HTML/CSS, multiple data types, and is widely used in web applications and presentations. The language was created by Brendan Eich in 1995 and has evolved with standards maintained by ECMA, with the latest version being ES2020.

Uploaded by

agarwalnaman445
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 216

JAVASCRIPT

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

 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
Features of JavaScript
 All popular web browsers support JavaScript as they
provide built-in execution environments.
 JavaScript follows the syntax and structure of the C
programming language. Thus, it is a structured
programming language.
 JavaScript is an object-oriented programming language that
uses prototypes rather than using classes for inheritance.
 It is a light-weighted and interpreted language.
 It is a case-sensitive language.
 JavaScript is supportable in several operating systems
including, Windows, macOS, etc.
 It provides good control to the users over the web browsers.
History
 JavaScript founder was Brendan Eich and developed in 1995
by Netscape.
 JavaScript name was later changed to 'mocha' and 'livescript'
but it still remains JavaScript due to some trademark reasons.
 Node JS is a engine, Node JS is not a programming
language, but it allows developers to use JavaScript, which is
a programming language that allows users to build web
applications.
 Node js is an open-source and cross-platform runtime
environment for executing JavaScript code outside a
browser.
Applications
 Websites:
JavaScript lets you add behavior to the web page where the
page responds to actions without loading a new page to request
processing. It enables the website to interact with visitors and
execute complex actions.
 Web Applications:
JavaScript gained the ability to create robust web applications.
Example: Google Maps
to explore a map in Google Maps, all you have to do is click and
drag with the mouse. You will see the part of the map that is less
detailed and then fills itself in. That’s the work of JavaScript
behind the scene.
 Presentations:
A very popular use of JavaScript is to create presentations as
websites. Using the Reveal.js framework, this becomes easy if
you are familiar with HTML and CSS.
Tools
 For working with JavaScript we need 2 things:

◦ 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

◦ 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">
console.log(".....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="homefile.js">
</script>
<body>
</body>
</html>
-----JavaScript file-----
console.log("connected with external javascript file ");
Online Editors
 https://codepen.io/
 https://scrimba.com/scrim/c66yyHm
 https://jsfiddle.net/jar9ntq5/

 Visual studio code


◦ Install Code runner (from VS)
◦ Install node (from https://nodejs.org/en/download/)
◦ To run program: Terminal  node file_name.js
Why HTML/CSS/JS….?
Web Designers vs Developers
Comments
 Comments are extra info that helps in understanding of code
and is not passed on to compiler at compilation.
 It is used to add information about the code, warnings or
suggestions so that end user can easily interpret the code.
 There are 2 types of comment
◦ Single line
 // This is a single line comment
◦ In-line
 Var num = 12; //in-line comment
◦ Multi line
 /* This is
a multi line
comment */
Example:

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

 JS is weakly typed- type coercions is allowed in JS


◦ 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.
◦ Use === (triple equals) to stop coercion
Variables
 Variable is a name of a memory location where the data is
stored.
Syntax:
◦ var varname = value ;
 In JavaScript, variable is defined using var keyword

◦ var name = “ Anil “;


◦ var reg_no = 50
◦ var marks = 90.5
◦ let y = 123e5; // 12300000
◦ let z = 123e-5; // 0.00123
Naming Convention
 Variable names should begin with a letter, $ or an underscore
‘_‘.
 First character can be letter, $ or _ followed by any
combination of letters or digits.
 A variable name cannot be any keyword as they are reserved
for special purposes.
 Variable names are case sensitive, for example x and X are
different variables.
 Example:
◦ valid : xyz, _name, $address, Name123
◦ invalid: 12name, *reg_no, @mail
Declare a variable

There are 3 ways to declare a variable in JavaScript.


 var : Declares a variable

 let : Declares a block variable

 const : Declares a block constant

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

Programmers have used different ways of joining multiple words into


one variable name:
 Underscore: (snake casing rule)

first_name, last_name, master_card, inter_city.


 Upper Camel Case (Pascal Case): (camel casing rule)

FirstName, LastName, MasterCard, InterCity.


 Lower Camel Case:
 JavaScript programmers tend to use camel case that starts with a

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.

 Variables defined with let have Block Scope.

Example:
let x = "John Doe";
let x = 0;
// SyntaxError: 'x' has already been declared

Note: With var you can redeclare a variables anywhere in a


program.
Example:
var x = "John Doe";
var x = 0;
Block Scope

 JavaScript had only Global Scope and Function Scope.


 let and const, these two keywords provide Block Scope in

JavaScript.
 Variables declared inside a { } block cannot be accessed from

outside the block:


Example:
 {

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

outside the block.


Example:
{
var x = 2;
}
// x can be used here
 Redeclaring a variable using the var keyword can impose
problems.
 Redeclaring a variable inside a block will also redeclare the

variable outside the block:


Example:
var x = 10;
// Here x is 10

{
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
}
Note: Outside the block x =2.
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.

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.

A const variable cannot be reassigned:


Example:
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
Output:
TypeError: Assignment to constant variable.
 JavaScript const variables must be assigned a value when they are
declared.
Correct:
const PI = 3.14159265359;
Incorrect:
const PI;
PI = 3.14159265359;

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.

 Data types are divided into 2 categories:


◦ Primitive
There are 5 primitive data types in JavaScript:
Number, String, Boolean, Undefined, Null
◦ Non primitive
◦ Object, Array, RegExp(regular expressions)
JavaScript primitive data types

Data Type Description


Number Represents numeric values
Example: 10
String Represents sequence of characters
Example: “welcome”

Boolean Represents boolean value either true or false


Undefined Represents undefined value
Null Represents null
i.e., no value at all
JavaScript non-primitive data types

Data Type Description

Object Represents instance through which we can


access members
Array Represents group of similar values
RegExp Represents regular expression
(/i-case insensitive, /g- global)
Primitive Data Type- Number
 It is used to store integer and floating point numbers
 Example:
◦ var a = 23;
◦ var b = 44.54;
◦ var c = -90;
◦ let num1 = 0xf // hexadecimal number ; here output = 15
◦ let num2 = 1.5e12 // exponential number
◦ let num3 = 100_00_000 // separate the zeros in number using underscores
◦ console.log(typeof(c)); Output: "number"

Primitive Data Type- String


 It is used to store sequence of characters
 Example:
◦ var S = "Hello";
◦ console.log(S) ;
◦ console.log(typeof(S));
Output: "Hello"
"string"
var name = “anil”;
console.log(name + “ is 24 years old”)
console.log(`${name} is 24 years old`)
Output: "anil is 24 years old"
"anil is 24 years old"

Primitive Data Type- Boolean


 It is used to assign a variable with either true or false

 Example:

var isValid = true;


console.log(isValid);
Output: true
Primitive Data Type- undefined
◦ It is used to specify a value of a variable which is not defined

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

 undefined and null are equal in value but different in type

 typeof undefined // undefined


typeof null // object

null === undefined // false


null == undefined // true
Examples
let x = 5; let y = 5; let z = 6;
(x == y) // Returns true
(x == z) // Returns false
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
// The object (person) in the example above has 4 properties:
firstName, lastName, age, and eyeColor

let car; // Value is undefined, type is undefined


// Any variable can be emptied, by setting the value to undefined.
The type will also be undefined.

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

let answer1 = "It's alright";


Output: It's alright
let answer2 = "He is called 'Johnny'";
Output: He is called 'Johnny'
let answer3 = 'He is called "Johnny"';
Output: He is called "Johnny"

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.

Code Result Description


\' ' inserts a Single quote in a string.
\" " inserts a Double quote in a string.
\\ \ inserts a Backslash in a string.
Quoting Strings with Single Quotes

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:

"<a href='http:\www.example.com' target = '_blank'> Link</a>"


"<a href='http:\www.example.com' target = '_blank'> Link</a>"
 A double-quoted string can have single quotes without
escaping them, conversely, a single-quoted string can have
double quotes within it without having to escape them.

 Double quotes ( \" ) must escape a double quote and vice versa
single quotes ( \' ) must escape a single quote.

 Advantage of using backticks (` `) is that it is no longer


necessary to escape double quotes ( "" ) or single quotes ( '' )
Strings as Objects

 JavaScript strings are primitive values, created from literals.


let x = "John"; // x is string
 strings can also be defined as objects with the keyword new.
let y = new String("John"); // y is object

let x = "John";
let y = new String("John");
console.log(x==y)
Output: true

let x = new String("John");


let y = new String("John");
console.log(x==y)
Output: false

Note: Comparing two JavaScript objects always returns false.


String Methods
 There are 3 methods for extracting a part of a string:
◦ slice(start, end)
◦ substring(start, end)
◦ substr(start, length)
slice() Method:
 slice() extracts a part of a string and returns the extracted part

in a new string.
 The method takes 2 parameters: the start position, and the end

position (end not included).


 Example: let str = "Apple, Banana, Kiwi";

let part = console.log(str.slice(4, 13));


Output: "e, Banana"
 JavaScript counts positions from zero and from left to right.
 If a parameter is negative, the position is counted from the end of

the string i.e., from right to left.


Example for negative indexing:
let str = "Apple, Banana, Kiwi";
let part = console.log(str.slice(-15, -8));
Output:
"e, Bana"
Note: If you omit the second parameter, the method will slice out the
rest of the string.
let part = console.log(str.slice(6));
Output: " Banana, Kiwi“
let part = console.log(str.slice(-10));
Output: "nana, Kiwi"
substring() Method
 substring() is similar to slice().

 The difference is substring() cannot accept negative indexes.

 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

returns a new string.

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!“

 By default, the replace() method is case sensitive.


Example:
let text = "Good Morning!";
let newText = console.log(text.replace("GOOD", "Great"));
Output:
“Good Morning!“
//Writing GOOD (with upper-case) will not work
 To replace case insensitive, use a regular expression with
an /i flag (insensitive).
 regular expressions are written without quotes.

Example:
let text = "Good Morning!";
let newText = console.log(text.replace(/GOOD/i, "Great"));
Output: "Great Morning!“

 To replace all matches, use a regular expression with a /g flag


(global match)
Example:
let text = "Good Morning and Good Evening!";
let newText = console.log(text.replace(/Good/g, "Great"));
Output: "Great Morning and Great Evening!"
Upper and Lower Case

A string is converted to upper case with toUpperCase() and is


converted to lower case with toLowerCase()

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.

 The concat() method can be used instead of the plus operator.

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“

 The below two lines do the same operation.


text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");
Note:
 All string methods return a new string. They don't modify the

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!)

 If you want to work with a string as an array, you can convert it to an


array.
 A string can be converted to an array with the split() method

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

position of the match


Non Primitive Data Type- Object
 Object can be created in 2ways in JavaScript
◦ Object literal
◦ New keyword
Object literal:
 Object is a collection of key value pairs. It is defined within curly

braces{}. Object represents real entities.


 It has key value pair, where value can be some property or

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

// to delete properties (laptop)


delete person.tech
console.log(person)
Object comparison
 ==, === and Object.is() used to check referential equality.
 Example:
let animal = new Object();
let cat = animal;
let dog = animal;
cat == dog // same object reference
Output: true
let horse = new Object(); // new address allocated
cat == horse
Output: false
cat === horse
Output: false
Object.is(cat, horse);
Output: false
 To compare the content you either have to implement yourself
or you can use JSON.stringify
 Example:
JSON.stringify(cat) = = = JSON.stringify(horse)
Output: true

console.log(+0 == -0); Output: true


console.log(+0 === -0) Output: true
console.log(Object.is(+0,-0)) Output: false
Constant Objects and Arrays

 The keyword const does not define a constant value. It defines


a constant reference to a value.

 Using const you cannot:


Reassign a constant value
Reassign a constant array
Reassign a constant object

 Using const you can:


Change the elements of constant array
Change the properties of constant object
Constant Arrays

You can change the elements of a constant array:


Example:
// create a constant array:
const cars = ["Saab", "Volvo", "BMW"];

cars[0] = "Toyota"; // change an element:

cars.push("Audi"); // add an element:


Output: Toyota, Volvo, BMW, Audi

 But you cannot reassign the array:


Example:
 const cars = ["Saab", "Volvo", "BMW"];

cars = ["Toyota", "Volvo", "Audi"]; // ERROR


Output: TypeError: Assignment to constant variable.
Constant Objects

You can change the properties of a constant object:


Example:
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};
car.color = "red"; // Change a property
car.owner = "Johnson"; // Add a property:
// Display the property:
console.log("Car owner is " + car.owner);
Output:
Car owner is Johnson

But you cannot reassign the object:


Example:
const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR
Output: TypeError: Assignment to constant variable.
Arrays
 It is used to store ordered data together.
 It is defined within square brackets( [ ] ) and can have

elements of different types.


 It is a common practice to declare arrays with
the const keyword.
 Array indexes start with 0 , and array element can be accessed

by referring to the index number.


Syntax:
const array_name = [item1, item2, ...];
Example:
var a=[1,true,'hello']
a[2]
Output: "hello"
 You can also leave some position
var a=[2,3,,4]
a[2]
Output: undefined
a
Output: (4)[2, 3, empty, 4]

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

 Arrays use numbers to access its "elements"


Arrays are Objects
 Arrays are a special type of objects.
 Objects use names to access its "members“

 You can have objects in an Array. You can have functions in

an Array. You can have arrays in an Array


Example:
const person1 = {firstName:"John", lastName:"Doe", age:46};
console.log(person1.firstName)
Output:
"John"
 person1.firstName returns John
Array Properties

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

beginning), and "unshifts" older elements


 The shift() method returns the value that was "shifted out“.

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

and from index


let arr3 = [2,5,6,4,9];
console.log(arr3)
arr3.splice(1,3, "hi");
console.log(arr3)
Output: [2, 5, 6, 4, 9]
[2, "hi", 9]
Note: Elements from 1 to 3 (both are inclusive)are replaced by hi
 Splice can be used to delete the elements from the array.

let arr4 = [14,2,3,5]


arr4.splice(1,3);
console.log(arr4)
Output: [14]
Slice
Slice help to create new array from existing array
Example:
let arr5 = [1,2,5,6,4];
let arr6 = arr5.slice(1,3);
console.log(arr5)
console.log(arr6)
Output: [1, 2, 5, 6, 4]
[2, 5]
Note: Elements from index 1 (inclusive) to 3 (exclusive) are
assigned to arr6.
concat() method
 Merging (Concatenating) Arrays

 concat() method creates a new array by merging (concatenating)

existing arrays.
 concat() method does not change the existing arrays. It always

returns a new array.


Example: Merging Three Arrays
const arr1 = ["John", "Peter"];
const arr2 = ["Rohan", "Riya", "Rohit"];
const arr3 = ["Robin", "Morgan"];
const myChildren = arr1.concat(arr2, arr3);
console.log(myChildren)
Output:
["John", "Peter", "Rohan", "Riya", "Rohit", "Robin", "Morgan"]
Example: Merging an Array with Values
const arr2 = ["Rohan", "Riya", "Rohit"];
const myChildren = arr2.concat("Peter");
Output:
["Rohan", "Riya", "Rohit", "Peter"]

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:

["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< arr.length ; i++)
console.log(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<emp.length;i++){
console.log(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
 It needs one operand
 There are 2 major operators:
◦ Increment
◦ Decrement
Both have 2 variations of postfix and prefix

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

console.log(++a); // here a=4


console.log(a); // a= 4

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:

console.log("a+b: " + (100+5)); //"a+b: 105"


console.log("a/b: " + (10/5)); //"a/b: 2"
console.log("a%b: " + (10%5)); //"a%b: 0"
console.log("a**b: "+ (10**5)); //"a**b: 100000"
Example:
let x = "100";
let y = "10";
let z1 = x / y;
let z2= x * y;
let z3 = x - y;
 JavaScript will try to convert strings to numbers in all numeric
operations

let z4 = x + y; //this will not work


 JavaScript uses the + operator to concatenate the strings
Adding Strings and Numbers

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

 All number methods can be used on any type of numbers

(literals, variables, or expressions)


Example:
let d = 369;
console.log(d.toString());
console.log((369).toString());
console.log((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;
console.log(f.toExponential(2));
console.log(f.toExponential(4));
console.log(f.toExponential(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;
console.log(m.toFixed(0));
console.log(m.toFixed(2));
console.log(m.toFixed(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;
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

Number objects to primitive values.


 There is no reason to use it in your code.
Converting Variables to Numbers

 There are 3 JavaScript methods that can be used to convert


variables to numbers:
Number() method
Returns a number, converted from its argument.
parseInt() method
Parses its argument and returns an integer
parseFloat() method
Parses its argument and returns a floating point number
Number() Method
 Number() can be used to convert JavaScript variables to numbers.
 If the number cannot be converted, NaN (Not a Number) is returned.

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

allowed. Only the first number is returned.


 If the number cannot be converted, NaN (Not a Number) is

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

allowed. Only the first number is returned.


 If the number cannot be converted, NaN (Not a Number) is

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

 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:
 console.log(x = 1 / 0);
Infinity
 console.log(x = -1 / 0);
-Infinity
 console.log(x = Number.POSITIVE_INFINITY);
Infinity
 console.log(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;
console.log("a<<b : "+ (a<<b)); // multiply by 2, left shift
console.log("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: 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:

console.log('2= ="2" : '+ (2= ="2"));


console.log('2= = ="2" : '+ (2= = ="2"));
console.log('2!="2" : '+ (2!="2"));
console.log('2!= ="2" : '+ (2!= ="2"));
console.log('2>"2" : '+ (2>"2"));
console.log('2>="2" : '+ (2>="2"));
console.log('2<"2" : '+ (2<"2"));
console.log('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
2<="2" : true
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;
console.log('a & b : '+ (a&b)); // “ a & b : 0”
console.log('a|b : '+ (a|b)); // “a | b : 10”
console.log('a^b : '+ (a^b)); // “ a^ b : 10”
console.log('~a : '+ (~a)); //”~a : -9”
Logical Operators
 Used for conditions comparison that checks for the validity of
condition and specifies the course of action to be taken.
 They are also used in loops as part of termination conditions.
 If the first condition is enough to give the final verdict, it will
not evaluate the second one.
 3 operators are there:
◦ && -logical AND, returns true when both conditions
evaluates to true
◦ || -logical OR, returns true when either of the conditions
evaluates to true
◦ ! -logical not, return true when condition evaluates to
false
Example:

var a=true, b=false;


console.log('a&&b : '+ (a&&b));
console.log('a||b : '+ (a||b));
console.log('!a : '+ (!a));

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

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, 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

Math.E // returns Euler's number


Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Math Methods
Syntax:
Math.method(number)

Number to Integer:
 There are 4 common methods to round a number to an integer

Math.round(x) : Returns x rounded to its nearest integer


Math.ceil(x) : Returns x rounded up to its nearest integer
Math.floor(x) : Returns x rounded down to its nearest
integer
Math.trunc(x) : Returns the integer part of x
Examples:
 Math.round(4.6); 5
Math.round(5.5); 6
Math.round(4.4); 4
 Math.ceil(3.9); 4
Math.ceil(4.7); 5
Math.ceil(4.1); 5
Math.ceil(-4.2); -4
 Math.floor(4.4); 4
Math.floor(4.2); 4
Math.floor(-4.2); -5
 Math.trunc(4.2); 4
Math.trunc(-4.2); -4
Math.sign()
 Math.sign(x) returns if x is negative, null or positive

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.pow(9, 2); //81


Math.sqrt()
 Math.sqrt(x) returns the square root of x

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

highest value in a list of arguments


Math.max(20, 0, 45, 200, 99); //200
Math.min(20, 0, 45, 200, 99); //0
Math.random()
 Math.random() returns a random number between 0
(inclusive), and 1 (exclusive)
 Math.random();

◦ 0.03817147708679558
◦ Note: Everytime when click on "Run" change the value
Math.random() always returns a number lower than 1
Random Integers

 Math.random() used with Math.floor() can be used to return random


integers. i.e., to create a numbers with no decimals.

 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">

// JavaScript program to illustrate If statement


var i = 10;

if (i > 15) document.write("10 is less than 15");

// This statement will be executed


// as if considers one statement by default
document.write("I am Not in if");
</script>
<script type = "text/javaScript">

// JavaScript program to illustrate If-


else statement
var i = 10;

if (i < 15)
document.write("10 is less than
15");
else
document.write("I am Not in if");
</script>
<script type = "text/javaScript">

// JavaScript program to illustrate nested-if statement


var i = 10;

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">

// JavaScript program to illustrate nested-if statement


var i = 20;

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

 It evaluates the content only if expression is true.


Syntax:
if(expression){
//content to be evaluated
}
Example:
var a1=20;
if(a1>10){
console.log("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){
console.log("a is even number");
}
else{
console.log("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)
console.log("Equal to 11");
else if(a+b > 11)
console.log("more than 11");
else
console.log("Less than 11");

Output: "Less than 11"


 If time is less than 10:00, create a "Good morning" greeting, if
not, but time is less than 20:00, create a "Good day" greeting,
otherwise a "Good evening":

if (time < 10) {


greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

Output:
Good day
 Nested if and else are possible
 Syntax:
if(condition) {
if(condition) {
}
else {
}
}

◦ There can be if without else but vice versa is not true


◦ Example: if(2==2)
console.log("They are equal");
Output: "They are equal"
Conditional Statements- switch
 It is an elegant way to replace multiple else-if statements
 Syntax:
switch(expression)
{
case val: //code block
break;
case val: //code block
break;
case val: //code block
break;
default: //code block
}
<script type = "text/javascript">

// JavaScript program to illustrate switch-case


let i = 9;

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.

 every case must be followed by break unless it is required not to


as per logic. Otherwise, all cases will start executing from the
matched case till either break is encountered or all cases gets
exhausted.
 default is optional and holds the code which should be executed
if no cases gets matched. It is similar to else statement.
 val can be integer, char or String in JavaScript.
Example:
var day="sun";
switch(day)
{
case "mon": console.log("Today is Monday"); break;
case "tues": console.log("Today is Tuesday"); break;
case "wed": console.log("Today is Wednesday"); break;
case "thurs": console.log("Today is Thursday"); break;
case "fri": console.log("Today is Friday"); break;
case "sat": console.log("Today is Saturday"); break;
case "sun": console.log("Today is Sunday"); break;
default : console.log("day is invalid!");
}
Output: "Today is Sunday"
<script> /*This example uses the weekday number to calculate the
weekday name */
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>
Output: Today is Sunday (Note: Displays actual day when executed)
Loops
 Loops are used to do a repeated task until a specified
condition remains true.

 Different types of loops are


 For loop
◦ For each
◦ For of
◦ For in
 While loop
 Do-while loop
for - Loop
 It is best to use for loop when we know that the code should be
executed specified number of times.
Syntax:
for( initialization; condition; increment){
//code block to be executed
}
◦ initialization - used to initialize the variable, which is being used
for iteration. It is executed once before the code block gets
executed.
◦ condition - defines condition which determine till when iteration
will continue. i.e., how many times you want to execute the
statements within this block.
◦ increment - executed every time after the code block has been
executed.
Example:
for(var i=0;i<5;i++)
console.log("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]+" ";
}
console.log(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) {
console.log(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)
console.log(key, person[key])

// to access only properties of laptop


for(let key in person.laptop)
console.log(key, person.laptop[key])
for in over Arrays:
 for in statement can also loop over the properties of an Array.

Syntax: for (variable in array) {


code
}
Example:
const numbers = [44, 9, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x];
}
Output:
44
9
25
Note:

 Do not use for in over an Array if the index order is


important.
 array values may not be accessed in the order you expect.
 use a for loop, a for of loop, or Array.forEach() when the
order is important.
for each
 Array.forEach() method calls a function once for each
array element.
 It is used when each element has to be accessed (parsed)

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

(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 Error: When a user makes a mistake in the pre-defined


syntax of a programming language, a syntax error may appear.

 Runtime Error: When an error occurs during the execution of the


program, such an error is known as Runtime error. The codes
which create runtime errors are known as Exceptions. Thus,
exception handlers are used for handling runtime errors.

 Logical Error: An error which occurs when there is any logical


mistake in the program that may not produce the desired output,
and may terminate abnormally. Such an error is known as Logical
error.
Exception Handling Statements
 These are following statements that handle if any exception occurs:
try: The try statement lets you test a block of code for errors.
catch: The catch statement lets you handle the error.
finally: The finally statement lets you execute code, after try
and catch, regardless of the result.
Syntax:
try{
expression;
}
catch(error){
expression;
}
finally{
expression; } //Executable code
 try{} statement: the code which needs possible error testing is kept
within the try block. If any error occur, it passes to the catch{} block
for taking suitable actions and handle the error. Otherwise, it
executes the code written within.

 catch{} statement: This block handles the error of the code by


executing the set of statements written within the block. This block
contains either the user-defined exception handler or the built-in
handler. This block executes only when any error-prone code needs
to be handled in the try block. Otherwise, the catch block is skipped.

 finally{} :Finally is an optional block of statements which is


executed after the execution of try and catch statements. Finally
block does not hold for the exception to be thrown. Any exception is
thrown or not, finally block code, if present, will definitely execute.
It does not care for the output too.
<p>You cannot evaluate code that contains a syntax error:</p>
<p id="demo"></p>
<script>
try {
eval("alert('Hello)");
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</script>
Output: SyntaxError
 cannot evaluate code that contains a syntax error.
<p>You cannot convert a number to upper case:</p>
<script>
let num = 1;
try {
num.toUpperCase();
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</script>
Output: TypeError

 A TypeError is thrown if you use a value that is outside the range


of expected types
Functions
 A function is a block of code designed to perform a particular task.
 A function is executed when "something" invokes it (calls it).
 Variables defined inside a function are not accessible (visible) from outside the
function.
 Variables declared with var, let and const are quite similar when declared inside
a function.

Syntax:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}

◦ A JavaScript function is defined with the function keyword, followed by a name


and parentheses ().
◦ Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).
◦ The code to be executed, by the function, is placed inside curly brackets: {}
 Function parameters are listed inside the parentheses () in the function
definition.
 Function arguments are the values received by the function when it is

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

the function result.


Function Invocation
 The code inside the function will execute when
"something" invokes (calls) the function:
 When an event occurs (when a user clicks a button)

 When it is invoked (called) from JavaScript code

 Automatically (self invoked)


Example1:
function myfunc() {
console.log("Hello World!!!")
}
myfunc()
Output: Hello World!!!

Example2: Passing values to functions with Arguments


function myfuncwitharg(a,b) {
console.log(a*b)
}
myfuncwitharg(10,5)
Output: 50
Example3:

//Calculate the product of two numbers, and return the result:


var x = myFunction(4, 3);
// Function is called, return value will end up in x

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 Variable: Outside of all the functions


 Local Variable: Within a function block

 The main difference between Global and local variables is that


global variables can be accessed globally in the entire program,
whereas local variables can be accessed only within the function
or block in which they are defined.
Global Variable
 Global variables are those variables which are declared outside of all the

functions or block and can be accessed globally in a program.


 It can be accessed by any function present in the program.

 Global variables are mostly used in programming and useful for cases

where all the functions need to access the same data.


Example:
var petName = "Rocky"; //global variable
myFunction();

function myFunction() {
console.log(typeof petName + "- " + "My pet name is " +
petName);
}

console.log(typeof petName + "- " + "My pet name is " +


petName);
Local Variable
 Variables that are declared within or inside a function block are known as

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

 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

 The Browser Object Model (BOM) allows JavaScript to


interact with the browser.
 All browsers are split into different parts or objects that can be
accessed using JavaScript. Collectively these parts are known
as BOM.
 At the very top of the browser hierarchy is the window object.
Browser default object is the window object and this
represents the entire browser.
 Effectively the window object is the browser.
 Underneath window object there are lot of other objects.
Other BOM objects are children of the window object.
Navigator :
 Represents information about the Browser and the underlying OS.

Screen :
 Information about the display capabilities of the client PC

running the Browser.


History :
 Information on recently visited sites.

Location :
 Information on current URL.

Document :
 Represents the current web page- the DOM.
The Window Object

 The window object is supported by all browsers. It represents the browser's


window.
 All global JavaScript objects, functions, and variables automatically become
members of the window object.
 Global variables are properties of the window object.
 Global functions are methods of 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:

 window.innerHeight - the inner height of the browser window

(in pixels)
 window.innerWidth - the inner width of the browser window

(in pixels)
Example
 let w = window.innerWidth; console.log(w);

let h = window.innerHeight; console.log(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()
 performs action after specified time like calling function, evaluating

expressions
Window Screen

 The window.screen object contains information about the user's screen.


The window.screen object can be written without the window prefix.
 It can be used to display screen width, height, colorDepth, pixelDepth etc.

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

 The window.location object can be used to get the current page


address (URL) and to redirect the browser to a new page.
Location methods:
 assign() : loads a new document

Example:
window.location.assign("https://www.google.com")
 reload() : reloads the current document

 replace() : replaces the current document with a new one.


Location Properties( attributes):
 window.location.hostname:

returns the domain name of the web host

 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.

- method loads the previous URL in the history list.


 history.forward() - 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 window.navigator object contains information about the

visitor's browser and can be written without window prefix.


Navigator properties:
navigator.cookieEnabled: returns true if cookies are enabled.
navigator.appName: returns application name of the browser.
- "Netscape" is the application name for both IE11, Chrome,
Firefox, and Safari.
navigator.appCodeName: returns the application code name of the
browser.
- "Mozilla" is the application code name for both Chrome, Firefox,
IE, Safari, and Opera.
navigator.product: returns the product name of the browser engine.
- Most browsers returns "Gecko" as product name !!
navigator.appVersion: returns version information about the browser.
navigator.userAgent: returns the user-agent header sent by the
browser to the server.
navigator.platform: returns the browser platform (operating system).
navigator.language: returns the browser's language
navigator.onLine: returns true if the browser is online

Navigator method:
javaEnabled()
The javaEnabled() method returns true if Java is enabled.
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 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

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");
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.

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.

To Stop the Execution:


 The clearTimeout() method stops the execution of the function specified

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.

<!DOCTYPE html> // Defines the document type


<html>
<head> // Contains metadata/information for the
document
<title>Page Title</title>
</head>
<body> // Defines the document's body
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
HTML - DOM

 DOM - Document Object Model


 When a web page is loaded, browser creates a DOM of the page.
 The HTML DOM is a standard object model and programming
interface for HTML.
 The DOM is a W3C (World Wide Web Consortium) standard.
 The DOM defines a standard for accessing documents.
 It defines:
The HTML elements as objects
The properties of all HTML elements
The methods to access all HTML elements
The events for all HTML elements
 The HTML DOM is a standard for how to get, change, add, or
delete HTML elements.
The HTML DOM model is constructed as a tree of Objects:
HTML DOM Methods
 HTML DOM methods are actions you can perform on HTML

Elements.
 HTML DOM properties are values (of HTML Elements) that you

can set or change.


The DOM Programming Interface
 The HTML DOM can be accessed with JavaScript and with other

programming languages.
 In DOM, all HTML elements are defined as objects.

 The programming interface is the properties and methods of each

object.
 A property is a value that you can get or set (like changing the

content of an HTML element).


 A method is an action you can do (like add or deleting an HTML

element).
 With the object model, JavaScript gets all the power it needs
to create dynamic HTML:

◦ JavaScript can change all the HTML elements in the page


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

 The following example changes the content (the innerHTML)


of the <p> element with id="demo":

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


<script>
document.getElementById("demo").innerHTML = "Hello
World!";
</script>

◦ 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

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
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

Adding Events Handlers


document.getElementById(id).onclick = function(){code}
 Adding event handler code to an onclick event
HTML DOM Elements

 To find and access HTML elements in an HTML page, you


have to find the elements first.

 There are several ways to achieve this:


Finding HTML elements by id
Finding HTML elements by tag name
Finding HTML elements by class name
Finding HTML elements by CSS selectors
Finding HTML elements by HTML object collections
Finding HTML elements by id
• finds the element with id="intro“:
 If the element is found, the method will return the element as an
object.
 If the element is not found, myElement will contain null.
Example:
<p id="intro">Finding HTML Elements by Id</p>
<p>This example demonstrates the <b> getElementsById </b>
method.</p>
<p id="demo"></p>
<script>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is: " +
element.innerHTML;
</script>
 Finding HTML elements by Tag Name
 This example finds all <p> elements

<body>
<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Tag Name.</p>


<p>This example demonstrates the <b>getElementsByTagName</b>
method.</p>
<p id="demo" > </p>

<script>
const element = document.getElementsByTagName("p");

document.getElementById("demo").innerHTML = 'The text in first


paragraph (index 0) is: ' + element[0].innerHTML;
</script>
</body>
 Finding HTML elements by class Name
 To find all HTML elements with the same class name, use getElementsByClassName().
 This example returns a list of all elements with class="intro".

<body>

<p class="intro">Hello World!</p>


<p class="intro">This example demonstrates the
<b>getElementsByClassName</b> method.</p>

<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>

<p id="demo"> </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>

 The HTML document above contains a <p> element with id="p1"


 We use the HTML DOM to get the element with id="p1"
 A JavaScript changes the content (innerHTML) of that element to
"New text!"
Example2: changes the content of an <h1> element

<h1 id="id01">Old Heading</h1>


<script>
const element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>

 The HTML document above contains an <h1> element with id="id01"


 We use the HTML DOM to get the element with id="id01"
 A JavaScript changes the content (innerHTML) of that element to "New
Heading“
 JavaScript changed "Old Heading" to "New Heading".
document.write()
 In JavaScript, document.write() can be used to write directly
to the HTML output stream.
Example:
<body>
<script>
document.write(Date());
</script>
</body>

Note: Never use document.write() after the document is loaded.


It will overwrite the document.
Changing the Value of an Attribute
syntax:
document.getElementById(id).attribute = new value
Example: This example changes the value of the src attribute of
an <img> element

<img id="image" src="image_scream.jpg" width="160" height="120">


<script>
document.getElementById("image").src = "lotus.jpg";
</script>
 The HTML document above contains an <img> element
with id=“image"
 We use the HTML DOM to get the element with id=“image"
 A JavaScript changes the src attribute of that element from "
image_scream.jpg " to "lotus.jpg"

You might also like