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

JavaScript ppt

JavaScript is a programming language primarily used for web development, enabling interactivity on web pages through its core components: ECMAScript, DOM, and BOM. It can operate both on the client-side in browsers and server-side with environments like Node.js, and it supports various data types, operators, and control structures such as loops and functions. The document also covers variable declaration methods, object and array creation, and essential array methods for managing elements.

Uploaded by

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

JavaScript ppt

JavaScript is a programming language primarily used for web development, enabling interactivity on web pages through its core components: ECMAScript, DOM, and BOM. It can operate both on the client-side in browsers and server-side with environments like Node.js, and it supports various data types, operators, and control structures such as loops and functions. The document also covers variable declaration methods, object and array creation, and essential array methods for managing elements.

Uploaded by

Candy Man
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 123

JavaSCRIPT

Example
What is JavaScript?

 JavaScript is a programming language initially designed to interact


with elements of web pages. In web browsers, JavaScript consists of
three main parts:
 ECMAScript provides the core functionality.
 The Document Object Model (DOM)provides interfaces for
interacting with elements on web pages
 The Browser Object Model (BOM)provides the browser API for
interacting with the web browser.
 JavaScript allows you to add interactivity to a web page. Typically, you
use JavaScript with HTML and CSS to enhance a web page’s functionality,
such as validating forms, creating interactive maps, and displaying
animated charts
Client-side vs. Server-side JavaScript
• When JavaScript is used on a web page, it is executed in web browsers. In
this case, JavaScript works as a client-side language.

• JavaScript can run on both web browsers and servers. A popular JavaScript
server-side environment is Node.js Unlike client-side JavaScript, server-
side JavaScript executes on the server that allows you to access databases,
file systems, etc.
3 Places to put JavaScript code

1. Between the body tag of html


2. Between the head tag of html
3. In .js file (external javaScript)
JavaScript Variable

 A JavaScript variable is simply a name of storage location. There are


two types of variables in JavaScript : local variable and global variable.
 There are some rules while declaring a JavaScript variable (also known
as identifiers).
 Name must start with a letter (a to z or A to Z), underscore( _ ), or
dollar( $) sign.
 After first letter we can use digits (0 to 9), for example value1.
 JavaScript variables are case sensitive, for example x and X are different
variables.
Correct vs Incorrect JavaScript
variables
• Correct JavaScript • Incorrect JavaScript
variables variables var 123=30;
var x = 10; var *aa=320;
var _value="sonoo";
4 Ways to Declare a JavaScript Variable

 Using var
 Using let
 Using const
 Using nothing
When to Use JavaScript var?

 Always declare JavaScript variables with var,let, or const.


 The var keyword is used in all JavaScript code from 1995 to 2015.
 The let and const keywords were added to JavaScript in 2015.
 If you want your code to run in older browser, you must use var.
JavaScript Let

 The let keyword was introduced in ES6 (2015).


 Variables defined with let cannot be Redeclared.
 Variables defined with let must be Declared before use.
 Variables defined with let have Block Scope.
Block Scope
 Before ES6 (2015), JavaScript had only Global
Scope and Function Scope.
 ES6 introduced two important new JavaScript
keywords: let and const.

 These two keywords provide Block Scope in JavaScript.


 Variables declared inside a { } block cannot be accessed from
outside the block:
JavaScript Const

 The const keyword was introduced in ES6 (2015).


 Variables defined with const cannot be Redeclared.
 Variables defined with const cannot be Reassigned.
 Variables defined with const have Block Scope.
When to use JavaScript const?
 As a general rule, 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
Difference between var, let and const
keywords in JavaScript

var let const

It can be declared without It can be declared without It cannot be declared


initialization. initialization. without initialization.
JavaScript Operators

JavaScript operators are symbols that are used to perform


operations on operands. For example:

var sum=10+20;

Here, + is the arithmetic operator and = is the assignment operator.


There are following types of
operators in JavaScript.
1.Arithmetic Operators
2.Comparison (Relational) Operators
3.Bitwise Operators
4.Logical Operators
5.Assignment Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands.
The following operators are known as JavaScript arithmetic operators.

 Addition +,
 Subtraction -, ++ Increment

 Multiplication *, -- Decrement

 Division /,
 Remainder %,
