0% found this document useful (0 votes)
3 views75 pages

JavaScript Notes - 1

Uploaded by

otanuja24
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)
3 views75 pages

JavaScript Notes - 1

Uploaded by

otanuja24
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

JavaScript

What is JavaScript?

• It is both scripting and programming [Link] to add functionality to html element in


frontend and also used to processing action in backend.
• It can be used for both frontend and backend development.
• It is a scripting language for frontend helps to add functionality/behavior of html element in
web browser.
• It is programming language for backend it processes the action using nodejs.
• JavaScript was invented by Brendan Eich in 1995.

Role of JS in Web Development:


• It is used to add functionality and interactivity to the web page.
• It is a light weight and object based programming language.
• Java Script can be directly embedded to HTML page.
• JavaScript is an interpreted language.
• It is an open-source language.
• JavaScript is case sensitive language.

Where JS Runs?
• JavaScript is an interpreted language, meaning it is executed by a JavaScript engine
inside browsers (or outside using [Link]).
• Di erent browsers use di erent JS engines like Firefox uses SpiderMonkey, Chrome
uses V8, Safari uses JavaScriptCore, Microsoft Edge uses Chakra
• A JS engine has the following key parts: Parser, Compiler (JIT – Just In Time), Memory
Heap and Call Stack.
• The parser reads your JS code line by line, checks for syntax [Link] everything is
valid, it passes code to the compiler.
• The compiler converts JS code into bytecode.
• The memory heap stores objects, variables, functions, and all declared entities in
JS.
• The class stack executes functions in order, using a stack structure (LIFO – Last In
First Out).Manages function calls and tracks which operation is currently running.

.JS->browser->JS engine-> parser(validation)->compiler(JIT)->heap memory->call stack->o/p


• Normally, JS runs inside browsers, giving functionality to HTML elements (e.g.,
buttons, forms).

• [Link] allows JS to run outside the browser (server-side):

• Uses V8 engine.

• Enables building backend apps, scripts, CLI tools, etc.

• No browser needed.
ff
ff
Adding JS to HTML:

1. Internal js:
• JS can be added within the html doc either in head or body section using script
tag
• Syntax:
<head>
<script>
//js code
</script>
</head>
or
<body>
<script>
//js code
</script>
</body> External js
• In html we can add the JavaScript using the script tag in head tag or the
body tag.
<script>…</script>

2. External js:
• We make a separate le for js with .js extensions
• To connect html with js we use script with src attribute
• Eg:
<script src=“[Link]”></script>

3. Inline js:
• Inline JavaScript is written inside HTML tags to add simple functionality or
handle events.
• <button onclick="alert('Button clicked')">Click Me</button>

Console & Debugging:

• Browsers have a developer console which helps in testing or debugging purpose for
users
• The console is a tool available in the browser’s Developer Tools that helps developers
test, monitor, and debug JavaScript code.
fi
Javascript output and input statements:

1. Output Statements:
• Output statements are used to display information to the user.
i. [Link]():
• Used to display output in the browser’s developer console.

• Mainly used for testing and debugging programs.

ii. [Link]():
• Used to display content directly on the web page.

• Writes HTML or text into the document.

iii. alert() or [Link]():


• Displays a popup message box on the screen.

• Contains an OK button.

• The rest of the page loads only after clicking OK.


iv. Dom method
• [Link](‘’): Used to access and manipulate HTML elements
dynamically using JavaScript. The method selects an element using its id.

• innerHTML(), textContent() are methods used with DOM

2. Input Statements:
• Input statements are used to take input from the user.
i. prompt():
• Used to take input from the user through a popup window.
• The prompt displays as a popup window the parameter is displayed on top
below that we will have single line text eld to add data. 2 buttons are present
cancel and [Link] we add data and click ok the value is returned to the
variable and if we click on cancel null is returned to the variable
fi
• If a user clicks on cancel it returns null

• Eg: Take 2 values from user and display the concatenated content

JS Variables:
• Containers that store values/data in the memory
• Helps to store, use and perform some operation with data
• Keyword variable_name=value;
• Keywords are let,

• Rules for variable declaration and naming:


