JavaScript Notes - 1
JavaScript Notes - 1
What is JavaScript?
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.
• Uses V8 engine.
• 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>
• 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.
ii. [Link]():
• Used to display content directly on the web page.
• Contains an OK button.
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,
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 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:
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:
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
Operation Description
== Is equal to
!= Is not equal to
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
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
}
• 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
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.
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.
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, …];
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.
• 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.
• splice():
• includes:
includes(value) Returns true if the value exists in the array, otherwise false
Looping Arrays:
i. for loop:
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
};
2. Bracket Notation:
• Useful when Property name is dynamic, Property has spaces
• 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.
length:
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):
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:
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.
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:
• 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
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
JSON Parsing:
• JSON is a string [Link] works with objects so we convert between them
• Object to JSON:
• JSON to Object:
fi