JavaScript Comparison Operators

The JavaScript comparison operator compares the two operands. The comparison operators
are as follows:

Operator Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
JavaScript Logical Operators
The following operators are known as JavaScript logical operators.

Operator Description Example


&& Logical AND (10==20 && 20==33) =
false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.

Operator Meaning Description


a=b a=b Assigns the value of b to a.

a += b a=a+b Assigns the result


of a plus b to a.
a -= b a=a-b Assigns the result
of a minus b to a.
a *= b a=a*b Assigns the result
of a times b to a.
a /= b a=a/b Assigns the result
of a divided by b to a.
a %= b a=a%b Assigns the result
of a modulo b to a.
a &=b a=a&b Assigns the result
of a AND b to a.
a |=b a=a|b Assigns the result
of a OR b to a.
a ^=b a=a^b Assigns the result
of a XOR b to a.
a <<= b a = a << b Assigns the result
of a shifted left by b to a.

a >>= b a = a >> b Assigns the result


of a shifted right (sign
preserved) by b to a.
a >>>= b a = a >>> b Assigns the result
of a shifted right by b to a.
JavaScript Bitwise Operators

The bitwise operators perform bitwise operations on operands. The


bitwise operators are as follows:
Operator Description Example
& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10


<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2


JavaScript Type Operators

Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an
instance of an object type
Javascript Data Types

• JavaScript provides different data types to hold different types of values.


There are two types of data types in JavaScript.

1. Primitive data type


2. Non-primitive (reference) data type
 JavaScript is a dynamic type language, means you don't need to specify type

of the variable because it is dynamically used by JavaScript engine.


1)JavaScript primitive data types
• There are five types of primitive data types in JavaScript. They are
as follows

Data Type Description


String represents sequence of characters
e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false


or true

Undefined represents undefined value

Null represents null i.e. no value at all


2)JavaScript non-primitive data types
The non-primitive data types are as follows:

Data Type Description


Object represents instance through
which we can access members
Array represents group of similar values
RegExp represents regular expression
JavaScript Primitive vs. Reference Values
JavaScript Primitive vs. Reference Values
 Javascript has two types of values: primitive values and reference values.
 You can add, change, or delete properties to a reference value, whereas you
cannot do it with a primitive value.
 Copying a primitive value from one variable to another creates a separate value
copy. It means that changing the value in one variable does not affect the
other.
 Copying a reference from one variable to another creates a reference so that
two variables refer to the same object. This means that changing the object via
one variable reflects in another variable.
conditional statement

 Conditional statements help you to make a decision based on certain


conditions. These conditions are specified by a set of conditional
statements having boolean expressions which are evaluated to a
boolean value of true or false
JavaScript If-else

 If Statement
 If else statement
 if else if statement
JavaScript If statement

• It evaluates the content only if expression is true.

SYNTAX:

if (condition)
{ // statements to execute }
JavaScript If...else Statement
• It evaluates the content whether condition is true of false. The
syntax of JavaScript if-else statement is given below.
• Syntax:
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Flowchart of JavaScript If...else
statement
JavaScript If...else if statement

• It evaluates the content only if expression is true from


several expressions. The signature of JavaScript if else if
statement is given below.

Syntax:

if (condition1)
{ // ... }
else if (condition2)
{ // ... }
else if (condition3) { //... }
else { //... }
Flowchart of JavaScript If...elseif
statement
Switch statement in JavaScript

• Use this, if we want to execute bunch of codes for different condition. The
switch statement is similar to if…else statement.

switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
case value3:
statement3;
break;
default:
statement;
}
Flowchart of JavaScript Switch
What is loop in Example?

A loop is used for executing a block of statements repeatedly until a particular


condition is satisfied. For example, when you are displaying number from 1 to 100
you may want set the value of a variable to 1 and display it 100 times, increasing its
value by 1 on each loop iteration.
Different Kinds of Loops
 for - loops through a block of code a number of times
 while - loops through a block of code while a specified condition is true
 do/while - also loops through a block of code while a specified condition is true
 for/in - loops through the properties of an object
 for/of - loops through the values of an iterable object
1) JavaScript For loop

• The JavaScript for loop iterates the elements for the fixed
number of times. It should be used if number of iteration is
known.
Syntax:
for (initialization; condition; increment)
{
code to be executed
}
Flowchart of JavaScript for loop
2) JavaScript while loop

• The while loop loops through a block of code as


long as a specified condition is true.
Syntax:
while (condition)
{
code to be executed
}
Flowchart of JavaScript while &
dowhile loop
3) JavaScript 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);
JavaScript Break and Continue

 The break statement "jumps out" of a loop.