1. Variable naming must start with a letter or $ or _ (underscore)
Eg: name=“abc” or $name=“abc” or _name=“abc”
2. We cant start variable naming with number or with any other special character except $ and _
Eg: %name=“abc” or 1name=“abc”
3. We can have number/other special character after rst letter of variable name
Eg: n1ame or name1 or name%
4. We cant have space in variable name
Eg: Person name=“abc”
5. We cant take any prede ned keywords in JS as variable name
Keywords like this, nally, try, catch cant be used eg: this=“abc”
6. Always variable in JS should declare through variable key words
Eg: variable key words like var, const, let eg: let name=“abc”
7. It is case sensitive
fi
fi
fi
Variable keywords in JS:
• It is used to declare variable in JS. var, let and const
i. var:
• It is a legacy key word in js (used from the 1st version of js to declare variable)
• Used to give functional scope to the variable
• Can be redeclared and can also be reinitialized
• Eg:

ii. let:
• Introduced in ES6 version of JS
• It has a block scope
• let can be reinitialized but cant be redeclared
• Eg:
iii. const:
• Introduced in es6 version
• It has a block scope
• Const cant be redeclared or reinitialized
• Eg:
Feature var let const

Scope Function Block Block

Redeclaration Allowed Not allowed Not allowed

Update Value Allowed Allowed Not allowed

Introduced Old JS ES6 ES6

Scope in JavaScript:
• Scope refers to the area or region of a program where a variable is accessible
• It determines where variables and functions can be accessed in the code.
Types of Scope in JavaScript:
1. Global Scope:A variable declared outside any function or block has global scope. It
can be accessed anywhere in the program.
Eg:

The variable city is accessible inside and outside the function.

2. Local Scope or Function Scope:Variables declared inside a function are accessible


only inside that function.
Eg:
3. Block Scope:Variables declared are accessible only within that block.
Eg:
4. Lexical Scope: It occurs in a nested functions in JS. An outer function variable can be
accessed inside the inner function but inner function variable cant be accessed in the outer
function.
It can be declared with var, let and const variable type
Eg:

Data types in JS:


• It de nes the type of value a variable can store in the memory.
• JS is a dynamically typed language we don’t need to specify the data type during declaration
the compiler will understand the data type based on the value. But we need data type when
we need to perform type conversion.
• Categories of data types:

1. Primitive data type:


• Primitive data types store actual values and represent single, it is a basic
datatype.

• Store a single value

• Immutable (their value cannot be changed, only replaced)

• Number, string, boolean, null, unde ned, symbol, big int

