0% found this document useful (0 votes)
19 views266 pages

BasicofJS Merged

Uploaded by

relaykilo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views266 pages

BasicofJS Merged

Uploaded by

relaykilo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 266

INTRODUCTION TO JAVASCRIPT

 JavaScript is the most popular programming language which is used to


create interactive webpages
 JavaScript is the client-server side scripting language which is used to
create dynamic web pages
 JavaScript was invented by Brendan Eich in 1995, and became an ECMA
standard in 1997.
 ECMA-262 is the official name of the standard. ECMAScript is the official
name of the language.
 Current version of JS is ES6 (introduced after 2015)

Characteristic of JavaScript
 Client-side scripting language: The code is readable analyzable and
executable by browser itself
 Interpreted Language: JavaScript is an interpreted language, meaning it
is executed line by line at runtime.
 Dynamically types Language: JavaScript is dynamically-typed, which
means you don't need to specify the data type of a variable when
declaring it. The type is determined at runtime.
 Weakly Typed Language: Semicolon is not mandatory at all the time
 Synchronous in nature: It will execute line by line; we can make it as
asynchronous using promise and async await

Advantages of JS
 Easy to learn and implement
 Reduces server load
 Efficient performance
 Regular updates
 Platform independent
 It has more frameworks and libraries

Environmental Setup
➢ We can run JavaScript code in two environments.
o Browser
o Node.js
➢ Browser understand the js through JS engine and every browser consists
of JavaScript engine which helps to run JS code

Browser JS engine

Chrome V8

Mozilla Firefox Spider monkey

Microsoft Edge Chakra

Safari JavaScript Core Webkit

How to include JS into HTML


We can insert JS code to HTML in two ways
1.Internal JS: In the HTML file we use <script></script> tags and we
will write JS code
2.External JS : We will create new file with .js extension and we can
link this to html file using <script src=’app.js’></script>
Output Methods
 console.log(“hello”)
It will print the output in console window
 document.write(“Hello”)
It will print the output in user interface
 document.writeln(“Hello”)
It will print the output in user interface

Tokens
Building blocks of every programming language
1. Keywords: Predefined words whose task is already predefined
Ex: for, if, while, var, let, const
2. Identifiers: The name given for the variables, arrays, objects etc.
3. Literals: The values written by developer

Variable in JS
 Variable is a named memory allocation to store the data
 In JavaScript We have 3 keywords to declare variables (var, let, const)
 Syntax To declare variable:
var/let/const identifier;
var/let/const identifier=value;
EX: let age = 27
Here let is keyword, age is identifier and 27 is literal
Difference between var, let and const

var let const

Declaration var a let b const c = 40

Initialization a = 30 b = 45 NP

Re-initialization a = 700 b = 90 NP

Re-declaration var a; NP NP

Scope global script script

Hoisting
 Hoisting is JavaScript's default behavior of moving all declarations to the
top of the current scope (to the top of the current script or the current
function).
 In JavaScript, a variable can be declared after it has been used.
Example:
console.log(myVar); // Outputs: undefined
var myVar = 42;
The let and const Keywords
 Variables defined with let and const are hoisted to the top of the block, but
not initialized.
 Meaning: The block of code is aware of the variable, but it cannot be used until it has
been declared.
 Using a let variable before it is declared will result in a Reference Error.
 The variable is in a "temporal dead zone" from the start of the block until it is
declared:
 A temporal dead zone (TDZ) is the area of a block where a variable is inaccessible
until the moment the computer completely initializes it with a value.
Datatypes in JS
Datatype defines the type of data to be stored in a particular memory
allocation
JavaScript has 2 types of Datatypes
1.primitive
• string: We can declare the string in js in 3 ways
Example: const emp = ‘suman’,
var str =” hello”
let str = `Hello everyone`

• number: Integer and floating-point numbers


Ex: let num = 80
var salary = 90008.67
• boolean: True or false
Ex: var isDeveloper = true
• bigint: large amount of data
o to create bigInt variable suffix number with ‘n’
Ex: var hike = 8798798n
• undefined: It represents the value of an uninitialized values
Ex: let project;
• null: It is empty variable and for future use
Ex: let company = null
• symbol: It will create function
o Ex: let work = symbol
2.Non primitive
A function
An object
An array

The typeOf() operator


• This is used to check the which type of data is stored in the
variable
Ex: typeOf(age)

JavaScript Template Strings