The continue statement "jumps over" one
iteration in the loop.
JavaScript Functions

JavaScript functions are used to perform operations. We can call JavaScript


function many times to reuse the code.

Advantage of JavaScript function

 There are mainly two advantages of JavaScript functions.


 Code reusability: We can call a function several times so it save coding.
 Less coding: It makes our program compact. We don’t need to write many
lines of code each time to perform a common task.
JavaScript Function Syntax

Syntax:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
JavaScript Functions
Function with Return Value:

 We can call function that returns a value and use it in our program.
 When JavaScript reaches a return statement, the function will stop
executing.

Syntax:
return expression;
JavaScript Objects
A JavaScript object is an entity having state and behavior (properties and
method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.

Creating Objects in JavaScript


There are 3 ways to create objects.

1) By object literal
2) By creating instance of Object directly (using new keyword)
3) By using an object constructor (using new keyword)
JavaScript Objects
1. By object literal
Syntax:
Objectname ={property1:value1,property2:value2..... propertyN:valueN }

Example:
<script>
const person={
firstName:"Mohana", lastName:"Priya", age:23,
phone:9876543210,address:"chennai"
};
</script>
2) By creating instance of Object

Syntax:
let objectname =new Object();

Example:
<script>
const employee=new Object();
employee.id=1001;
employee.name="Ashok";
employee.salary=16000;
</script>
3) By using an Object constructor
Syntax:

objectName.methodName();

Example:
<script>
const person={
firstName:"Dinesh",
lastName:"Kumar",
id:1005,
fullName:function(){
return this.firstName+" "+this.lastName;
}
};
</script>
JavaScript Array
JavaScript array is an object that represents a collection of similar type of
elements .

There are 3 ways to construct array in JavaScript


1) By array literal
2) By creating instance of Array directly (using new keyword)
3) By using an Array constructor (using new keyword)
JavaScript Array
1) JavaScript array literal
Syntax:
let arrayname=[value1,value2.....valueN];

Example:
const color=["Green","Red","Blue","Yellow"];
2) JavaScript Array directly (new keyword)

Syntax:
let arrayname=new Array();

Example:
const student_name=new Array();
3)By using an Array constructor (using new keyword)

Example:
<script>
const fruits=new Array("apple","Mango","pineapple");
document.getElementById("demo").innerHTML=fruits[1];
</script>
JavaScript Array Methods
Popping and Pushing
JavaScript Array pop()
• The pop() method removes the last element from an array

JavaScript Array push()


• The push() method adds a new element to an array (at the end)
JavaScript Array Methods
Shifting Elements
Shifting is equivalent to popping, but working on the first element instead of
the last.
 JavaScript Array shift()
The shift() method removes the first array element and "shifts" all other
elements to a lower index.
 JavaScript Array unshift()
The unshift() method adds a new element to an array (at the beginning), and
"unshifts" older elements
JavaScript Array Methods
 Changing Elements
• Array elements are accessed using their index number:
• Array indexes start with 0:
• [0] is the first array element
1 is the second
2 is the third ...
 JavaScript Array length
The length property provides an easy way to append a new element to an
array
JavaScript Array Methods
JavaScript Array delete():

• Array elements can be deleted using the JavaScript operator delete.


• Using delete leaves undefined holes in the array.

Merging (Concatenating) Arrays:

The concat() method creates a new array by merging (concatenating) existing arrays

Splicing and Slicing Arrays:

• The splice() method adds new items to an array.


• The slice() method slices out a piece of an array.
JavaScript Sorting Arrays

Sorting an Array
• The sort() method sorts an array alphabetically
Reversing an Array
• The reverse() method reverses the elements in an array.
JavaScript String

The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript


• By string literal
• By string object (using new keyword)
1) By string literal

1) By string literal
• The string literal is created using double quotes.