1. Number type: integers, decimal , oat comes under number data type (e.g., 10,
3.14)
2. String : Text values (e.g., “Hello")
3. Boolean type: variable that contains value true or false
4. Null – Represents intentional empty value ie declaring a variable and storing null
value is called null data type
5. Unde ned – Variable declared but not assigned
6. Symbol – Unique identi er (introduced in ES6) created using symbol()
constructor
7. BigInt – Large integers beyond the Number limit
fi
fi
fi
fl
fi
2. Non- Primitive data type:

• Non-primitive types store collections of data or complex structures.

• Can store multiple values

• Mutable (values can be changed)

• Variables store a reference (address) to the object

• Object, Array, Function

Operators:
• Symbols used to perform operations on operands

1. Arithmetic Operators:
• Arithmetic operators are used to perform arithmetic between variables and/or values.
Operator Description

+ addition

- subtraction

* multiplication

/ division

% modulus

++ increment

-- decrement

[Link] Operators:
• Assignment operators are used to assign values to variables

Operator Description

= Assign

+= Add and assign

-= Sub and assign

*= Multiply and assign

/= Divide and assign

%= Modulus and assign


Comparison Operators:
• Comparison operators are used in logical statements to determine equality or
di erence between variables or values.

Operation Description

== Is equal to

=== Is exactly equal to (value and type)

!= Is not equal to

> Greater than

< Less than

Logical Operators:
• Logical operators are used to determine the logic between variables or values.

Operation Descrip on

&& And

|| Or

! not

Special Operators:

Operation Description

?: Conditional

, Comma. Multiple expressions as single statement

delete delete property from an object

in checks if object has a given property

new create instance

Typeof check type of object


ff
ti
Ternary Operator:
• It helps to write an if else statement in a single line.

• Syntax: condition ? expressionIfTrue : expressionIfFalse;

Type Conversion:
• Type Conversion in JavaScript means changing a value from one data type to another
Implicit:
• JavaScript automatically converts types when needed.
• Eg:

Explicit:
• You manually convert types using functions.
• Eg:
Conditional Statements:
• Used to perform di actions for di decisions
1. If : Execute some code only if a speci ed condition is true
if(condition)
{
Code to execute
}

2. If else: Execute some code if the condition is true and another code if the condition is
false

if(condition)
{
Code to execute
}
else {
other code execute
}

3. Else if: Handling multiple possible conditions and outputs, evaluating more than two options
based on whether the conditions are true or false.
if(condition)
{
Code to execute}
else if {
some other code executes
}
else {
other code
}

4. Switch: Select one of many blocks of code to be executed


let a=5
switch
(a) {
case 1:
[Link] ("1 is executed")
break
case 2:
[Link] ("2 is executed")
break
case 3:
[Link] ("3 is executed”)
break
case 4:
[Link] ("4 is executed") break
case 5:
[Link] ("5 is executed") break
case 6:
[Link] ("6 is executed") break
}
ff
ff
fi
Loops in Javascript:
• Same block of code to run over and over again in a row we use loops
• In JavaScript there are two di erent kind of loops:
• for - loops through a block of code a speci ed number of times
for (initialization; condition; increment/decrement)
{
Statement to execute
}

• while - loops through a block of code while a speci ed condition is true


while (var<=end value)
{
// code to be executed
}

• Do while - This loop will always execute a block of code once, and
then it will repeat the loop as long as the speci ed condition is true. This
loop will always be executed at least once, even if the condition is false,
because the code is executed before the condition is tested.

do
{
//code to be executed
}while (var<=end value);
ff
fi
fi
fi
Break and Continue Statements:
• There are two special statements that can be used inside loops: break and continue.
Break:
• The break command will break the loop and continue executing the code that follows
after the loop (if any condition).

Continue:
• The continue command will break the current loop and continue with the next value.
Functions in JavaScript:
• A function is a self-contained piece of code that performs a particular task.
• A function is a reusable code-block that will be executed by an event, or when the
function is called.
• Function name should represent behaviors
• Wont get automatically invoked until we invoke it

Function Declaration:
• Syntax:
function func_name{
//set of statement
} //function declaration

fun_name() //function call

Function Expression:
• Function stored inside a variable.
Parameters vs Arguments:

Parameters:
• A parameter is a variable listed in a function de nition.
• It acts as a placeholder for the value that you pass into the function when calling it.

Types of Parameters in JavaScript:


1. Default Parameters:
• You can assign a default value if no argument is passed.

2. Rest Parameters (…):


• A function take multiple arguments and stores them in an array.
fi
3. Destructured Parameters:
• Extracting values from objects or arrays directly in the function parameters, instead of
accessing them inside the function.

4. Optional Parameters:
• Function parameters are not strictly enforced, so if you call a function with fewer
arguments than it expects, the missing parameters are automatically set to unde ned

Arguments:
• Arguments are the actual value passed to a function when it is called.
fi
Description Example
Variables listed in the function
Parameters
de nition
function greet(name, age)
Actual values passed when
Arguments
calling the function
greet(“Abc", 22)

Return Statement:
• The return statement is used to specify the value that is returned from the
function. So, functions that are going to return a value must use the return
statement.

Types of functions:
1. Named functions:
• A function with a name, de ned normally.
• It is reusable.
fi
fi
2. Parameterized functions:
• A function that accepts inputs (parameters).

3. Return:
• Returns output using return
• It is the last executed statement
• Can return string, variable, number, boolean, [Link], array, objects

4. Anonymous:
• Anonymous functions are function without a name.
• It is used in callbacks and expressions
5. Callback:
• A function passed as an argument to another function.

6. Higher order functions:


• A higher order function is a function that takes one or more functions as
arguments, or returns a function as its result.

7. Arrow function:
• Arrow function is a shorter way to write function using =>
• It is used for clearer and concise code
• Syntax:
const functionName = (parameters) => {
// code
};

8. IIFE’s:
• IIFE is Immediately Invoked Function Expression
• It’s a function that is de ned and executed immediately after it’s created.
• It avoids global scope pollution
• No function name is used, parentheses are used inside which an anonymous
function is added

Javascript Currying:
• Currying is a technique where a function with multiple arguments is transformed into a
sequence of functions, each taking one argument at a time.

• The rst function takes the rst argument and gives back a new function to take the
next one.
• The returned function takes the next argument and keeps going until all the
arguments are given.
• Once all the arguments are provided, the nal result is calculated and returned.
fi
fi
fi
fi
• Here getAPIData will execute rst and then that will intern return the ShowAPIData
method and return the status.
fi
Javascript Closures:
• A closure in JavaScript is when a function remembers variables from its outer scope
even after that outer function has nished executing.
• Closure is A function with the lexical environment in which it was created.

fi
Hoisting in JavaScript :
• Hoisting is the default behavior of moving all the declarations at the top of the
scope before code execution.
• JavaScript only hoists declarations, not initializations.
• JavaScript allocates memory for all variables and functions de ned in the
program before execution
• Function declarations are hoisted but function expressions are not hoisted.

Arrays:
• An array is a special variable, which can hold more than one value
• In Java Script arrays are heterogeneous means they can hold any type of variable.
• In Java Script arrays are dynamic in nature which means they can be dynamically
updated
fi
Creating Arrays:
• There are 2 ways to create a array:
1. Using an array:
• Syntax: const array_name = [item1, item2, …];

2. Using new Keyword:

Accessing Elements:
• Array elements are accessed by their index, starting at 0.
Array Methods:
• length:
The length property returns the length (size) of an array.

• toString():
The JavaScript method toString() converts an array to a string of (comma
separated) array values

• join():
The join() method joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator.

• pop():
The pop() method removes the last element from an array.

It returns the value that was popped out.


• push():
The push() method adds a new element to an array at the end.

It returns the new length of array.

• shift():
The shift() method removes the rst array element and "shifts" all other elements to
a lower index.
The shift() method returns the value that was removed.

• unshift():
It adds the element at rst index.

The method returns the new array length


fi
fi
• slice():
The slice(start index, end index) method slices out a piece of an array into a new array.
The slice() method creates a new array and does not remove any elements from the source
array.

• splice():

[Link](start, deleteCount, item1, item2, …) method used to add, remove, or replace


elements directly in an array.
start: index where changes begin
deleteCount: number of elements to remove
item1, item2…: elements to add
• indexof:

indexOf(value) Returns the rst index of the value, or -1 if not found

• includes:
includes(value) Returns true if the value exists in the array, otherwise false

Looping Arrays:
i. for loop:

ii. for…of loop:

iii. forEach method:


Executes a function for each element.
fi
iv. map():
Creates a new array by applying a function to each element

v. lter:
Creates a new array with elements that satisfy a condition

vi. reduce:
Reduces the array to a single value using a callback
fi
What are Objects?
• Objects are used to store the data in key-value pair.
• Eg: const person = {
rstName : "Abc",
lastName : "S",
age : 23,
height : 6.0
};

Object Properties & Methods:


• Object properties: They are variables inside objects
• Methods: They are functions inside objects
fi
Accessing Properties:
• You can access object data in two main ways:
1. Dot Notation:

• Cannot use dynamic keys

2. Bracket Notation:
• Useful when Property name is dynamic, Property has spaces

Adding New Properties


You can add new properties to an existing object by simply giving it a value. If
property is already existing, then that property will be overridden.
[Link] = “India”;
Deleting Properties

• The delete keyword deletes a property from an object.

• The delete keyword deletes both the value of the property and the property itself.

Nested Objects:
Objects can contain other objects inside them that is a object inside another object
Array Of Objects:
We can store an objects inside the array.

We can access the individual objects according to the indexes.


We can access the object property using the index of object and key of object.

[Link](obj[0])//print object at 0 index.


Strings:
String Creation:
• You can create strings using single quotes, double quotes, template literals (backticks)

length:

Returns the number of characters.

toUpperCase() :
convert text to upper case.

toLowerCase() :
convert text to lower case.
trim():
The trim() method removes whitespace from both sides of a string

trimStart():
The trimStart() method will removes whitespace only from the start of a string

trimEnd():
The trimEnd() method will removes whitespace only from the Ending of a string.

substring():
substring() is similar to slice(). The di erence is that start and end values will not take negative
index it will be treated as 0.

replace():
This method is used to replace a string with another String
ff
includes():
Checks if a string contains a value.

charAt():
The charAt() method returns the character at a speci ed index in a string.

charCodeAt():
The charCodeAt() method returns the code of the character at a speci ed index in a string.

slice():
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters ie start and end position.
fi
fi
DOM(Document Object Model):

• DOM (Document Object Model) is a programming interface for web pages.


• The HTML DOM model is constructed as a tree of Objects with the document as the
parent element.
• With the help of DOM, we can access and manipulate the html element in JavaScript.
Selecting Elements:
1. getElementById :
• Selects a single element by ID

2. getElementsByClassName:
• Find all HTML elements with the same class name
• Syntax: [Link](“className”)
• If multiple elements have the same class, all are returned
3. querySelector:
• It selects the rst matching element.
• If you want to nd all HTML elements that matches a speci ed CSS selector (id,
class names, types,), use the querySelector() method.

4. querySelectorAll:
• It selects all matching elements.
• Returns a NodeList can loop through it easily
fi
fi
fi
Manipulating Elements

Text:

To change or get text of an element we use:

innerText:
• It is used to add the text content inside the element
• Gives visible text.
innerHTML:
• It is used to add the html content inside the element.

style:
• It is used to add the style for the element:
• Respects CSS visibility to some extent
• Here we need to write the properties in camelCase Convention and the value need to
be speci ed in string format.
fi
createElement:
• This method is used to create a html element.
• Eg: const heading= [Link]('h1')

appendChild:
• This method is used to add the element created to html document.
remove:
• It is used to remove element from the document
setAttribute:
• It is used to add an attribute for the element

removeAttribute:
• It is used to remove attribute from the element
Program to take input from the user and print the sum in html document
using DOM
Events in JavaScript:
• Event are the action or occurrence that happen in the web browser such as click,
keypress, form submission, mouse hover.
• JavaScript provide a build in mechanism for handling the events, allow you to create
an interactive web application.
Event Handling:

• Event handling means responding to user actions like click, keypress, mouse
movement, etc.

Event Event Handler


click onclick
mouseover onmouseover
mouseout onmouseout
mousedown onmousedown
keyup onkeyup
keydown onkeydown
Focus onfocus
Submit onsubmit
onload onload

Click:
• onclick is an event handler
• It runs when the button is clicked
• Only one function can be assigned
Change:
• Triggered when the value of an input changes AND loses focus
• Input eld loses focus after change
• Dropdown selection changes
fi
keypress:
• Triggered when a key is pressed on keyboard
• keypress is deprecated in modern JS instead use keydown (recommended) Or
keyup
Submit:
• Triggered when a form is submitted
mouseover:
• Triggered when the mouse comes over an element
• Color changes but does NOT go back
mouseout:
• Triggered when the mouse leaves an element

mousedown:
• Triggered when a mouse button is pressed down.
Focus:
• Triggered when an input eld gets focus (clicked or tabbed into)
fi
onload:
• Triggered when the page fully loads
Event Litesner:
•This function that wait for the event to occur and response to it.
•Event listener listen for the event and response for the event by calling a function.

addEventListener():
• Used to attach an event to an element
• This function is an example of higher order function which will take event as one
argument as a string and a callback function which will a ect when the event occurs.
• Syntax: [Link](event, function);

ff
Event capturing:

• Event ows from parent to child


• Syntax: addEventListener("click", function, true)
• In capturing the outer most element's event is handled rst and then the inner
fl
fi
Event Bubbling:
• Event ows from child to parent
• In bubbling the inner most element's event is handled rst and then the outer
fl
fi
Event Delegation:

• A event delegation is where a parent is used to handle events of multiple child


elements
• Reduces the number of event [Link] uses event bubbling to capture events.
this:
this refers to the object that is executing the current function
Its value depends on how the function is called
Template Literals

• It is used for string formatting with variables


• Use backticks ( ` ` ) Introduced in ES6, they support easy interpolation and multi-line
strings.
Spread Operator(...)
• The spread operator is used to expand elements of arrays or objects.
• It is used for cloning arrays/objects, merging data, passing values
• It expands elements of arrays and strings or properties of objects into individual values.

Rest Operator (…)


• The rest operator collects multiple values or properties into a single array.
• The rest parameter syntax allows a function to accept an inde nite number of
arguments as an array.
fi
Destructuring:

• Destructuring is used to extract values from arrays or objects into variables.


• Array destructuring:Array members can be unpacked into di erent variables.

• Object destructuring: Object destructuring means extracting values from objects into
variables

Default Parameters:

• It is used to give the default values to the arguments, if no parameter is provided in the
function call.
ff
Modules:

• Modules allow you to split your code into multiple les and reuse them.
• It helps in code organization, reusability, maintainability

Synchronous (Blocking):
• Code runs line by line, one after another.
• Next task waits until current task nishes.

fi
fi
Asynchronous (Non-blocking):
• It allows multiple tasks to run independently of each other. In asynchronous code, a task
can be initiated, and while waiting for it to complete, other tasks can proceed.

• The code does is rst it logs in Hi then rather than executing the setTimeout
function it logs in End and then it runs the setTimeout function.

Callbacks:
• A callback is a function passed as an argument to another function and is invoked after
the execution of main function.
fi
Callback Hell:
• Callback hell is used to describe the nested callback stacked over bellow one another
formatting a pyramid structure.
• Every callback depends/wait for previous callback.
• It is hard to understand and maintain
• To solve this we can use promises or async/await

Promises:
• Promise is an object representing the eventual completion or failure of an asynchronous
operation
• A promise object can be in any 3 states
1. Pending : operation started (not nished)
2. Rejected: operation failed
3. ful lled: operation completed

async / await:
• async: declare a function or method as asynchronous and can pause its
execution to wait for completion of other process.
• await: make a suspension point where execution may wait for the result of async
function or methods.

setTimeout:
• Executes a function after a delay (in milliseconds)
• Syntax: setTimeout(function, delay);
fi
fi
setInterval:
• Executes a function repeatedly at a xed interval
• Syntax: setInterval(function, delay);

Debounceing :
• Debouncing ensures a function runs only after a certain delay after the last event or
function has occurred
• Eg: Form validation, Search bar typing
• Debouncing works by clearing the previous timer, then starting a new timer and the functions

runs only once after the delay

Throttling:
• Throttling ensures a function runs at most once in a given time interval.
• It limits how often a function runs.
• Eg: Scroll events, Window resize
• Function runs immediately and then ignores calls until time limit is over
fi
Browser APIs:
Browser APIs are built-in features provided by the browser that allow JavaScript to
interact with:

• Storage
• Network requests
• Data formats

Local Storage:
• Stores data with no expiration time.
• Even after browser is closed, after system restart the stored data does not
expire until manually cleared
• Used for saving user preferences (dark mode) saving login token (careful with
security) cart items in e-commerce remembering theme/language
Session Storage:
• Stores data only for one browser session.
• Data gets deleted when tab is closed, when browser is closed
• Used for otp veri cation sessions one-time page visit data multi-step form data

Feature Local Storage Session Storage


Storage Limit ~5MB ~5MB
Ends when tab
Expiry No expiry
closes
All tabs (same
Accessible in Only same tab
origin)
Use Case Long-term storage Temporary storage
Data
Yes No
Persistence

JSON Parsing:
• JSON is a string [Link] works with objects so we convert between them
• Object to JSON:

• JSON to Object:
fi

You might also like