• Also known as String Templates, Template Strings and Template
Literals
• Template Strings use back-ticks (``) rather than the quotes ("")
to define a string
Ex: let text = `Hello World!`;
• Template Strings allow both single and double quotes inside a
string:
o let text = `He's often called "Johnny"`;
• Template Strings allow multiline strings:
o let text =
`The quick
brown fox
jumps over
the lazy dog`;
• Template String provide an easy way to interpolate variables
and expressions into strings.
The method is called string interpolation.
The syntax is: ${var_name}
Variable Substitutions
Template Strings allow variables in strings:
let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}! `;
let res = ` ${50+67} `;

Operators in JS
 Predefined symbols used to perform particular task
 Types of operators
• Arithmetic Operators: +, -, *, /, %, ++, --
• Assignment Operators: +=, -=, *=, /=, %=, =
• Comparison Operators: >, <, !=, >=,<=,==,===
• Logical Operators: &&, ||, !
• Ternary Operators:
The ternary operator is a simplified conditional operator like if / else.
Syntax: condition? <expression if true>: <expression if false>

Conditional Statements
• Conditional statements are used to perform different actions
based on different conditions.
• Use if to specify a block of code to be executed, if a specified
condition is true
• Use else to specify a block of code to be executed, if the same
condition is false
• Use else if to specify a new condition to test, if the first
condition is false
• Use switch to specify many alternative blocks of code to be
executed

Loops in JS
Loops can execute a block of code a number of times
while loop : Repeats a statement or group of statements while a
given condition is true. It tests the condition before executing the
loop body
Do while loop : It is more like a while statement, except that it tests
the condition at the end of the loop body.
For loop : Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable
BOM AND DOM
BOM :
The Browser Object Model (BOM) allows JavaScript to "talk to" the
browser.
"BOM" stands for Browser Object Model. It represents the objects that a
browser provides to JavaScript to interact with the browser itself.
The BOM includes objects like:

Window: The global object in a browser's environment. It represents the


browser window or tab and contains properties like window. location
(which gives information about the current URL), window. document
(which refers to the DOM document in the current window), and many
others.
1. Document: Represents the DOM (Document Object Model) of a web
page. It provides methods and properties to interact with the contents
of the page.
2. Location: Represents the current URL of the browser and allows you to
interact with it.
3. Navigator: Provides information about the browser itself, such as its
name, version, and capabilities.
4. Screen: Represents the user's screen. It provides information about the
dimensions and pixel depth of the screen.
5. History: Allows manipulation of the browser's history (back, forward,
etc.).
Window. Screen
 The window.screen object contains information about the user's screen.
 The window.screen object can be written without the window prefix
Properties:
• screen.width
• screen.height
• screen.availWidth
• screen.availHeight
• screen.colorDepth
• screen.pixelDepth

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.
 Some examples:
• 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.location.assign() loads a new document

Window.history
 Window.history object contains the browser history.
 Some methods:
• history.back() - same as clicking back in the browser
• history.forward() - same as clicking forward in the browser
window.navigator
 Window.navigator object contains information about the visitor’s
browser
 Examples:
• navigator.cookieEnabled : property returns true if cookies are
enabled, otherwise false.
• navigator.appCodeName :property returns the application code
name of the browser.
• navigator.platform : property returns the browser platform
(operating system).
DOM(Document Object Model)
 In JavaScript, the DOM (Document Object Model) is a programming
interface for web documents. It represents the structure of a document
as a tree-like model where each node is an object representing a part of
the document, such as elements, attributes, and text.
 When a web page is loaded, the browser creates
a Document Object Model of the page.
 The HTML DOM model is constructed as a tree of Objects:

DOM Manipulation
• 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
DOM Targeting Methods
 Methods used to target HTML elements in JavaScript file
 getElementById(id): This method allows you to retrieve an element from
the document by its unique id.
 getElementsByClassName(className): This method returns a collection
of all elements in the document with a specified class name.
 getElementsByTagName(tagName): Returns a collection of elements
with the specified tag name.
 querySelector(selector): Returns the first element that matches a
specified CSS selector.
 querySelectorAll(selector): Returns a NodeList of all elements that match
a specified CSS selector.

Changing HTML Elements


1.innerHTML : Change the inner HTML of an element
element.innerHTML = new html content

2.innerText : Change the content of an element


element. innerText = new content

3. element.attribute = new value


Change the attribute value of an HTML element

4. style : Change the style of an HTML element


element.style.property = new style

5.setAttribute() : Change the attribute value of an HTML element


element.setAttribute(attribute, value)
Adding and Deleting Elements
1.createElement() : Create an HTML element
document.createElement(element)

2. appendChild() : Add an HTML element


document.appendChild(element)

3. removeChild() : Remove an HTML element


document.removeChild(element)

4.remove() : Remove an HTML element


element.remove ()

5.replaceChild() : Replace an HTML element


document.replaceChild(new, old)

DOM Event Listener


 The addEventListener() method attaches an event handler to the
specified element
 The first parameter is the type of the event (like "click" or "mousedown"
or any other HTML DOM Event.)
 The second parameter is the function we want to call when the event
occurs.
Ex: element.addEventListener("click", function(){
alert("Hello World!");
});
DOM Events
 Event: An action performed by the user on the webpage is known as an
event
 A JavaScript can be executed when an event occurs, like when a user
clicks on an HTML element.
 Click
 Mouseover
 Mouseout
 Mousedown
 Mouseup
 Contaxmenu
 Doubleclick
 Keypress
 Keyup
 Keydown
 submit

Event Object :
 Event handler(function) takes a parameter that is event object
 This has the information of the event which we are performing
preventDefault() :
The preventDefault() method cancels the event if it is cancelable, meaning that
the default action that belongs to the event will not occur.
For example, this can be useful when:
 Clicking on a "Submit" button, prevent it from submitting a form
 Clicking on a link, prevent the link from following the URL
By calling the preventDefault() method in event handler we can prevent the
default action of event on the element
Event Propagation
 Event propagation refers to the way events travel through the DOM
tree. When an event occurs on an element, it can trigger event
handlers not only on that element but also on its parent elements, all
the way up to the root of the document. There are two phases of
event propagation:
1.Capturing Phase: The event travels from the root of the DOM tree
down to the target element.
2.Bubbling Phase: The event then bubbles up from the target
element back to the root.
 event.stopPropagation(): This method prevents further propagation
of the current event. It stops the event from bubbling up the DOM
tree or from capturing down the tree

JSON(Java Script Object Notation)


It is format of storing and transporting data.
It is used when the data is sent form the server to web page
It is a popular data format for developers because of its human readable
text, light weight which requires less coding and faster process
Example: [
{“fname”:”Ram”,”lname”:”Patil”},
{“fname”:”Raj”,”lname”:”smith”},
{“fname”:”Ashish”,”lname”:”gouda”}
]
 Data is in Key value pairs
 Data is separated by ‘,’
 Curly braces holds objects
 [ ]---holds array
In JavaScript, there are two main methods used to work with JSON (JavaScript
Object Notation):
1.JSON.Stringify() : used to convert normal object to JSON format
2.JSON.parse(): Used to convert JSON format of data to normal object

Time delays
 setTimeOut() and setInterval() are two functions in js allows to schedule
tasks to be executed at later time. Used for animations, polling data
from server and other asynchronous tasks.
setTimeOut() :
 Runs the code with time delay
Syntax : window.setTimeOut( function , delay ) ;
• function: The function you want to execute.
• delay: The amount of time (in milliseconds) before the function is
executed
setInterval() :
 The function similar to setTimeOut, but it schedules a function to be
executed repeatedly at specified interval.
Syntax : window.setInterval( function , delay ) ;
• function: The function you want to execute.
• delay: The amount of time (in milliseconds) before the function is
executed
 createTimeOut() and createInterval()
 cancel a setTimeout, you use clearTimeout
 cancel a setTimeout, you use clearTimeout
Promises
Promises in JavaScript are a powerful way to work with asynchronous code.
They provide a clean and more readable syntax for handling operations that
may take an unknown amount of time to complete, such as fetching data from
a server or reading a file.
A promise represents the eventual result of an asynchronous operation. It
can be in one of three states:
• Pending: Initial state, neither fulfilled nor rejected.
• Fulfilled: Meaning the operation completed successfully.
• Rejected: Meaning the operation failed.

Syntax to create promise


const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation, e.g., fetching data from a server.

if (/* operation successful */) {


resolve('Success data'); // Resolve if successful.
} else {
reject('Error message'); // Reject if there's an error.
}
});
Consuming a Promise:
 then() : It will executed when the promise will be in resolved
state
 catch() : It will get executed when the promise is in rejected
state
 finally() : It will execute always means promise is in resolve ,
reject or in pending state

async and await


 "async and await make promises easier to write"
 async makes a function return a Promise
 await makes a function wait for a Promise
 Async : The async keyword is used to define a function that returns a
promise.
 Await : The await keyword is used inside an async function to wait for a
Promise to settle (either resolve or reject). It can only be used inside an
async function
BOOTSTRAP
What is Bootstrap?
• Bootstrap is the most popular HTML, CSS and JavaScript framework for
developing a responsive and mobile friendly website.

• It is absolutely free to download and use.

• It is a front-end framework used for easier and faster web development.

• It includes HTML and CSS based design templates for forms, buttons,
tables, navigation, image carousels and many others.

•It facilitates you to create responsive designs.


History of Bootstrap:-

Bootstrap was developed by Mark Otto and Jacob Thornton at Twitter. It was released as an
open source product in August 2011 on GitHub.

In June 2014 Bootstrap was the No.1 project on GitHub.

Version 3→stable version


Version 4→updated version of 3
Version 5-→current version

Main difference between Bootstrap 5 and Bootstrap 3 & 4,is that Bootstrap 5 has switched
to javaScript instead of jQuery.
A

Why use Bootstrap:-

•It is very easy to use. Anybody having basic knowledge of HTML and CSS
can use Bootstrap.
•It facilitates users to develop a responsive website.
•It is compatible on most of browsers like Chrome, Firefox, Internet
Explorer, Safari and Opera etc.

What is a responsive website:-

A website is called responsive website which can automatically adjust


itself to look good on all devices, from smart phones to desktops etc.
HERE WE HAVE TWO WAYS TO USE BOOTSRAP:-
1By using installation process

2.By using CDN(Content Delivery Network or Content Distribution Network) links

➢ CDN is a free content delivery network that helps us to quickly load


Bootstrap CSS, Javascript, and jQuery libraries on our projects to make projects
responsive, mobile friendly, and attractive.

Bootstrap CDN Link and scripts:-


CSS URL:-https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css

JS URL:-https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js
Utilities / Helper Classes:-
Bootstrap 5 has a lot of utility/helper classes to quickly style elements without
using any CSS code.
1.Background 10.Flex 19.Height

2.Colors 11.Display 20.width

3.text-bg-color 12.Opacity

4.Borders 13.Position

5.Border Radius 14.Shadow

6.Margin 15.Visibility

7.Padding 16.z-index

8.Float 17.Overflow

9.object-fit 18.Text
1.Background Color:-
The classes for background colors are: .bg-primary, .bg-success, .bg-
info, .bg-warning, .bg-danger, .bg-secondary, .bg-dark and .bg-light.

Note that background colors do not set the text color, so in some cases
you'll want to use them together with a .text-* class.

Syntax:- .bg-color

2.Colors:-
The classes for text colors are: .text-muted, .text-primary, .text-success, .text-
info, .text-warning, .text-danger, .text-secondary, .text-white, .text-dark, .text-
body (default body color/often black) and .text-light

➢ Text classes can also be used on links, which will add a darker hover color:

Ex:- <a href="#" class="text-success">Hover</a>

Syntax:- .text-color
3.Text-bg-color:-

• if we want to give both text color and background color we can use this
property. Based on background color text color will be display.

• Syntax:-.text-bg-color

4.Borders:-

The border classes to add or remove borders from an element.


Syntax:-.border-value

• border
• border border-0
• border border-top-0
• border border-left-0
• border border-bottom-0
• border border-right-0
• We can able to give the colors border.
5.Border-Radius:-

Add rounded corners to an element with the rounded classes:

Syntax:-.rounded-value

• rounded-0
• rounded
• rounded-sm
• rounded-lg
• Rounded-top
• Rounded-right
• Rounded-left
• Rounded-bottom
• Rounded-circle
6.float:- Float an element to right or left.
Syntax:-.float-value

• Left , right , none


7.Width:-
Set the width of an element with the w-* classes (.w-25, .w-50, .w-75, .w-
100, .mw-100):
8.Height:-
Set the width of an element with the h-* classes (.h-25, .h-50, .h-75, .h-
100, .mh-100):

9.Margin and padding:-


• m - sets margin
•p - sets padding
•t - sets margin-top or padding-top
•b - sets margin-bottom or padding-bottom
•l - sets margin-left or padding-left
•r - sets margin-right or padding-right
•x - sets both padding-left and padding-right or margin-left and margin-
right
•y - sets both padding-top and padding-bottom or margin-top and margin-
bottom
•0 - sets margin or padding to 0
•1 - sets margin or padding to .25rem (4px if font-size is 16px)
•2 - sets margin or padding to .5rem (8px if font-size is 16px)
•3 - sets margin or padding to 1rem (16px if font-size is 16px)
•4 - sets margin or padding to 1.5rem (24px if font-size is 16px)
•5 - sets margin or padding to 3rem (48px if font-size is 16px)

Note: margins can also be negative, by adding an "n" in front of size:

•n1 - sets margin to -.25rem (-4px if font-size is 16px)


•n2 - sets margin to -.5rem (-8px if font-size is 16px)
•n3 - sets margin to -1rem (-16px if font-size is 16px)
•n4 - sets margin to -1.5rem (-24px if font-size is 16px)
•n5 - sets margin to -3rem (-48px if font-size is 16px)
10.Display:-
i)d-inline:- converting block-level element to inline-line element.
Ex:- <p></p>,<h1></h1>,<div></div>……etc

ii)d-block:- converting inline element to block-level. Element.


Ex:-<span></span>

iii)d-inline-block:-Element act likes a inline but it will accept block-level properties.


Ex:-<img>

iv)d-flex:-By using this property we are arranging all the elements into one dimension.

• Justify-content:- around, start, end, between.


• Align-items:- center, start, end, stretch, baseline.
• Flex:- wrap, no-wrap.
• Flex-direction:- column, row, row-reverse, column-reverse.
• Flex-fill:- flex items to force them into equal widths
11.Position:-

How an HTML element can be placed in UI.


• Static
• Fixed
• Sticky
• Relative
• Absolute

• When ever we are using position properties along with those we can able to use top, bottom,
start, end.

12.Shadow:-We can add shadow to text and to elements.


Syntax:-.shadow-values

• None
• sm
• lg
• Regular(shadow)
13.opacity:-The opacity property sets the opacity level for an element.
zero means complete transparent.

Syntax:- .opacity-value
• 100
• 75
• 50
• 25

14.Text:-Aligning the text.


Syntax:- .text-value

• Start
• Center
• end
15.Visibility:-This visibility have two values.
i)visible:-the element should be visible on UI

II)invisible:-The element should be invisible on UI

16.Z-index:-
Use z-index utilities to stack elements on top of one another. Requires a position value other than static.

Syntax:- .z-values

• Z-3
• Z-2
• Z-1
• Z-0
• Z-n1
17.Overflow:-

The overflow property on the fly with four default values and classes.

Syntax:- .overflow-values

• Auto
• Hidden
• Visible
• scroll
CSS(Cascading style sheet)
 CSS is the language we use to style and align our HTML elements.

 CSS was introduced in 1994 by Haykon wium lie.

 First version of CSS was introduced in 1996(CSS1)

 CSS2-1998

 Current version of CSS is CSS3-1999

 It is style sheet language which is used to describe the look and formatting of documents
written in markup language.

 It is generally used with html to change the style of web pages and UI.

 Commenting in CSS:-- /*-----*/

How to add CSS to HTML


1.Inline style sheet :
 We will use style attribute in the tagline itself
<p style : ” color: red”>Hello CSS</p>

2.Internal style sheet :


 We have to use <style > tag in the <head> section of HTML
documnet
Example:
<style>
p{color : value}
</style>

3.External style sheet :


 We have to create external file with .css extension and we need
to link that CSS file to HTML file using <link> tag
<link rel=”stylesheet” href=”./style.css”/>

@import
 @import rule is used to link one CSS within another CSS..
Syntax:- @import url(“cssfilepath”)
Selectors
Selectors are used to target the HTML elements
A CSS selector selects the HTML element(s) you want to style.
Syntax :
Selector{
property: value;
property: value;
}

Types of CSS Selectors


1. Simple Selector
2. Combinator Selector
3. Attribute Selector
4. Pseudo class Selector
5. Pseudo Element Selector

1.Simple Selectors
I. Id selector (#)
II. Class selector (.)
III. Universal Selector (*)
IV. Element Selector (tag)
V. Grouping Selector(,)
1.ID SELECTOR (#)
 Unique id attribute within the page is selected
 Core attribute selector
 Selected by symbol “#” followed by id name
 SYNTAX: #id_name{
css properties

}
2. CLASS SELECTOR (.)
 Core attribute selector ,with specific class.
 The character to access in css file “ . “
 Multiple class name can be called using comma
SYNTAX: . class _ name{
/* css properties*/
}
3. UNIVERSAL SELECTOR(*)
 Select all elements in html page.
 All the elements within a body tag.
 Symbol of selector: “ * “
SYNTAX:
*{
properties
}
4. TYPE/ ELEMENT SELECTOR(tagname)
 Selects particular element with specified tagname.
 Call by type of tag.
SYNTAX:
element name{
properties
}
5. GROUPING SELECTOR(,)
 We can group the multiple selectors and we can do styling
#heading,.para,button{
Properties
}
NOTE: PRIORITY ORDER =====
{ “ ID > CLASS > TYPE/ELEMENT >UNIVERSAL “}

Combinator Selectors
 We will combine and target the elements
Types of combinator selectors
I. Descendent selector(space)
II. Child selector(>)
III. Adjacent sibling selector(+)
IV. General sibling selector(~)
1.DESCENDENT SELECTOR (space)
 A CSS selector can contain more than one simple selector.
Between the simple selector we can use combinator
 Combines two selectors are such that elements are matched by
second selector are selected if they have ancestor.
 (parent,parents’s parent, parent’s parents’s parent)
 Selector utilities a descendents combinator are called
descendent selectors.
Syntax: Selector1_Selector2{property declaration}
Div p{ prop:val;}

2.Child selector(>)
 The child selector selects all the elements that are the children
of a specified element
 It is placed between 2 CSS selectors,matches only those
elements matched by second selector and direct child.
Syntax:
selector 1 > selector 2 { properties }
Ex:
Div>p{prop : val}

3. Adjacent sibling selector (+)


 The adjacent sibling selector is used to select an element that is
directly after another specific element.
 Sibling elements must have the same parent element, and
"adjacent" means "immediately following".
Syntax :
former_element + target_element {style properties }

4. General sibling selector(~)


 The general sibling selector selects all elements that are next
sibling of a specified element.
 The general sibling combinator (~) separates two selectors.

Syntax :
former_element ~ target_element {
style properties
}

Pseudo classes
A CSS pseudo-class is a keyword added to a selector that specify a
special state of the selected element.
For Example: It can be used to
• Style an element when a user mouses over it
• Style visited and unvisited links differently
• Style an element when it gets focus
• Symbol for pseudo class selector is ‘:’
Selector:pseudo-class{
property:value;
}
In pseudo class selectors we have 2 types
1.structural pseudo class selectors
 Link: used to style the unvisited link
 Visited: used to style the visited link
 Active: used to style the active link
 Focus: used to style the text filed when we focus that
 Hover: used to style the element when mouse hover on the
element

a:hover - style the element when mouse hover on the element


a:link - style the unvisited link
a:visited - style the unvisited link
a:active – style the active link
input:focus – style the focused text field

2.dynamic pseudo class selectors


• first-child
• last-child
• nth-child
The :first-child pseudo-class matches a specified element that is the
first child of another element.
The :last-child pseudo-class matches a specified element that is the
last child of another element.
The :nth-child(n) selector matches every element that is the nth child
of its parent.
We can target only even children using nth-child() by passing even or
2n in parenthesis
We can target only odd children using nth-child() by passing odd or
2n+1 in parenthesis
Selector:nth-child(even){ Selector:nth-child(even){
Property Property
} }

n can be a number, a keyword (odd or even), or a formula


(like an + b).

Pseudo Elements
A CSS pseudo-element is used to style specified parts of an element.
Symbol for pseudo element selector is ‘::’
For example, it can be used to:
• Style the first letter, or line, of an element
• Insert content before, or after, the content of an element
selector::pseudo-element{
property:value;
}

:: first-line : styles the first letter of the element


:: first-letter: styles the first line of the element
::before : adds the content before the actual content
::after: adds the content after the actual content
::marker: style the list style type
::selection : style the selected content on the webpage
Selector Example Example description

::after p::after Insert something after the


content of each <p> element

::before p::before Insert something before the content


of each <p> element

::first-letter p::first-letter Selects the first letter of each <p> element

::first-line p::first-line Selects the first line of each <p> element

::marker ::marker Selects the markers of list items

::selection p::selection Selects the portion of an element that is selected by a

Attribute selector
 Attribute provides extra information to the tag.
 In this attribute selector we are targeting the elements based on
attributes
Targeting using attribute name
Selector[attribute]{
property}:value
}
Targeting using attribute name and value
Selector[attribute=“value”]{
Property:value
}
CSS
CASCADING STYLE SHEET
CSS

 CSS is the language we use to style and align our HTML


elements.
 CSS was introduced in 1994 by Haykon wium lie.
 First version of CSS was introduced in 1996(CSS1)
 CSS2-1998
 Current version of CSS is CSS3-1999
Types of CSS

 It is style sheet language which


is used to describe the look and
formatting of documents
written in markup language.
 It is generally used with html to
change the style of web pages
and UI.
 Commenting in css :-- /*-----*/
Syntax of css

Css syntax:- selector,property,value


| | |
P{ color: blue }
Three ways to add css file

1.Inline style sheet : Style attribute


<p style : ” color: red”>Hello CSS</p>

2.Internal style sheet : <style >tag


Example:
<style>
p{color : value}
</style>
External CSS Style

 External style sheet==<link>tag


 External css is used to apply css on multiple pages .
 Extension must be .css for css files.

code

.CS
S
@import

 rule is used to link one CSS within another CSS..

 This rule also supports media queries so that the user can import the media-

dependent ss.

 The @import rule must be declared on top of document after any @charset

declaration.

 Syntax:- @import url|string list-of-mediaqueries;


Selectors
Types of CSS Selectors

Simple Selector
Combinator Selector
Attribute Selector
Pseudo class Selector
Pseudo Element Selector
Selector

A CSS selector selects the HTML element(s) you want to style.

Selector{
property: value;
property: value;
}
Simple Selector

Id selector (#)


Class selector (.)
Universal Selector (*)
Element Selector (tag)
Grouping Selector(,)
UNIVERSAL SELECTOR(*)

 Select any and all types of elements in html page.


 All the elements within a body tag.
 Symbol of selector: “ * “
SYNTAX:
*{
properties }
TYPE/ ELEMENT SELECTOR

 Selects particular element.


 Call by type of tag.
SYNTAX:
element name{
properties
}
ID SELECTOR(#)

 Unique id attribute within the page is selected


 Core attribute selector
 Selected by symbol “#” followed by id name
 SYNTAX: #id_name{
css properties

}
CLASS SELECTOR

 Core attribute selector ,with specific class.


 The character to access in css file “ . “
 Multiple class name can be called using comma
SYNTAX: . class _ name{
/* css properties*/
}

NOTE: PRIORITY ORDER =====


{ “ ID > CLASS > TYPE/ELEMENT >UNIVERSAL “}
Combinator Selector

 Descendent selector(space)
 Child selector(>)
 Adjacent sibling selector(+)
 General sibling selector(~)
DESCENDENT SELECTOR

 A CSS selector can contain more than one simple selector. Between the
simple selector we can use combinator
 Combines two selector are such that elements are matched by second
selector are selected if they have ancestor.
 (parent,parents’s parent, parent’s parents’s parent)
 Selector utilities a descendents combinator are called descendent
selectors.
 Syntax: Selector1_Selector2{property declaration}
 Div p{ prop:val;}
Child selector(>)

 The child selector selects all the elements that are the children of a
specified element
 It is placed between 2 CSS selectors,matches only those elements
matched by second selector and direct child.
 Syntax:
selector 1 > selector 2 { properties }
Ex:
Div>p{prop : val}
Adjacent sibling selector

 The adjacent sibling selector is used to select an element that is


directly after another specific element.
 Sibling elements must have the same parent element, and
"adjacent" means "immediately following".

Syntax :
former_element + target_element {style properties }
general sibling selector

The general sibling selector selects all


elements that are next sibling of a
specified element.
The general sibling combinator (~)
separates two selectors.

 Syntax :
former_element ~ target_element
{ style properties }
Attribute Selector

 Attribute provides extra information to the tag.


 In this attribute selector we are targeting the elements based on
attributes
Selector[attribute]{
property}:value
}

Selector[attribute=“value”]{
Property:value
}
Pseudo classes

A CSS pseudo-class is a keyword added to a selector


that specify a special state of the selected element.
For Example: It can be used to
• Style an element when a user mouses over it
• Style visited and unvisited links differently
• Style an element when it gets focus

Selector:pseudo-class{
property:value;
}
Pseudo Classes

 Dynamic pseudo classes Structural pseudo


 Anchor Pseudo- classes
classes First-child
Last-child
 Link
Nth-child()
 Visited
 Active
 Focus
 Hover
Psuedo ClASS SELECTOR

 a:hover MUST come after we mouse hover on it


 a:link and a:visited in the CSS definition in order to be effective.
 a:active MUST come after

The :first-child pseudo-class matches a specified element that


is the first child of another element.

The :last-child pseudo-class matches a specified element that


is the last child of another element.

The :nth-child(n) selector matches every element that is


the nth child of its parent.
n can be a number, a keyword (odd or even), or a formula
(like an + b).
Pseudo Elements

 A CSS pseudo-element is used to style specified parts of an


element.

❑ For example, it can be used to:

• Style the first letter, or line, of an element


• Insert content before, or after, the content of an element

 selector::pseudo-element{
property:value;
}
Pseudo Elements

:: first-line
:: first-letter
::before
::after
::marker
::selection
Selector Example Example description

::after p::after Insert something after the content of each


<p> element

::before p::before Insert something before the content of each


<p> element

::first-letter p::first-letter Selects the first letter of each <p> element

::first-line p::first-line Selects the first line of each <p> element

::marker ::marker Selects the markers of list items

::selection p::selection Selects the portion of an element that is


selected by a user
NOW WRITE THE DIFFERENCE
BETWEEN
PSEUDO CLASS AND PSEUDO ELEMENT
SELECTOR?!
Pseudo class v/s pseudo element

PSEUDO CLASS PSEUDO ELEMENT

selectors are selected by selectors are selected by

“:“ “ :: “
Pseudo-classes are used to Pseudo-elements are used to
target state. target specific parts of an
element.
Text Property

 Textformatting
color
Text-align
Text-transform
Text-shadow
Text-decoration
Letter-spacing
Word-spacing
Text-indention
Background Property

 Background-image : url (“image.jpg”)


 Background-repeat : no-repeat/repeat-x/Y
 Background-size : cover/100%
 Background-Position : right/left/center
 Background-attachment : scroll/fixed
Font Property

 Font-size:large/small/medium
 Font-weight:bold/bolder/lighter/normal
 Font-style:italic
 Font-family:font styles
color

 Color: #efefef;
 Color:red;
 Color:rgb(255,255,0)
 Color:rgba(rgba)
Gradient:
Gradient:

 Linear-gradient(direction,color-stop1,color-stop2);
 Radial-gradient(shape size at position, start-color,…,last-color);
Box Model
Box model:

• The CSS box model is essentially a box that wraps around every
HTML element. It consists of: margins, borders, padding, and the
actual content. The image illustrates the box model:
• Content - The content of the box, where text and images appear
• Padding - Clears an area around the content. The padding is
transparent
• Border - A border that goes around the padding and content
• Margin - Clears an area outside the border. The margin is
transparent
Properties

 Margin-style
 Margin-top
 Margin-bottom
 Margin-left
 Margin-right
 Padding-style
 Padding-left
 Padding-right
 Padding-top
 Padding-bottom
 Border-style
 Border-color
 Border-width
 Border-radius
Position Property

 Static
 Relative
 Fixed
 Absolute
 Sticky
Display properties

 Inline : Displays an element as an inline element (like <span>).


Any height and width properties will have no effect
 block : Displays an element as a block element (like <p>). It
starts on a new line, and takes up the whole width
 Inline-block : Displays an element as an inline-level block
container. The element itself is formatted as an inline element,
but you can apply height and width values
 Flex : Displays an element as a block-level flex container
Flex Properties

 Flex-box properties
 Display : flex
 Flex-direction: row/column
 Flex-wrap: wrap/nowrap/wrap-reverse
 Justify-content: flex-start/flex-end/center/space-around/space-
between/baseline
 Align-items: flex-start/flex-end/center
Flex-Box
 Flex-items properties
 Flex-basis:<length>
 Flex-grow: <number>
Transition
TRANSITION ALLOWS YOU TO CHANGE PROPERTY VALUE.
Transition Property

CSS transitions allows you to change property


values smoothly, over a given duration.
• Transition-property: The CSS property you want to add
an effect to
• Transition-duration: The duration of the effect
• Transition-timing-function:
• Transition-delay : The transition-delay property specifies a delay
(in seconds) for the transition effect.
• Transition(shorthand property)
• transition: width 2s linear 1s
Transition-timing-function

• ease - specifies a transition effect with a slow start,


then fast, then end slowly (this is default)
• linear - specifies a transition effect with the same
speed from start to end
• ease-in - specifies a transition effect with a slow start
• ease-out - specifies a transition effect with a slow end
• ease-in-out - specifies a transition effect with a slow
start and end
2D and 3D
Transforms
TRANSFORMS ALLOW YOU TO MOVE, ROTATE, SCALE, SKEW, ELEMENT.
Transform property

 The transform property applies a 2D or 3D


transformation to an element. This property allows
you to rotate, scale, move, skew, etc., elements.
 It is used to change behavior of an element
2D transform :
•translate()
•rotate()
•scaleX()
•scaleY()
•scale()
•skewX()
•skewY()
•skew()
3D transform :
•rotateX()
•rotateY()
•rotateZ()

Difference
2D Transforms

1.translate()-moves an element from its current position.


2.rotate()-rotate an element clockwise/counter-clockwise according to
degree.
Using negative values will rotate the element counter-clockwise.
3.scale()- increases/decreases the size of an element.
4.scaleX()-increases or decreases the width of an element.
5.scaleY()- increases or decreases the height of an element.
6.skew()-skews an element along the X and Y-axis by the given angles.
7.skewX()-skews an element along the X-axis by the given angle.[degree 0-
360]
8.skewY()-skews an element along the Y-axis by the given angle.
9.matrix()- 6 parameters
mathematical function
matrix(scaleX(),skewY(),skewX(),scaleY(),translateX(),translateY())
transform: matrix(1, -0.3, 0, 1, 0, 0);
3D Transforms

 rotateX()- rotates an element around its X-axis.


 rotateY()-rotates an element around its Y-axis.
 rotateZ()-rotates an element around its Z-axis.
Animations

 CSS allows animation of HTML elements without using JavaScript.

 An animation lets an element gradually change from one style to

another.

 You can change as many CSS properties you want, as many times as

you want.

 To use CSS animation, you must first specify some keyframes for the

animation.

 Keyframes hold what styles the element will have at certain times.
ANIMATIONS

•@keyframes
•animation-name
•animation-duration
•animation-delay
•animation-iteration-count
•animation-direction
•animation-timing-function
The @keyframes Rule
 When you specify CSS styles inside the @keyframes rule, the animation will
gradually change from the current style to the new style at certain times.

 To get an animation to work, you must bind the animation to an element.


EXAMPLE :
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}

/* The element to apply the animation to */


div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}
Animations

•animation-name :Name of the animation


•animation-duration: This property defines how long an animation
should take to complete, If the animation-duration property is not specified, no
animation will occur, because the default value is 0s (0 seconds)

•animation-delay : Property specifies a delay for the start of an


animation.

•animation-iteration-count : property specifies the number of times an


animation should run.

•animation-direction : property specifies whether an animation should be


played forwards, backwards or in alternate cycles.

•animation-timing-function: property specifies the speed curve of the

animation
animation-direction

•normal - The animation is played as normal


(forwards). This is default
•reverse - The animation is played in reverse
direction (backwards)
•alternate - The animation is played forwards
first, then backwards
•alternate-reverse - The animation is played
backwards first, then forwards
Media queries

 Media query is a CSS technique introduced in CSS3.

 It uses the @media rule to include a block of CSS properties only


if a certain condition is true.

 In this example, the only keyword is used to target only


screens.

 Example
 If the browser window is 600px or smaller, the background color will be
lightblue:
 @media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
CSS Typography
Text Properties in CSS
color : property is used to set the color of the text
 a color name - like "red"
 a HEX value - like "#ff0000"
 an RGB value - like "rgb (255,0,0)"
 An RGB color value represents red, green, blue.

 Each parameter (red, green, and blue) defines the intensity of the color between 0
and 255.

 For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value
(255) and the others are set to 0.

 To display black, set all color parameters to 0, like this: rgb(0, 0, 0).

 To display white, set all color parameters to 255, like this: rgb(255, 255, 255).

 In rgba (red,green,blue,alpha).alpha means opacity of the color.

 The alpha value is a number between 0.0 means full transparent and 1.0 not
transparent.

 Color:rgb(255,255,0)
 Color:rgba(160,200,100,0.4)

text-align : property is used to set the horizontal alignment of


a text.
 A text can be left or right aligned, centered, or justified.
text-transform: property is used to specify uppercase and
lowercase letters in a text.
 It can be used to turn everything into uppercase or
lowercase letters, or capitalize the first letter of each
word:
text-shadow: property adds shadow to text
 In its simplest use, you only specify the horizontal
shadow (2px) and the vertical shadow (2px) (text-
shadow: 2px 2px;)
 add a color (red) to the shadow ( text-shadow: 2px 2px
red;)
 add a blur effect (5px) to the shadow( text-shadow: 2px
2px 5px red)
letter-spacing: property is used to specify the space between
the characters in a text.
word-spacing: property is used to specify the space between
the words in a text.
text-indention: property is used to specify the indentation of
the first line of a text
text-decoration :
 text-decoration-line : property is used to add a
decoration line to text.(overline,underline,line-through)
 text-decoration-color: property is used to set the color
of the decoration line(red).
 text-decoration-style: property is used to set the style of
the decoration line(solid,dashed,double,dotted,wavy).
 text-decoration-thickness: property is used to set the
thickness of the decoration line(2px).
 text-decoration: It is a shorthand property for all these
four properties
text-decoration-line (required)
text-decoration-color (optional)
text-decoration-style (optional)
text-decoration-thickness (optional)

line-height:- The line-height property specifies the height of a line. we pass


values in px, deg, decimal.

box-shadow:- The CSS box-shadow property is used to apply one or more


shadows to an element.
This property will accept five values. h-shadow v-shadow blur-radius spread-
radius color of the shadow.
*Default shadow color is text-color. we can pass negative values too.

Background Property: -
background-color: property sets the background color of an element.
background-image : url (“image.jpg”)
 property sets one or more background images for an element.
 By default, a background-image is placed at the top-left corner of an
element, and repeated both vertically and horizontally.
background-repeat : no-repeat/repeat-x/Y
 property sets if/how a background image will be repeated.
 By default, a background-image is repeated both vertically and
horizontally.
background-size : cover/100%
 property specifies the size of the background images.
background-Position : right/left/center
 property sets the starting position of a background image.
background-attachment : scroll/fixed
 property sets whether a background image scrolls with the rest of the
page, or is fixed.

Gradient
CSS gradients is used to display smooth transitions between two or more
specified colors.
1. Linear-gradient(direction,color-stop1,color-stop2);
2. Radial-gradient(shape size at position, start-color,…,last-color);

Height and Width Property:-


The height and width properties are used to set the height and width of an
element.
The height and width properties may have the following values:
 auto - This is default.
 length - The height/width.
 % - The height/width in percent of the containing block
 initial – Automatically set the height/width to its default value
 inherit - The height/width will be inherited from its parent
max-width:px, max-height:px, min-width:px, min-height:px, width:px,
height:px

Font Properties
CSS fonts control how text appears on a webpage.
Font-size: large/smaller/medium/small/x-small/xx-small/x-large/xx-
large/px/deg.
Font-weight: bold/bolder/lighter/normal/100 to 900
Font-style: italic/normal/oblique
Font-family: font styles

Box Model:-

• The CSS box model is essentially a box that wraps around every HTML
element. It consists of: margins, borders, padding, and the actual content. The
image illustrates the box model:
• Content - The content of the box, where text and images appear
• Padding - Clears an area around the content. The padding is transparent
no negative values.
• Border - A border that goes around the padding and content
• Margin - Clears an area outside the border. The margin is
transparent.negative values will be accepted.
• Margin-style
• Margin-top
• Margin-bottom
• Margin-left
• Margin-right
• Padding-style
• Padding-left
• Padding-right
• Padding-top
• Padding-bottom
• Border-style
• Border-color: Color of the border. Default color will be text color(this
property is optional)
• Border-width: Thickness of border. Default thickness will be 2px(this
property is optional)
• Border-style: dotted/double/groove/dashed/solid(this property is
mandatory )
• Border-radius: Convert sharp edges to curve shape.
Ex:-border-radius:px/deg.

Position Property:-
The position property specifies the type of positioning method used for an
element.
You must specify at least one of top, right, bottom or left for positioning to
work.
Static:-Default value for position property
Relative:-Moves the element from its current position
Fixed:-It will be fixed in particular place. which means it always stays in
the same place even if the page is scrolled
Absolute:- Is positioned relative to the nearest positioned ancestor.if no
ancestor then it uses document body.
Sticky:- It is positioned based on the user's scroll. Toggles between
relative and fixed.
Display properties:-
Inline :- Displays an element as an inline element (like <span>). Any height
and width properties will have no effect
Block :- Displays an element as a block element (like <p>). It starts on a new
line, and takes up the whole width
Inline-block :-Displays an element as an inline-level block container. The
element itself is formatted as an inline element, but you can apply height
and width values
Flex :-Displays an element as a block-level flex container

Flex-box properties
Display :- flex
Flex-direction:- specifies the display-direction of flex items in the flex
container. Values are row/column/row-reverse/colomn-reverse
Flex-wrap:- specifies whether the flex items should wrap or not. values are
wrap/no-wrap/wrap-reverse
Justify-content:- property is used to align the flex items in horizontally. values
are flex-start/flex-end/center/space-around/space-between/baseline
Align-items:- property is used to align the flex items in vertically. values are
flex-start/flex-end/center

CSS Grid Layout


The Grid Layout Module offers a grid-based layout system, with rows and
columns.
The Grid Layout Module allows developers to easily create complex web
layouts.

Grid Container
The rows and columns of a grid is defined with the grid-template-rows and
the grid-template-columns properties (or the shorthand grid or grid-
template properties).
grid-template-columns: property defines the number of columns in your grid
layout, and it can define the width of each column.
grid-template-rows: property defines the height of each row.

Grid Items
grid-column: property defines on which column(s) to place an item.
You define where the item will start, and where the item will end.
grid-row: property defines on which row to place an item.
You define where the item will start, and where the item will end.
grid-area: property can be used as a shorthand property for the grid-row-
start, grid-column-start, grid-row-end and the grid-column-end properties.

Transition:
Transition allows you to change property value smoothly, over a given
duration.
Transition-property: The CSS property you want to add an effect
Transition-duration: The duration of the effect
Transition-timing-function: speed curve of the transition effect.
ease - specifies a transition effect with a slow start, then fast, then end
slowly (this is default)
linear - specifies a transition effect with the same speed from start to
end
ease-in - specifies a transition effect with a slow start
ease-out - specifies a transition effect with a slow end
ease-in-out - specifies a transition effect with a slow start and end

Transition-delay : The transition-delay property specifies a delay (in


seconds) for the transition effect.
Transition(shorthand property)
transition: width 2s linear 1s
2D and 3D Transforms
Transforms allow you to move, rotate, scale, skew, element.
The transform property applies a 2D or 3D transformation to an
element. This property allows you to rotate, scale, move, skew, etc.,
elements.
It is used to change behavior of an element
2D transform :
translate()
rotate()
scaleX()
scaleY()
scale()
skewX()
skewY()
skew()
3D transform :
rotateX()
rotateY()
rotateZ()
1.translate()-moves an element from its current position.
2.rotate()-rotate an element clockwise/counter-clockwise according to
degree.
Using negative values will rotate the element counter-clockwise.
3.scale()- increases/decreases the size of an element.
4.scaleX()-increases or decreases the width of an element.
5.scaleY()- increases or decreases the height of an element.
6.skew()-skews an element along the X and Y-axis by the given angles.
7.skewX()-skews an element along the X-axis by the given angle.[degree 0-360]
8.skewY()-skews an element along the Y-axis by the given angle.
9.matrix()- 6 parameters mathematical function
• matrix(scaleX(),skewY (),skewX(),scaleY(),translateX(),translateY())
• transform: matrix (1, -0.3, 0, 1, 0, 0);
3D Transforms:-
rotateX()- rotates an element around its X-axis.rotateY()-rotates an
element around its Y-axis.
rotateZ()-rotates an element around its Z-axis.

Animations
CSS allows animation of HTML elements without using JavaScript
An animation lets an element gradually change from one style to
another.
You can change as many CSS properties you want, as many times as you
want.
To use CSS animation, you must first specify some keyframes for the
animation.
Keyframes hold what styles the element will have at certain times.
@keyframes:-
When you specify CSS styles inside the @keyframes rule, the animation
will gradually change from the current style to the new style at certain
times.
To get an animation to work, you must bind the animation to an element.
EXAMPLE :
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
/* The element to apply the animation to */
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}

animation-name :Name of the animation


animation-duration: This property defines how long an animation should take
to complete, If the animation-duration property is not specified, no animation
will occur, because the default value is 0s (0 seconds)
animation-delay : Property specifies a delay for the start of an animation.
animation-iteration-count : property specifies the number of times an
animation should run.
animation-direction : property specifies whether an animation should be
played forwards, backwards or in alternate cycles.
normal - The animation is played as normal (forwards). This is default
reverse - The animation is played in reverse direction (backwards)
alternate - The animation is played forwards first, then backwards
alternate-reverse - The animation is played backwards first, then forwards
animation-timing-function: property specifies the speed curve of the
animation

Media queries
 Media query is a CSS technique introduced in CSS3.
 It uses the @media rule to include a block of CSS properties only if a certain
condition is true.
 In this example, the only keyword is used to target only screens.
Example
If the browser window is 600px or smaller, the background color will be lightblue:
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
ES6
ES6 concepts

 Arrow function
 Rest parameter
 Spread operator
 Destructuring (Array destructuring and object destructuring)
 Modules
Rest parameter and spread operator

 InJava script, both the spread operator and


rest parameter have the same syntax which is
three dots(…).
 Even though they have the same syntax they
differ in functions.
Rest parameter (…identifier)

 The rest parameter is an improved way to handle function parameters


 The rest parameter syntax allows us to represent an indefinite number of
arguments as an array.
 Rest parameter is used to store the rest of the values
 Always rest parameter should be the last parameter
function function_name(...parameters) {
statement;
}
Spread operator(…variablename)

 The JavaScript spread operator (...) allows us to


quickly copy all or part of an existing array or object
into another array or object.
Syntax : var var_name = [...iterable];
 const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];
Destructuring

 Destructuring in ES6 is a convenient feature that allows you to extract


values from arrays or objects and assign them to variables in a more
concise and readable way. It simplifies the process of extracting specific
data from complex structures.
 Destructuring is the easy to extract only what is needed.
 EX:
 const numbers = [1, 2, 3];

const [a, b, c] = numbers;


console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3
Modules

 JavaScript modules allow you to break up your code


into separate files.
 This makes it easier to maintain the code-base.
 ES Modules rely on
the import and export statements.
 Browser will not understand modules. So in modules it is
mandatory to mention type = “module” inside the script tag
of index.html
Export
 You can export a function or variable from any file with export keyword.
 There are two types of exports: Named and Default.
 Named Export :
 You can create named exports two ways. In-line individually, or all at
once at the bottom.
 Default Export :
 You can only have one default export in a file.
Import

 You can import modules into a file in two ways, based on if they are
named exports or default exports.
 Named exports must be destructured using curly braces. Default exports
do not.
 When you import the named export, you must have to use the same
name as the corresponding object inside { }.
 When you import the default export, we can give any name.
Functions In JS
 A JavaScript function is a block of code designed to perform a particular
task.
 A JavaScript function is executed when "something" invokes it (calls it).
 With functions you can reuse code
 You can write code that can be used many times.
 You can use the same code with different arguments, to produce
different results.
 Syntax :
function myFunction(p1, p2) {
return p1 * p2;
}
 A JavaScript function is defined with the function keyword, followed by
a name, followed by parentheses ().
 Function names can contain letters, digits, underscores, and dollar signs
(same rules as variables).
 The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
 The code to be executed, by the function, is placed inside curly
brackets: {}

Types of Functions in JS
1. Anonymous function
2. Named function
3. Function with expression
4. Nested function
5. Immediate invoking function
6. Arrow function
7. Higher order function
8. Callback function
9. Generator function

1.Anonymous function:
A function without name is known as Anonymous function
Syntax:
function(parameters) {
// function body
}
2. Named Function
A function with name is called as named function
Syntax :
function functionName(parameters) {
// function body
}
3 . Function with expression
It is the way to execute the anonymous function
Passing whole anonymous function as a value to a variable is known as
function with expression.
The function which is passed as a value is known as first class function
EX : let x=function(){
//block of code
}
x();

4.Nested function
 A function which is declared inside another function is known as
nested function.
 Nested functions are unidirectional i.e., We can access parent
function properties in child function but vice-versa is not possible.
 The ability of js engine to search a variable in the outer scope when it
is not available in the local scope is known as lexical scoping or scope
chaining.
 Whenever the child function needs a property from parent function
the closure will be formed and it consists of only required data.
 A closure is a feature of JavaScript that allows inner functions to
access the outer scope of a function. Closure helps in binding a
function to its outer boundary and is created automatically whenever
a function is created. A block is also treated as a scope since ES6.
Since JavaScript is event-driven so closures are useful as it helps to
maintain the state between events.
function parent(){
let a=10;
function child(){
let b=20;
console.log(a+b);
}
Child();
}
Parent();
JavaScript currying:
Calling a child function along with parent by using one more parenthesis is
known as java script currying
Example:
Function parent(){
let a=10;
function child(){
let b=20;
console.log(a+b);
}
return child;
}
parent()(); ==èJavaScript currying

5.Immediate invoking function(IIF)


 A function which is called immediately as soon as the function
declaration is known as IIF
 We can invoke anonymous function by using IIF
Example:
(function(){
console.log(“Hello”);
})();
6.Arrow function
 It was introduced in ES6 version of JS.
 The main purpose of using arrow function is to reduce the syntax.
 If function has only one statement then block is optional.
 It is mandatory to use block if function consists of multiple lines of code
or if we use return keyword in function.
 Example:
Let x=(a,b)=>console.log(a+b);
Let y=(a,b)=>{return a + b };

7.Higher order function(HOF)


 A function which accepts a function as a parameter is known as HOF
 It is used to perform multiple operations with different values.
 Example:
Function hof(a , b , task ){
Let res=task(a,b);
return res;
};
Let add=hof(10,20,function(x , y){
return x + y;
}
Let mul = hof(10,20,function(x , y){
return x*y;
}
Console.log(add());
Console.log(mul());

8.Callback function
 A function which is passed as an argument to another function is known
as callback function.
 The function is invoked in the outer function to complete an action
 Example
function first(){
Console.log(“first”);
}
function second(){
Console.log(“third”);
}
function third(callback){
Console.log(“second”);
Callback()
}
first();
third(second);

10.Generator function
 A generator-function is defined like a normal function, but whenever it
needs to generate a value, it does so with the yield keyword rather than
return.
 Example:
Function* gen(){
Yield 1;
Yield 2;
…….
………
}
Let res=gen();
Console.log(res.next().value);
Console.log(res.next().value);
Console.log(res.next().value);

JAVASCRIPT ARRAYS
ARRAYS:- Array is collection of different elements. Array is heterogenous in
nature.
• In JavaScript we can create array in 2 ways.
1.By array literal
2.By using an Array constructor (using new keyword)

1) JavaScript array literal: -


• The syntax of creating array using array literal is:
var arrayname = [value1, value2......valueN];
• As you can see, values are contained inside [ ] and separated by ,
(comma).
• The .length property returns the length of an array.

2) JavaScript array constructor (new keyword):-


Here, you need to create instance of array by passing arguments in constructor
so that we don't have to provide value explicitly.
var emp=new Array("Jai","Vijay","Smith");

Java script Array methods


 push() : It will insert an element of an array at the end

flipkart.push("laptop","tv");
 unshift() : It will insert an element of an array at the first

flipkart.unshift("Shirts","jacket")

 pop() : It will remove elements of array from the end

flipkart.pop();

 shift() : It will remove elements of array from the start

flipkart.shift();

 indexOf() :It will return a index of particular element

console.log(flipkart.indexOf("glossery"));

 Includes() : It will check whether the particular element is


present in array or not.

console.log(flipkart.includes("footwares"))

 At() : It will return the element which is present in particular


index.

console.log(flipkart.at(3))
 Slice() : It will give slice of an array and it will not affect the
original array.

let newArr=flipkart.slice(1,4);
console.log(newArr);
console.log(flipkart);

 Splice() : It is used to add or remove elements from an array

flipkart.splice(2,0,"bluetooth","kurtha")
console.log("after splicing");
console.log(flipkart);

 Join() : It is used to join all elements of an array into a string.

console.log(flipkart.join());
console.log(flipkart.join(""));

 Concat() : It is used to join/concat two or more arrays.

console.log(flipkart.concat(amazon));

 toString() : It converts all the elements in an array into a single


string and returns that string.

console.log(flipkart.toString());

 Split() : It is used to split a string into an array.


let str="Hello";
console.log(str.split(""));

 Reverse() : It is used to reverse an array.

console.log(flipkart.reverse());

 Array.from() : It will convert string into an array

filter(), map(), reduce()


filter, map and reduce are all array methods in JavaScript. Each one
will iterate over an array and perform a transformation or
computation. Each will return a new array based on the result of the
function.
1. filter():
The filter() method in JavaScript is used to create a new array with
all elements that pass a test specified by a provided function. It
does not modify the original array.
Example:
let newArray = array. filter(callback(element, index, array){
thisArg;
}

callback: This is the function that is used to test each element in the
array. It takes three arguments:
element: The current element being processed in the array.
index (optional): The index of the current element being
processed.
array (optional): The array filter was called upon.
thisArg (optional): Value to use as this when executing callback.

2.map():
The map() method in JavaScript is used to create a new array by
applying a function to every element in an existing array. It does not
modify the original array. Instead, it returns a new array with the
modified elements.
EX:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers. Map(number => number * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

3.reduce():
The reduce() method in JavaScript is used to apply a function to an
accumulator and each element in an array, in order to reduce it to a
single value. It iterates over each element in the array and
accumulates a value based on the provided function.
Ex :
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
Objects in JavaScript
 Object is nothing but the thing which has existence in the
world.
 A JavaScript object is an entity having state and behavior
(properties and method). For example: car, pen, bike, chair,
glass, keyboard, monitor etc.
 In java script object is used to store the data in key value pairs.
 JavaScript is an object-based language. Everything is an object
in JavaScript.
 Objects are mutable.
 We can access, update, add and delete the properties from an
object.
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 constructor function

1.By object literal.


The syntax of creating object using object literal is given below:
VariableName object=
{
property1:value1,
property2:value2,
propertyN:valueN
}
As you can see, property and value is separated by : (colon).
Example of creating object in JavaScript.
let emp={
id:102,
name:"Kumar",
salary:40000
}
2. By creating instance of Object directly (using new keyword).
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Example of creating object directly.
var emp=new Object();
emp.id=101;
emp.name="Ravi";
emp.salary=50000;
3.By using constructor function
• Here, you need to create function with arguments. Each
argument value can be assigned in the current object by using
this keyword.
• The this keyword refers to the current object.

In JavaScript, there are two main ways to access and manipulate


object properties: dot notation and bracket notation.
1. Dot notation
Dot notation is the most common way to access object properties. It
uses a period (.) to access the value of a property by its key.
Here’s an example:
const person = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'New York'
}
};
console.log(person.name); // John
console.log(person.address.city); // New York

2.Bracket notation:
Use square brackets [] to access the value of a property by its key.
Here’s an example:
console.log(person['name']); // John
console.log(person['address']['city']); // New York

OBJECT METHODS
• Objects can also have methods.
• Methods are actions that can be performed on objects.
OBJECT METHODS:
1.keys: It will return array of keys
console.log(Object.keys(mobile)); //array of keys
2.Values: It will return array of values
console.log(Object.values(mobile)); //array of values
3.Entries: It will return array of keys and values
console.log(Object.entries(mobile)); //array of keys and values
4.Assign: It is used to merge two objects
Object.assign(mobile,mobile1)
console.log(mobile);
let resObj=Object.assign({},mobile,mobile1);
console.log(resObj);
console.log(mobile);
console.log(mobile1);

5.Seal: We can only update the properties


Object.seal(mobile);
// console.log(mobile.brand); //access
// mobile.brand="redmi" //updation
// console.log(mobile.brand);
// mobile.battery="5000mah" //not able to add prop
// console.log(mobile);
// delete mobile.cost; //not able to delete
// console.log(mobile);

6.isSealed: It is used to check whether the particular object is


sealed or not
// console.log(Object.isSealed(mobile));
7.Freeze: We cannot do any modifications in an object
// Object.freeze(mobile);
// console.log(mobile.color); //access
// mobile.color="grey"; //cannot update
// console.log(mobile.color);
// mobile.battery="6000mah"; //cannot add
// console.log(mobile);
// delete mobile.camera; //cannot delete
// console.log(mobile);

8.Isfrozen: It is used to check whether the particular object is frozen


or not
// console.log(Object.isFrozen(mobile));
9.hasOwn: It is used to check whether the particular property is
present in an object or not.
// console.log(mobile.hasOwn("cost")); //true

let obj={
firstName:"Mahesh",
lastName:"Babu",
eid:123,
sal:25000,
address:{
city:"bng",
pin:560021
},
fullname:function(){
console.log(`${this.firstName} ${this.lastName}`);
}
}
obj.fullname();
Basics of web-technology
HTML : Hyper text markup language

To create the structure of the webpage

CSS : Cascading style sheet

Used for styling and alignment of HTML elements on the webpage

JS: JavaScript

Used to add the functionality

Terminologies

 WEB : The world wide web is also called as web and it is


interconnection of public websites which can be accessible
through internet
 INTERNET : It is system of interconnected computer networks
that allows users to access and share the information
 CLIENT : User
 BROWSER : It is a standalone application through which we can
access data with a help of internet
 SERVER : It is a combination of software and hardware that
receives request and response to a request over a network
 WEBPAGES : It is document that is accessible by browser and it
contains text,images,hyperlinks and these are also called as
building blocks of websites
 WEBSITES : It is collection of related or interconnected
webpages
How Web Works

Structure of URL
Types of websites

Static Website Dynamic Website

 User can’t modify the content  User can modify the content.
 Contents are static to all the user and same.  Contents are dynamic to all the user and different to
individual user.
 Is has more reloading time.
 Comparatively less reloading time.
 Most of the static websites are connected to
server, Interaction will be between browser and  Most of the dynamic websites follows 3 tier
server. architecture and N TIRE ARCHITECTURE, is browser ->
server -> database.
 Multi-page applications.
 Single page application.
 Ex : w3schools
 Ex : Instagram, facebook

HTML
 HTML stands for Hyper Text Markup Language.
 A reference / link created by developers to provide the
data / information to the users which is designed by pre-
defined tags and it comunicatable with browsers.
 This will be first page to rendered on the browsers.
 HTML is not case sensitive.
 .html/.htm are the extensions for HTML.
 HTML was introduced in 1991 by Tim Berners Lee
 First version of HTML is released in 1993—html 1.0
 Html 2.0----1995
 Html 3.2----1997
 Html 4.02----1999
 Html 5.0----2014
 Current version of html means now we are using html
5.0
Structure of HTML Document
<!DOCTYPE html>
<html Lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>JAVASCRIPT</title>
</head>
<body>

</body>
</html>

HTML Tags

TAG: Tag is predefined word or keyword which is enclosed


within angular braces
<html> </html>
Types of Tags
1) Paired Tags: These are the tags that will have an opening and
closing tags
Ex: <p> </p>, <head> </head> etc….
2) Unpaired tags: These are the tags that will not having any
closing tags and these are also called as self-closing tags
Ex: </br>, <hr>,<input>,<img> etc….

STRUCTURE OF HTML
 <!DOCTYPE HTML>--Represents the version of html
 <html>--Root element of the html page
 <head>--Contains meta information about the html page
 <title>--It will give the title for the webpage
 <body>--It is a document’s body and it is the container for all the visible
contents such as headings,paragraphs,images etc.

Basic HTML Tags

HTML Documents:

 All HTML documents must start with a document type declaration: <!DOCTYPE html>.

 The HTML document itself begins with <html> and ends with </html>.

 The visible part of the HTML document is between <body> and </body>.

HTML Headings:

 HTML headings are defined with the <h1> to <h6> tags.

 <h1> defines the most important heading. <h6> defines the least important heading

<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>

HTML Paragraphs:

 HTML paragraphs are defined with the <p> tag

HTML Elements
An HTML element is defined by a start tag, some content, and an
end tag.
Tags along with the content is known as element
Ex: <h1>Hello World</h1>
 BLOCK LEVEL ELEMENTS: It will take entire width of the
browser and these are starts from new line
Ex:<div>, <table>, <form>, <nav><nav>
 INLINE ELEMENTS: It will take only content width
These are starts from the same line means next to each other
Ex:<span>, <b>, <i>, <u>

HTML Attributes
 HTML attributes provide additional information to HTML
tags.
 All HTML elements can have attributes
 Attributes are always specified in the start tag/opening tag
 Attributes usually come in name/value pairs
like: name="value“.
 Values of an attributes are case sensitive

Core Attributes:
 Id: It is used to target a particular element uniquely.
 Class: The class attribute specifies one or more classnames
for an element
 Title: The title attribute gives a suggested title for the
element. It is used to give tooltip for the element.
 Style : It specifies an inline style for an element.

HTML Formatting
Formatting elements were designed to display special types of text
 <b> - to display bold text
 <strong> - display bold text and according to browser it has
extra importance
 <i> - display Italic text
 <em> - display Emphasized(italic) text
 <u> - display underlined text
 <ins> - very similar to <u>, according to browser it will be
inserted text
 <strike> - display striked text
 <del> - very similar to <strike>, according to browser it will be
deleted text
 <mark> - display highlighted text
 <sub> - display subscript text
 <sup> - display superscript text

Sectioning Elements / Semantic Elements


 A semantic element clearly describes its meaning to both the
browser and the developer.
 Examples of semantic elements: <form>, <table>,
and <article> - Clearly defines its content.
 Examples of non-semantic elements: <div> and <span> - Tells
nothing about its content.
 Semantic elements represent their meaning to both the
browser and developer.
 All semantic elements are block level
 HDAMNSTAFF
 H àHEADER
 D àDETAILS
 A àASIDE
 M àMAIN
 N àNAV
 S àSUMMARY AND SECTION
 T àTABLE
 A àARTICLE
 F àFIGURE
 F àFIGCAPTION/FOOTER

HTML Lists
1.Unordered HTML List:
 An unordered list starts with the <ul> tag. Each list item starts with
the <li> tag.
 The list items will be marked with bullets (small black circles) by default
 Attributes
 Type : square,circle,none
2.Ordered HTML List:
 An ordered list starts with the <ol> tag. Each list item starts with
the <li> tag.
 The list items will be marked with numbers by default
 Attributes:
 Type : numbers,alphabets(lower,upper),roman(lower,upper)
 Start: number
 reverse
3.Description Lists:
 A description list is a list of terms, with a description of each term.
 The <dl> tag defines the description list, the <dt> tag defines the term
(name), and the <dd> tag describes each term
Nested Lists:
 List inside another list is called as nested list.
HTML Image
 <img> tag is used to insert an image in webpage
 Image is inline-block element
Attributes
 src: It is an attribute of img tag, inside this we will pass the path of the
image.
 alt: It is used give the alternative name for the image
 When the image is not displaying on webpage this alternative name will
be displayed
 height: It is used give the height for the image
 width: It is used give the width for the image

Anchor tag / Hyperlinks


 The <a> tag defines a hyperlink, which is used to link from one page to
another.
 The most important attribute of the <a> element is the href (hyper
reference) attribute, which indicates the link's destination.
 By default, links will appear as follows in all browsers:
• An unvisited link is underlined and blue
• A visited link is underlined and purple
• An active link is underlined and red
Text as a Link
 To use a text as a link, just write the text inside the <a> tag with href
attribute
Image as a Link
 To use an image as a link, just put the <img> tag inside the <a> tag
Button as a Link
 To use a button as a link, just put the <button> tag inside the <a> tag
Absolute URL v/s Relative URL

Absolute URL Relative URL

1) a full web address in 1) A local link (a link to a


the href attribute. page within the same
2) <p><a href="https://www.w3.org/" website) is specified with
>W3C</a></p> a relative URL (without
the "https://www" part):
2) <p><a href="html_images
.asp">HTML
Images</a></p>

The target Attribute in <a> tag


 By default, the linked page will be displayed in the current browser
window. To change this, you must specify another attribute that is target
for the link.
 The target attribute specifies where to open the linked document.
 The target attribute can have one of the following values:
à _self - Default. Opens the document in the same window/tab as it was
clicked
à _blank - Opens the document in a new window or tab
à _parent - Opens the document in the parent frame
à _top - Opens the document in the full body of the window
HTML TABLE
 A table in HTML consists of table cells inside rows and columns.
 <table> tag is used to create a table in html
 <thead> and <tbody> to represent heading section and body
section of table
 Table Headers: Sometimes you want your cells to be table
header cells. In those cases, use the <th> tag
 Table Rows: Each table row starts with a <tr> and ends with
a </tr> tag.
 Table Cells: Each table cell is defined by a <td> and a </td> tag.

Table attribute
 border: It is used give the border to table. (<table>)
 cellpadding: It is the space between the cell edges and the cell
content. (<table>)
By default, the padding is set to 0
 cellspacing: It is the space between each cell.
By default, the space is set to 2 pixels.
 colspan: It is used to merge multiple columns. (<td>)
 rowspan: It is used to merge multiple rows. (<td>)
HTML FORMS
The <form> Element
 The HTML <form> element is used to create an HTML form for
user input
 The <form> element is a container for different types of input
elements, such as: text fields, checkboxes, radio buttons,
submit buttons, etc.
 The <input> Element
 The HTML <input> element is the most used form element.
 An <input> element can be displayed in many ways, depending
on the type attribute.
 Ex:
 <input type="text">Displays a single-line text input field
 <input type="password">Displays a password input field (dots
will be displayed instead of the data)
 <input type="email">Displays a email input field (will give
suggestion to include ‘@’ symbol)
 <input type="date">Displays a date input field (gives calendar
to select the date)
 <input type="file">to get file kind of data(we can use accept
attribute to represent type of file the file and we can
pass .doc, .pdf, .xml)
 <input type="number"> to get number kind of data
 <input type="tel"> to get contact number, Aadhaar number
kind of data
 <input type="radio">Displays a radio button (for selecting one
of many choices)
 <input type="checkbox">Displays checkbox (for selecting zero
or more of many choices)
 <input type="button">Displays a clickable button
 <input type="submit">Displays a submit button (for submitting
the form)
 <input type="reset">Displays a reset button (for resetting the
form)

 <textarea> Defines a multiline input control (text area)


 <select> Defines a drop-down list
 <option> Defines an option in a drop-down list
 <optgroup> to create dropdown with groups / Defines a group
of related options in a drop-down list
 <label> Defines a label for an <input> element
 <fieldset> Groups related elements in a form
 <legend> Defines a caption for a <fieldset> element
 <button> Defines a clickable button
 <datalist> Specifies a list of pre-defined options for input
controls

Form Attributes
 <form>
 Action: It defines action to be performed when the form is
submitted.
 Method: It specifies the http method to be used when submitting
the form data. (get-Not secured and post-Secured)
 <label>
 for: It is used to connect label and input text field.
 <input>
 Id: It is used to connect label and input text field and the
value passed in the id attribute should be same as the
value passed in the for attribute.
 Name: The value of name attributes acts like container,
The form values with name attribute will sent to a server
when submitting the form.
 Type: It represents the type of data

Form Validation Attributes


1) value: The input value attribute specifies an initial value for an
input field
2) readonly: The input read only attribute specifies that an input field
is read-only.
3) disabled: The input disabled attribute specifies that an input field
should be disabled.
 A disabled input field is unusable and un-clickable.
4) size: The input size attribute specifies the visible width, in
characters, of an input field.
 The default value for size is 20.
 Note: The size attribute works with the following input types:
text, search, tel, url, email, and password.
5) Maxlength: The input maxlength attribute specifies the maximum
number of characters allowed in an input field.
6) Min & Max: The input min and max attributes specify the
minimum and maximum values for an input field.
7) Placeholder: The input placeholder attribute specifies a short hint
that describes the expected value of an input field (a sample value or
a short description of the expected format).
8) Required: The input required attribute specifies that an input field
must be filled out before submitting the form.
9) Autofocus: The input autofocus attribute specifies that an input
field should automatically get focus when the page loads.
10) Height & Width: The input height and width attributes specify
the height and width of an <input type="image"> element.
11) List: The input list attribute refers to a <datalist> element that
contains pre-defined options for an <input> element.
12) multiple: The input multiple attribute specifies that the user is
allowed to enter more than one value in an input field.
The multiple attribute works with the following input types: file.
HTML MEDIA
Multimedia on the web is sound, music, videos, movies.
HTML media consist of audio, video and maps
 Audio:
o <audio> tag is used to embed the audio into our web
page.
o The content which is written in side <audio></audio> will
not display on the webpage (void element)
Attributes of audio tag:
 src: we will pass path of audio.
 controls: The controls attribute adds audio controls, like
play, pause, and volume.
 muted: It will mute the audio when you open your file
with browser
 autoplay: It will play the audio automatically when you
open your file with browser.
 loop: The audio will start over again, every time it is
finished.
 Video :
o <video> tag is used to embed the video into our web
page.
o The content which is written in side <video></video> will
not display on the webpage
Attributes of audio tag:
 src: we will pass path of video.
 controls: The controls attribute adds video controls, like
play, pause, and volume.
 muted: It will mute the video when you open your file
with browser
 autoplay: It will play the video automatically when you
open your file with browser.
 loop: The video will start over again, every time it is
finished.
 iframe:
 <iframe> tag is used to embedded another document
within the current HTML document.
 An HTML iframe is used to display a web page within a
web page.
 The HTML <iframe> tag specifies an inline frame.
 Height and width attributes are used to specify the height
and width of th iframe
 Title attribute is used to give the title for the iframe
Java Script
// JS
JavaScript
 JavaScript is the most popular programming language which is used to
create interactive webpages
 JavaScript is the client-server side scripting language which is used to
create dynamic web pages
 JavaScript was invented by Brendan Eich in 1995, and became
an ECMA standard in 1997.
 ECMA-262 is the official name of the standard. ECMAScript is the
official name of the language.
 Current version of JS is ES6 (introduced after 2015)
Characteristics of JavaScript
 Client-side scripting language : The code is readable analyzable and
executable by browser itself
 Interpreted Language : JavaScript is an interpreted language, meaning it
is executed line by line at runtime.
 Dynamically typed Language : JavaScript is dynamically-typed, which
means you don't need to specify the data type of a variable when declaring
it. The type is determined at runtime.
 Weakly Typed Language : Semicolon is not mandatory at all the time
 Synchronous in nature : It will execute line by line; we can make it as
asynchronous
Advantages of JS

 Easy to learn and implement


 Reduces server load
 Efficient performance
 Regular updates
 Platform independent
 It has more frameworks and libraries
Environmental Setup
 We can run JavaScript code in two environments.
 Browser
 Node.js
 Browser understand the js through JS engine and Every browser consists
of JavaScript engine which helps to run JS code

Browser JS engine
Chrome V8
Mozilla Firefox Spider monkey
Microsoft Edge Chakra
Safari JavaScript Core Webkit
How to include JS in HTML

❑ We can insert JS code to HTML in two ways

1.Internal JS
2.External JS
Output Methods

 Console.log(“hello”)
 It will print the output in console window
 Document.write(“Hello”)
 It will print the output in user interface
 Document.writeln(“Hello”)
 It will print the output in user interface
Tokens

 Building blocks of every programming language

1. Keywords : Predefined words whose task is already predefined


2. Identifiers : The name given for the variables ,arrays , objects etc..
3. Literals : The values written by developer
Variables

 In JavaScript We have 3 keywords to declare variables(var , let , const)


 Syntax To declare variable:
var/let/const identifier;
var/let/const identifier=value;
Var , let and const

var Let Const

Declaration yes yes Declaration with


initialization

Initialization Yes Yes No

Reinitialization Yes Yes No

Redeclaration Yes No No

Scope Global scope Script scope Script scope

Hoisting Yes Yes(TDZ) Yes(TDZ)


Hoisting

 Hoisting is JavaScript's default behavior of moving all


declarations to the top of the current scope (to the top of the
current script or the current function).
 In JavaScript, a variable can be declared after it has been used.

Example:

console.log(myVar); // Outputs: undefined


var myVar = 42;
The let and const Keywords

 Variables defined with let and const are hoisted to the top of the
block, but not initialized.
 Meaning: The block of code is aware of the variable, but it cannot
be used until it has been declared.
 Using a let variable before it is declared will result in
a ReferenceError.
 The variable is in a "temporal dead zone" from the start of the
block until it is declared:
 A temporal dead zone (TDZ) is the area of a block where a variable is
inaccessible until the moment the computer completely initializes it with a
value.
Datatypes in JS
 Datatype defines the type of data to be stored in a particular memory
allocation
JavaScript has Datatypes(primitive)
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol

 Non primitive
A function
An object
An array
Datatypes
 String : We can declare the string in js in 3 ways
 Example : ‘hello’ ,”hello” ,`Hello everyone`
 Number : Integer and floating point numbers
 Boolean : True or false
 Bigint : large amount of data
 Undefined : It represents the value of an uninitialized values
 Null : It is empty variable and for future use
 Symbol : It will create function
Operators in JS
 Predefined symbols used to perform particular task
 Types of operators
• Arithmetic Operators : +,-,*,/,%,++,--
• Assignment Operators : +=,-=,*=,/=,%=,=
• Comparison Operators : >,<, !=,>=,<=,==,===
• Logical Operators : && , || , !
• Ternary Operators : ( condition ) ? True stmt : false stmt
Conditional Statements
 Conditional statements are used to perform different actions
based on different conditions.
•Use if to specify a block of code to be executed, if a specified
condition is true
•Use else to specify a block of code to be executed, if the same
condition is false
•Use else if to specify a new condition to test, if the first condition is
false
•Use switch to specify many alternative blocks of code to be
executed
Loops in JS

 Loops can execute a block of code a number of times

while loop : Repeats a statement or group of statements while a


given condition is true. It tests the condition before executing the
loop body

Do while loop : It is more like a while statement, except that it


tests the condition at the end of the loop body.

For loop : Executes a sequence of statements multiple times and


abbreviates the code that manages the loop variable
Functions In JS
 A JavaScript function is a block of code designed to perform a
particular task.
 A JavaScript function is executed when "something" invokes it (calls
it).
 With functions you can reuse code
 You can write code that can be used many times.
 You can use the same code with different arguments, to produce
different results.

 Syntax :
 function myFunction(p1, p2) {
return p1 * p2;
}
JavaScript Function Syntax

 A JavaScript function is defined with the function keyword,


followed by a name, followed by parentheses ().
 Function names can contain letters, digits, underscores, and
dollar signs (same rules as variables).
 The parentheses may include parameter names separated by
commas:
(parameter1, parameter2, ...)
 The code to be executed, by the function, is placed inside curly
brackets: {}
Types of Functions in JS

1. Anonymous function
2. Named function
3. Function with expression
4. Nested function
5. Immediate invoking function
6. Arrow function
7. Higher order function
8. Callback function
9. Generator function
1.Anonymous function

 A function without name is known as Anonymous function

 Syntax :
 function(parameters) {
// function body
}
2. Named Function

 A function with name is called as named function

 Syntax :

 function functionName(parameters) {
// function body
}
3 . Function with expression

 It is the way to execute the anonymous function


 Passing whole anonymous function as a value to a variable is known as
function with expression.
 The function which is passed as a value is known as first class function

EX : let x=function(){
//block of code
}
x();
Nested function
 A function which is declared inside another function is known as nested
function.
 Nested functions are unidirectional i.e., We can access parent function
properties in child function but vice-versa is not possible.
 The ability of js engine to search a variable in the outer scope when it is not
available in the local scope is known as lexical scoping or scope chaining.
 Whenever the child function needs a property from parent function the
closure will be formed and it consists of only required data.
 A closure is a feature of JavaScript that allows inner functions to access the
outer scope of a function. Closure helps in binding a function to its outer
boundary and is created automatically whenever a function is created. A block
is also treated as a scope since ES6. Since JavaScript is event-driven so
closures are useful as it helps to maintain the state between events.
Nested function
Function parent(){
let a=10;
function child(){
let b=20;
console.log(a+b);
}
Child();
}
Parent();
JavaScript currying
 Calling a child function along with parent by using one more parenthesis
is known as java script currying
 Example:
Function parent(){
let a=10;
function child(){
let b=20;
console.log(a+b);
}
return child;
}
parent()(); ==JavaScript currying
Immediate invoking function(IIF)

 A function which is called immediately as soon as the function


declaration is known as IIF
 We can invoke anonymous function by using IIF
 Example:

(function(){
console.log(“Hello”);
})();
Arrow function

 It was introduced in ES6 version of JS.


 The main purpose of using arrow function is to reduce the syntax.
 If function has only one statement then block is optional.
 It is mandatory to use block if function consists of multiple lines of code
or if we use return keyword in function.
 Example:
Let x=(a,b)=>console.log(a+b);
Let y=(a,b)=>{return a + b };
Higher order function(HOF)
 A function which accepts a function as a parameter is known as HOF
 It is used to perform multiple operations with different values.
 Example:
Function hof(a , b , task ){
Let res=task(a,b);
return res;
};
Let add=hof(10,20,function(x , y){
return x + y;
}
Let mul = hof(10,20,function(x , y){
return x*y;
}
Console.log(add());
Console.log(mul());
Callback function
 A function which is passed as an argument to another function is known as callback function.
 The function is invoked in the outer function to complete an action
 Example :
function first(){
Console.log(“first”);
}
function second(){
Console.log(“third”);
}
function third(callback){
Console.log(“second”);
Callback()
}
first();
third(second);
Generator function
 A generator-function is defined like a normal function, but whenever it
needs to generate a value, it does so with the yield keyword rather than
return.
 Example:
Function* gen(){
Yield 1;
Yield 2;
…….
………
}
Let res=gen();
Console.log(res.next().value);
Console.log(res.next().value);
Console.log(res.next().value);
JAVASCRIPT ARRAYS
ARRAYS:- Array is collection of different elements.Array is heterogrnous in nature.

• In javascript we can create array in 3 ways.

1. By array literal
2.By using an Array constructor (using new keyword)

1) JavaScript array literal:-


• The syntax of creating array using array literal is: var arrayname=[value1,value2.....valueN];
• As you can see, values are contained inside [ ] and separated by , (comma).
• The .length property returns the length of an array.
Ex:-<script>
var emp=["Sonoo","Vimal","Ratan"]; Output
for Sonoo
(i=0;i<emp.length;i++){ document.wri Vimal
te(emp[i] + "<br/>"); Ratan
}
</script>
2) JavaScript array constructor (new keyword):-
Here, you need to create instance of array by passing arguments in constructor
so that we don't have to provide value explicitly.

Ex:-
<script>
var emp=new
Array("Jai","Vijay","Smith"); for
(i=0;i<emp.length;i++){ document
.write(emp[i] + "<br>");
}
</script>

Output:-
Jai
Vijay
Smith
Java script Array methods
 push() : It will insert an element of an array at the end
 unshift() : It will insert an element of an array at the first
 pop() : It will remove elements of array from the end
 shift() : It will remove elements of array from the start
 indexOf() :It will return a index of particular element
 Includes() : It will check whether the particular element is present in
array or not.
 At() : It will return the element which is present in particular index.
 Slice() : It will give slice of an array and it will not affect the original
array.
 Splice() : It is used to add or remove elements from an array
Java script Array methods

 Join() : It is used to join all elements of an array into a string.


 Concat() : It is used to join/concat two or more arrays.
 toString() : It converts all the elements in an array into a single string
and returns that string.
 Split() : It is used to split a string into an array.
 Reverse() : It is used to reverse an array.
 Array.from() : It will convert string into an array
Filter() , map() , reduce()
 Filter() :
 The filter() method in JavaScript is used to create a new array with all elements that pass a test
specified by a provided function. It does not modify the original array.
 Example :
 let newArray = array. Filter(callback(element[, index, array]){
thisArg;
}

•callback: This is the function that is used to test each element in the array. It takes three arguments:
•element: The current element being processed in the array.
•index (optional): The index of the current element being processed.
•array (optional): The array filter was called upon.
•thisArg (optional): Value to use as this when executing callback.
Filter() , map() , reduce()
 Map() :
The map() method in JavaScript is used to create a new array by applying a
function to every element in an existing array. It does not modify the original
array. Instead, it returns a new array with the modified elements.
EX:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers. Map(number => number * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
Filter() , map() , reduce()

 Reduce() :
The reduce() method in JavaScript is used to apply a function to an accumulator and each
element in an array, in order to reduce it to a single value. It iterates over each element
in the array and accumulates a value based on the provided function.
 Ex :
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
Objects in JS
 Object is nothing but the thing which has existence in the world.
 A JavaScript object is an entity having state and behavior (properties and
method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.
 In java script object is used to store the data in key value pairs.
 JavaScript is an object-based language. Everything is an object in JavaScript.
 Objects are mutable.

 We can access , update, add and delete the properties from an object.
OBJECTS IN JAVASCRIPT
• A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.

• JavaScript is an object-based language. Everything is an object in JavaScript.

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).
OBJECTS IN JAVASCRIPT

• A JavaScript object is an entity having state and behavior (properties and


method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.

• JavaScript is an object-based language. Everything is an object in JavaScript.

 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 constructor function


1)JavaScript Object by object literal:

The syntax of creating object using object literal is given below:


VariableName object=
{
property1:value1,
property2:value2,
propertyN:valueN
}
As you can see, property and value is separated by : (colon).

Example of creating object in JavaScript.


<script>
Let emp={
id:102,
name:"Kumar", salary:40000
}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
2) By creating instance of Object:

The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

Example of creating object directly.

<script>
var emp=new Object(); emp.id=101;
emp.name="Ravi"; emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
3) By using an constructor function:

• Here, you need to create function with arguments. Each argument value can
be assigned in the current object by using this keyword.
• The this keyword refers to the current object.

The example of creating object by object constructor is given below.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
Var e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
In JavaScript, there are two main ways to access and manipulate object properties: dot
notation and bracket notation.
1. Dot notation
Dot notation is the most common way to access object properties. It uses a period (.) to access the value of a property by its key.
Here’s an example:
const person =
{ name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'New York'
}
};
console.log(person.name); // John
console.log(person.address.city); // New York
Bracket notation, on the other hand, uses square brackets [] to access the
value of a property by its key.
Here’s an example:
console.log(person['name']); // John
console.log(person['address']['city']); // New
York
OBJECT METHODS
• Objects can also have methods.
• Methods are actions that can be performed on objects.

OBJECT METHODS:

1.keys : It will return array of keys


2.Values : It will return array of values
3.Entries : It will return array of keys and values
4.Assign : It is used to merge two objects
5.Seal : We can only update the properties
6.isSealed : It is used to check whether the particular object is sealed or not
7.Freeze : We cannot do any modifications in an object
8.Isfrozen : It is used to check whether the particular object is frozen or not
9.hasOwnProperty : It is used to check whether the particular property is present in an object or not.
let obj4={
ename:"lavanya",
id:123,
sal:20000
};
let obj5={
ename1:"bujji",
id1:12,
sal1:40000
};
console.log(Object.keys(obj4));//array of keys
console.log(Object.values(obj4))//array of values
console.log(Object.entries(obj4))//array of keys and values
console.log(Object.assign({},obj4,obj5))//merge multiple objects
console.log(obj4)//stroring all properites of obj5 into obj4 Object.seal(obj4);//In
seal method i can update can’t add,i cant remove,can
fetch
console.log(Object.isSealed(obj4));//true
delete obj4.ename;
console.log(obj4)

obj4.sal=12000;
console.log(obj4);
console.log(obj4.sal);

Object.freeze(obj4);
console.log(Object.isFrozen(obj4))//true
obj4.skills="html";
obj4.sal=300;
console.log(obj4)
console.log(obj4)//freeze object we cant add,we cant update,we cant delete,we
can fetch
delete obj4.id
console.log(obj4);
console.log(obj4.hasOwnProperty("ename"));//if the property is present means it
will return true else false
LOOPS IN JAVASCRIPT

• Loops can execute a block of code a number of times.


• foreach- loops through a block of code a number of times
• for/in- loops through the properties of an object
• for/of- loops through the values of an iterable object
Foreach():-
The forEach() method calls a function for each element in an array.
The forEach() method is not executed for empty elements.

Example:
const array1 = ['a', 'b', 'c’];

array1.forEach((element) => console.log(element));


Output:- 1
2
3
4
5

For of loop:-
Iterable objects are objects that can be iterated over with for..of.
<script> Ex:-const name = "W3Schools";
let text = ""
for (const x of
name){ text += x +
"<br>";
}
For in loop:-
The JavaScript for in loop iterates over the keys of an object
Ex:-

const object = { a: 1, b: 2, c: 3 }; for


(const property in object) {
console.log(`${property}: ${object[property]}`);
}

// Expected output:
// "a: 1“
// "b: 2“
// "c: 3“

DATE OBJECT:-

• When a date object is created, a number of methods allow you to operate on it.

• Date methods allow you to get and set the year, month, day, hour, minute, second,
and
millisecond of date objects, using either local time or UTC (universal, or GMT) time.
Creating Date Objects
Date objects are created with the new Date()constructor. There are 9 ways to
create a new date object:

new Date()
new Date(date string)
new Date(year,month)
new Date(year,month,day)
new Date(year,month,day,hours)
new Date(year,month,day,hours,minutes)
new Date(year,month,day,hours,minutes,seconds)
new Date(year,month,day,hours,minutes,seconds,ms)
new Date(milliseconds)

JavaScript new Date():-


new Date()creates a date object with the current date and time:
Const d= new Date( );
console.log(d);
Output:-
Sun Aug 27 2023 18:42:42 GMT+0530 (India Standard Time)
MATH OBJECT

• The JavaScript Math object allows you to perform mathematical tasks on numbers.

• Unlike other objects, the Math object has no constructor.


• The Math object is static.
• All methods and properties can be used without creating a Math object first.
• The syntax for any Math property is : Math. method(number)
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 (new in ES6)


1.Math.round(4.6);
OUTPUT:-5 4.Math.trunc(4.9);
Math.trunc(4.7);
Math.round(4.5); Math.trunc(4.4);
OUTPUT:4
Math.trunc(4.2);
Math.round(4.4); Math.trunc(-4.2);
OUTPUT:4
Output:4
2. Math.ceil(4.9);
Math.ceil(4.7);
Math.ceil(4.4);
Math.ceil(4.2);
output:-5

3. Math.floor(4.9);
Math.floor(4.7);
Math.floor(4.4);
Math.floor(4.2);

Output:4
STRING CONCEPT IN JAVASCRIPT

STRING:-Collection of characters (or) bunch of characters we called it as string

String methods:-

String length String trim()


String slice() String trimStart()
String substring() String trimEnd()
String substr() String padStart()
String replace() String padEnd()
String replaceAll() String charAt()
String toUpperCase() String charCodeAt()
String toLowerCase() String split()
String concat()
1. The lengthproperty returns the length of a string:

Ex:-
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.log(text.length)//26

2.slice() extracts a part of a string and returns the extracted part in a new string. The
method takes 2 parameters: start position, and end position (end not included).
Ex:-
let text = "Apple, Banana, Kiwi";
let part = text.slice(7,13);//banana

3.substring( ):- it is similar to slice( )


Syntax:-substring(start,end)
The difference is that substring( ) cannot accept negative indexes.
Ex:-
let text = "Apple, Banana, Kiwi";
let part = text.substring(7,13);//banana
4.substr( ):-
Substr( ) is similar to slice( )
 The difference is that the second parameter specifies the length of the extracted part.
 Ex:-
 let text = "Apple, Banana, Kiwi";
 let part = text.substr(7,6);//banana

5. replace( ):-The replace method replaces a specified value with another value in a string By
default,the replace( ) method replaces only the first match.
 Ex:-
 let text = "Please visit Microsoft!";
 let newText = text.replace("Microsoft", “js");//”please visit js

6.trim( ):-
 The trim( ) method removes whitespace from both sides of a string. Ex:-
 let text1 = " Hello World! ";
 let text2 = text1.trim();//hello world!
7.indexOf( ):-
The indexOf( ) method returns the index of the position of the first occurrence of a
specified text in a string.
indexOf( ) return -1 if the text is not found.
Ex:-
Let str=“please locate where ‘locate’ occurs!”;
str.indexOf(“locate”);//7
Str.indexOf(“locate”);//-1
8.lastIndexOf( ):-
The lastIndexOf() method of String values searches this string and returns the index of
the last occurrence of the specified substring. It takes an optional starting position and
returns the last occurrence of the specified substring at an index less than or equal to
the specified number.
Ex:-
Let str=“please locate where ‘locate’ occurs!”;
str.indexOf(“locate”);//21
Str.indexOf(“locate”);//-1
9.Includes( ):-

The includes()method returns trueif a string contains a specified string.


Otherwise it returns false.
The includes()method is case sensitive.

Syntax:-string.includes(searchvalue, start)

Ex:-
let text = "Hello world, welcome to the universe.";
let result = text.includes("world");//true

10. repeat( ):-


The repeat()method returns a string with a number of copies of a string.
The repeat()method returns a new string.
The repeat()method does not change the original string
let text = "Hi";
let result = text.repeat(2);//hi hi

11. charAt( ):-

it will return the character of the specified position

Ex:-
var str=“hi guys”
Console.log(str.charAt(3));//g

12. charCodeAt( ):-

It will return the ASCII value of specified index value of that character. Ex:-
Ex:-var str=“javascript”
Console.log(str.charCodeAt(1));//97 Split( ):-
covert string to array.
Join( ):-convert array to string
BOM and DOM
BROWSER OBJECT MODEL AND DOCUMENT OBJECT MODEL
BOM(Browser Object Model)

 The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
 "BOM" stands for Browser Object Model. It represents the objects that a browser
provides to JavaScript to interact with the browser itself.
 The BOM includes objects like:
BOM
Window: The global object in a browser's environment. It represents the browser window or tab
and contains properties like window. location (which gives information about the current
URL), window. document (which refers to the DOM document in the current window), and
many others.

1. Document: Represents the DOM (Document Object Model) of a web page. It provides
methods and properties to interact with the contents of the page.
2. Location: Represents the current URL of the browser and allows you to interact with it.
3. Navigator: Provides information about the browser itself, such as its name, version, and
capabilities.
4. Screen: Represents the user's screen. It provides information about the dimensions and pixel
depth of the screen.
5. History: Allows manipulation of the browser's history (back, forward, etc.).
Window. Screen
 The window.screen object contains information about the user's
screen.
 The window.screen object can be written without the window
prefix

Properties:
•screen.width
•screen.height
•screen.availWidth
•screen.availHeight
•screen.colorDepth
•screen.pixelDepth
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.
 Some examples:
•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.location.assign() loads a new document
Window.history and window.navigator
 Window.history object contains the browser history.
 Some methods:
•history.back() - same as clicking back in the browser
•history.forward() - same as clicking forward in the browser

 Window.navigator object contains information about the visitor’s browser


 Examples:
•navigator.cookieEnabled : property returns true if cookies are enabled, otherwise false.
•navigator.appCodeName :property returns the application code name of the browser.
•navigator.platform : property returns the browser platform (operating system).
JavaScript Popup Boxes

 JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
 An alert box is often 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.
JavaScript Popup Boxes
Confirm Box
 A confirm box is often used if you want the user to verify or accept
something.
 When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
 If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.
JavaScript Popup Boxes
Prompt Box :
 A prompt box is often used if you want the user to input a value
before entering a page.
 When a prompt box pops up, the user will have to click either "OK"
or "Cancel" to proceed after entering an input value.
 If the user clicks "OK" the box returns the input value. If the user
clicks "Cancel" the box returns null.
DOM(Document Object Model)
 In JavaScript, the DOM (Document Object Model) is a programming interface for
web documents. It represents the structure of a document as a tree-like model
where each node is an object representing a part of the document, such as
elements, attributes, and text.
 When a web page is loaded, the browser creates
a Document Object Model of the page.
 The HTML DOM model is constructed as a tree of Objects:
DOM(Document Object Model)
 In JavaScript, the DOM (Document Object Model) is a programming interface for
web documents. It represents the structure of a document as a tree-like model
where each node is an object representing a part of the document, such as
elements, attributes, and text.
 When a web page is loaded, the browser creates
a Document Object Model of the page.
 The HTML DOM model is constructed as a tree of Objects:
DOM Manipulation

• 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
DOM Methods
 Methods used to target HTML elements in JavaScript file

 getElementById(id): This method allows you to retrieve an element from


the document by its unique id.
 getElementsByClassName(className): This method returns a collection
of all elements in the document with a specified class name.
 getElementsByTagName(tagName): Returns a collection of elements with
the specified tag name.
 querySelector(selector): Returns the first element that matches a
specified CSS selector.
 querySelectorAll(selector): Returns a NodeList of all elements that match
a specified CSS selector.
Changing HTML Elements
Property Description

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

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


DOM Event Listener
 The addEventListener() method attaches an event handler to the
specified element
 The first parameter is the type of the event (like "click" or "mousedown"
or any other HTML DOM Event.)
 The second parameter is the function we want to call when
the event occurs.
 Ex:
element.addEventListener("click", function(){
alert("Hello World!");
});
DOM Events
 Event: An action performed by the user on the webpage is known
as an event
 A JavaScript can be executed when an event occurs, like when a
user clicks on an HTML element.
 Click
 Mouseover
 Mouseout
 Mousedown
 Mouseup
 Contaxmenu
 Doubleclick
 Keypress
 Keyup
 Keydown
 submit
Event Propagation
 Event propagation refers to the way events travel through the DOM tree.
When an event occurs on an element, it can trigger event handlers not
only on that element but also on its parent elements, all the way up to the
root of the document. There are two phases of event propagation:
1. Capturing Phase: The event travels from the root of the DOM tree down
to the target element.
2. Bubbling Phase: The event then bubbles up from the target element back
to the root.
 event.stopPropagation(): This method prevents further propagation of
the current event. It stops the event from bubbling up the DOM tree or from
capturing down the tree
JSON(Java Script Object Notation)
 It is format of storing and transporting data.
 It is used when the data is sent form the server to web page
 It is a popular data format for developers because of its human readable
text, light weight which requires less coding and faster process
Example: [
{“fname”:”Ram”,”lname”:”Patil”},
{“fname”:”Raj”,”lname”:”smith”},
{“fname”:”Ashish”,”lname”:”gouda”}
]
Syntax of JSON

 Data is in Key value pairs


 Data is separated by ‘,’
 Curly braces holds objects
 [ ]---holds array
In JavaScript, there are two main methods used to work with JSON
(JavaScript Object Notation):
1.JSON.Stringify() : used to convert normal object to JSON format
2.JSON.parse(): Used to convert JSON format of data to normal object
Time delays
 setTimeOut() and setInterval() are two functions in js allows
to schedule tasks to be executed at later time. Used for
animations, polling data from server and other asynchronous
tasks.
 setTimeOut() :
 Runs the code with time delay
Syntax : window.setTimeOut( function , delay ) ;
•function: The function you want to execute.
•delay: The amount of time (in milliseconds) before the function
is executed
Time delays
 setInterval() :
 The function similar to setTimeOut, but it schedules a
function to be executed repeatedly at specified interval.
Syntax : window.setInterval( function , delay ) ;
•function: The function you want to execute.
•delay: The amount of time (in milliseconds) before the function
is executed
 createTimeOut() and createInterval()
 cancel asetTimeout, you use clearTimeout
 cancel a setTimeout, you use clearTimeout
Promises
Promises in JavaScript are a powerful way to work with asynchronous code. They provide
a clean and more readable syntax for handling operations that may take an unknown
amount of time to complete, such as fetching data from a server or reading a file.
A promise represents the eventual result of an asynchronous
operation. It can be in one of three states:
• Pending: Initial state, neither fulfilled nor rejected.
• Fulfilled: Meaning the operation completed successfully.
• Rejected: Meaning the operation failed.
Syntax to create promise
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation, e.g., fetching data from a server.

if (/* operation successful */) {


resolve('Success data'); // Resolve if successful.
} else {
reject('Error message'); // Reject if there's an error.
}
});
Consuming a Promise:

 Then() : It will executed when the promise will be in


resolved state
 Catch() : It will get executed when the promise is in rejected
state
 Finally() : It will execute always means promise is in
resolve , reject or in pending state
async and await

 "async and await make promises easier to write"


 async makes a function return a Promise
 await makes a function wait for a Promise

 Async : The async keyword is used to define a function that returns a promise.
 Await : The await keyword is used inside an async function to wait for a Promise to
settle (either resolve or reject). It can only be used inside an async function

You might also like