Syntax:
let stringname="string value";
2)By string object (using new keyword)

Example:
<script>
let x="javascript";
let y=new String("Javascript");
document.getElementById("demo").innerHTML=typeofx+"<br>"+typeof y;
</script>
Escape Character

Code Result Description


\' ' Single quote
\" " Double quote
\\ \ Backslash

Code Result

\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator
JavaScript String Methods

Method/Prop Description
charAt() Returns the character at a specified index (position)
charCodeAt() Returns the Unicode of the character at a specified index
concat() Returns two or more joined strings
constructor Returns the string's constructor function
endsWith() Returns if a string ends with a specified value
fromCharCode() Returns Unicode values as characters

includes() Returns if a string contains a specified value


indexOf() Returns the index (position) of the first occurrence of a value in a
string
lastIndexOf() Returns the index (position) of the last occurrence of a value in a
string
JavaScript String Methods
length Returns the length of a string
localeCompare() Compares two strings in the current locale
match() Searches a string for a value, or a regular expression, and
returns the matches
prototype Allows you to add properties and methods to an object

repeat() Returns a new string with a number of copies of a string

replace() Searches a string for a value, or a regular expression, and


returns a string where the values are replaced

search() Searches a string for a value, or regular expression, and


returns the index (position) of the match
JavaScript String Methods
slice() Extracts a part of a string and returns a
new string
split() Splits a string into an array of substrings
startsWith() Checks whether a string begins with
specified characters
substr() Extracts a number of characters from a
string, from a start index (position)
substring() Extracts characters from a string, between
two specified indices (positions)
toLocaleLowerCase() Returns a string converted to lowercase
letters, using the host's locale
toLocaleUpperCase() Returns a string converted to uppercase
letters, using the host's locale
JavaScript String Methods

toLowerCase() Returns a string converted to lowercase


letters
toString() Returns a string or a string object as a
string
toUpperCase() Returns a string converted to uppercase
letters
trim() Returns a string with removed
whitespaces
valueOf() Returns the primitive value of a string or a
string object
JavaScript Numbers

The JavaScript number object enables you to represent a numeric


value. It may be integer or floating-point.
Syntax:
let n=new Number(value);
JavaScript Numbers
Integer Precision
• Integers (numbers without a period or exponent notation) are
accurate up to 15 digits.
Floating Precision
• The maximum number of decimals is 17.
Adding Numbers and Strings
• JavaScript uses the + operator for both addition and concatenation.
• Numbers are added. Strings are concatenated.
NaN - Not a Number:
• NaN is a JavaScript reserved word indicating that a number is not a
legal number.
JavaScript Number Methods

Method Description
isFinite() Checks whether a value is a finite number
isInteger() Checks whether a value is an integer
isNaN() Checks whether a value is Number.NaN
isSafeInteger() Checks whether a value is a safe integer
toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the decimal point

toLocaleString() Converts a number into a string, based on the locale settings


toPrecision(x) Formats a number to x length
toString() Converts a number to a string
valueOf() Returns the primitive value of a number
JavaScript Number Properties

Property Description
constructor Returns the function that created JavaScript's Number
prototype
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a "Not-a-Number" value
POSITIVE_INFINITY Represents infinity (returned on overflow)
prototype Allows you to add properties and methods to an object
JavaScript Random
Math.random()
The JavaScript math random() method returns the random number
between 0 (inclusive) and 1 (exclusive).
Syntax:
Math.random()

Return
The random number between 0 (inclusive) and 1 (exclusive).
JavaScript Math Methods

Methods Description

abs() It returns the absolute value


of
the given number.
ceil() It returns a smallest integer
value, greater than or equal to
the given number.
floor() It returns largest integer value,
lower than or equal to the given
number.
JavaScript Math Methods

max() It returns maximum value of


the given numbers.
min() It returns minimum value of
the
given numbers.
pow() It returns value of base
to the power of
exponent.
random() It returns random number
between 0 (inclusive) and 1
(exclusive).
JavaScript Math random() method

The JavaScript math random() method returns the random number between 0 (inclusive) and 1
(exclusive).
Syntax
Math.random() Return
The random number between 0 (inclusive) and 1 (exclusive).
JavaScript Events

The change in the state of an object is known as an Event.


In html, there are various events which represents that some activity is
performed by the user or by the browser.
When javascript code is included in HTML, js react over these events and allow the
execution.
This process of reacting over the events is called Event Handling. Thus, js handles the HTML
events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task
to be performed on the event.
Mouse events

Event Performed Event Handler Description


click onclick When mouse click on an
element
mouseover onmouseover When the cursor of the
mouse comes over
the element
mouseout onmouseout When the cursor of the
mouse leaves an
element
mousedown onmousedown When the mouse
button is pressed
over the element
mouseup onmouseup When the mouse
button is released
over the element
Window/Document events

Event Performed Event Handler Description

load onload When the browser


finishes the
loading of the page
unload onunload When the visitor leaves the
current webpage, the
browser unloads it
resize onresize When the visitor resizes
the
window of the browser
Keyboard events

Event Performed Event Handler Description

Keydown & Keyup onkeydown When the user


press and then
& onkeyup release the key

Note: The onKeyDown event is triggered when the user presses a key. The
onKeyUp event is triggered when the user releases a key. The onKeyPress event
is triggered when the user presses & releases a key ( onKeyDown followed by
onKeyUp ).
Form events

Event Performed Event Handler Description

focus onfocus When the user focuses


on an element
submit onsubmit When the user submits the form
blur onblur When the focus is away
from a
form element
change onchange When the user modifies or
changes the value of a form
element
Browser Object Model

The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of window by
specifying window or directly.
For example:
window.alert("hello javatpoint");
is same as:
alert("hello javatpoint");
Window Object
• The window object represents a window in browser. An object of window is
created automatically by the browser.
• Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.
Methods of window object

Method Description

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.

open() opens the new window.


close() closes the current window.
setTimeout() performs action after specified time like
calling
function, evaluating expressions etc.
JavaScript Window History

•The window.history object contains the browsers history.


Some methods:
• history.back() - same as clicking back in the browser
• history.forward() - same as clicking forward in the browser
JavaScript Screen Object
• The JavaScript screen object holds information of browser screen. It can be
used to display screen width, height, colorDepth, pixelDepth etc.

No. Property Description

1 width returns the width of the screen

2 height returns the height of the screen

3 availWidth returns the available width

4 availHeight returns the available height

5 colorDepth returns the color depth

6 pixelDepth returns the pixel depth.


JavaScript Navigator Object

• The JavaScript navigator object is used for browser detection. It can be used to
get browser information such as appName, appCodeName, userAgent etc.
JavaScript Navigator Object

Strange enough, "Netscape" is the application name for both IE11, Chrome,
Firefox, and Safari.
"Mozilla" is the application code name for both Chrome, Firefox, IE, Safari,
and Opera.
Warning !!!
The information from the navigator object can often be misleading, and
should not be used to detect browser versions because:
 Different browsers can use the same name
 The navigator data can be changed by the browser owner
 Some browsers misidentify themselves to bypass site tests
Browsers cannot report new operating systems, released later than the
browser
JavaScript 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.
window.location.href returns the href (URL) of the current page
window.location.hostname returns the domain name of the web host
window.location.pathname returns the path and filename of the current page
window.location.protocol returns the web protocol used (http: or https:)
Window Object
What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.


The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-
neutral interface that allows programs and scripts to dynamically access
and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
The HTML DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model
of the page.
Document- is means it can be any file [e.g.: HTML ,XML .. etc]
Object -means (Tags Element) Eg: <h1> <img> .. etc
Model- Layout Structure (eg:HTML Structure)
The HTML DOM model is constructed as a tree of Objects
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
What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines:
 In the 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).
 In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
 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 innerHTML Property

The easiest way to get the content of an element is by using


the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML
elements.
The innerHTML property can be used to get or change any HTML element,
including <html> and <body>.
Differene between innerText and innerHTML

innerText innerHTML

Retrieves and sets the content Retrieves and sets the content
in plain text. in HTML format.
We can not insert We can insert the HTML tags.
the HTML tags.
It ignores the spaces. It considers the spaces.
It returns text without It returns a tag with
an inner element an inner element
tag. tag.
Finding HTML Elements

Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(nam Find elements by class name


e)
Changing HTML Elements

Property Description
element.innerHTML = new Change the inner HTML of
html content an element
element.attribute = new 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


JavaScript Array forEach()

The forEach() method calls a function for each element in an array.


Syntax:
array.forEach(function(currentValue, index, arr), thisValue)
Parameter
 callback - It represents the function that test the condition.
 currentvalue - The current element of array.
 index - It is optional. The index of current element.
 arr - It is optional. The array on which forEach() operated.
 thisArg - It is optional. The value to use as this while executing callback.
JavaScript Iterables

The For In Loop


 For in support both array and object type.
For in is useful when iterating all the items in a collection

Syntax
for (variable_name in object_name) //Here in is the keyword
{
// statement or block to execute
}
Example:
const fruits = ["apple", "orange", "cherry"];
const mobile={name:"Oppo",model:"A37",color:"Gold"};
JavaScript Iterables

for…of loop
Unlike the object literals, this loop is used to iterate the iterables (arrays,
string, etc.).
Syntax
for(variable_name of object_name) // Here of is a keyword
{
//statement or block to execute
}
In every iteration, one property from the iterables gets assigned to the
variable_name, and the loop continues till the end of the iteration.
. Arrow Functions

 Arrow functions allows a short syntax for writing function expressions.


 You don't need the function keyword, the return keyword, and the curly brackets
JavaScript Date Object

The JavaScript 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.
JavaScript Classes
JavaScript Class Syntax
 Use the keyword class to create a class.
 Always add a method named constructor()
Syntax
class ClassName {
constructor() { ... }
}
• A JavaScript class is not an object.
• It is a template for JavaScript objects.
JavaScript HTML DOM EventListener

The addEventListener() method


The addEventListener() method attaches an event handler to the specified
element.
The addEventListener() method attaches an event handler to an element
without overwriting existing event handlers.

Syntax:
element.addEventListener(event, function, useCapture);
Example
element.addEventListener("click", function(){ alert("Hello World!"); });
JavaScript HTML DOM EventListener

The removeEventListener() method


• The removeEventListener() method removes event handlers that have
been attached with the addEventListener() method
Example
element.removeEventListener("mousemove", myFunction);
JavaScript Maps

The JavaScript Map object is used to map keys to values. It stores


each element as key-value pair. It operates the elements such as
search, update and delete on the basis of specified key.
Syntax:
new Map([iterable])
Parameter
iterable - It represents an array and other iterable object whose
elements are in the form of key-value pair.
How to Create a Map

You can create a JavaScript Map by:


 Passing an Array to new Map()
 Create a Map and use Map.set()
Method Description
new Map() Creates a new Map
set() Sets the value for a key in a Map
get() Gets the value for a key in a Map
delete() Removes a Map element specified by the key
has() Returns true if a key exists in a Map
forEach() Calls a function for each key/value pair in a Map
entries() Returns an iterator with the [key, value] pairs in a Map
Property Description
size Returns the number of elements in a Map
JavaScript Set
 A JavaScript Set is a collection of unique values.
 Each value can only occur once in a Set.
How to Create a Set
You can create a JavaScript Set by:
Passing an Array to new Set()
Create a new Set and use add() to add values
Create a new Set and use add() to add variables
Method Description

new Set() Creates a new Set

add() Adds a new element to the Set


delete() Removes an element from a Set
has() Returns true if a value exists in the Set

forEach() Invokes a callback for each element in the Set

values() Returns an iterator with all the values in a Set

Property Description

size Returns the number of elements in a Set


JavaScript Closures

 A closure can be defined as a JavaScript feature in which the


inner function has access to the outer function variable.
 JavaScript variables can belong to the local or global scope.
 Global variables can be made local (private) with closures.
Javascript setTimeout()
The setTimeout() method executes a block of code after the specified time. The method
executes the code only once.
Syntax:
setTimeout(function, milliseconds);
JavaScript CallBack Function
 A function is a block of code that performs a certain task when called.
 In JavaScript, you can also pass a function as an argument to a function. This function
that is passed as an argument inside of another function is called a callback function.
JavaScript Promise
 A JavaScript Promise object contains both the producing code and calls to the
consuming code
 A Promise is an Objective that represents a task that will be complete in that will be
complete in the future.
Promise Syntax
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

myResolve(); // when successful


myReject(); // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)


myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);

You might also like