JS Notes
JS Notes
JavaScript Notes.
What is JavaScript ?
i. Javascript is a high-level , object based ,programming language. Javascript is a
interpreted, user friendly ,client-side scripting language .
History of javascript ?
i. javascript developed by Brenden Eich-1995 .
ii. First name of javascript --> MOCHA .
iii. next --> LIVESCRIPT .
iv. next--> JAVASCRIPT .
Features of JavaScript?
Light Weight
Open Source
Cross Platform
Dynamically typed language
Interpreted language
Client-side scripting language
Synchronous language
Weakly typed language
Javascript characteristics ?
Clientside Scripting language - no compiler and without help of server logic
we can update the data .
High-level language - user-friendly .
Interpreted language - line by line execution .
Single threaded - one call stack and one heap area .
Loosely typed - no strong syntax .
Dynamic language - can change the datatype during the runtime .
Object-based language - In JavaScript everything was object .
Advantages of Javascript ?
1. Client-Side Execution :
Sarvesh Sir’s Notes
JavaScript runs in the browser, reducing the load on the server and improving
performance .
2. Speed :
It executes quickly within the user's browser without the need for server
interaction .
Allows for interactive web pages (e.g., animations, dynamic updates, form
validations) .
Large ecosystem with frameworks like React, Vue, and Angular, as well as libraries
like jQuery and Lodash .
5. Cross-Browser Support :
7. Asynchronous Processing :
Disadvantages of Javascript ?
1. Security Issues :
Since JavaScript runs on the client side, it is vulnerable to attacks like cross-site
scripting (XSS) and code injection . (Vulnerable means weak or unprotected,
making something easy to attack or harm . In JavaScript security, if a website is
vulnerable, it means hackers can easily break in, steal data, or damage the site
because there are security weaknesses .)
2. Browser Inconsistencies :
3. Limited Multithreading :
JavaScript is single-threaded meaning heavy tasks can block the main thread and
affect performance
Many projects rely heavily on external libraries, which can introduce security risks
and maintenance issues .
Uses of JavaScript ?
We use javascript for Web application , Web development , Mobile application , Games
development , Server application , Animate elements , Web server , Client-Side validation
.
2. External Way : To write javascript externally to html file, we need to create an external
javascript file with extension as .js (ex: index.js) . After that link that javascript file to the
html by using script tag .
Token :
Token is a smallest unit cell in a programming language and it has some specific
meaning . The combination of keywords , identifiers , literals and operators make a valid
token .
Keywords :
Reserved words that have special meanings in the language. Examples include var, if,
else, for, while, etc . Every keyword must be in the lower case and it is not used as
Identifiers.
Identifiers :
These are names that are used to identify variables, functions, and other objects. For
example, the identifier myVariable could be used to identify a variable that stores the
value 5.
Rulers: -an identifiers can't start with number. -We can’t use keywords as identifiers. -
Except $, _ no other Special Characteristics are allowed.
Literals :
Data which is used in the js programming is called as literals. For example, the literal 5 is
a numeric literal (Data types), and the literal "Hello, world!" is a string literal
Operators :
Sarvesh Sir’s Notes
These are symbols that are used to perform operations on operands. For example, the
operator + is used to add two numbers together.
There are some rules while declaring a JavaScript variable (also known as identifiers) .
Operaters :
Operators are special symbols in JavaScript that are used to perform operations on
values. There are many different types of operators, including arithmetic operators,
comparison operators, logical operators, and assignment operators .
Sarvesh Sir’s Notes
1. Arithmetic operators :
Arithmetic operators are use to do some arithmetic operation between two values .
EX -: + , - , * , / , % , **
2. Comparison operators :
3. Logical operators :
EX -: && , || , !
4. Assignment operators :
EX -: += , -+ , *= , /= , %= , **=
Conditional statement :
A conditional statement is a programming instruction that executes different actions
based on whether a specified condition is true or false. It helps in decision-making in
code .
1. JavaScript If statement :
Syntax -: if(expression){
//content to be evaluated
EX -: var a=20;
if(a>10){
Syntax -: if(expression){
else{
EX -: var a=20;
if(a>10){
Syntax -: if(expression1){
else if(expression2){
else if(expression3){
}
Sarvesh Sir’s Notes
else{
Ex -: var a=20;
if(a==10){
else if(a==15){
else if(a==20){
else{
Switch Statement Execute the block of code depend on the different cases . if we not
give the break keyword then ,even the condition is satisfied it will execute the remaining
blocks .
Syntax -: switch(expression) {
case n:
// code block
break;
Sarvesh Sir’s Notes
case n:
//code block
break;
default:
switch (food) {
case "cake":
break;
case "pizza":
break;
default:
break;
break;
JavaScript Loops :
JavaScript Loops are powerful tools for performing repetitive tasks efficiently. Loops in
JavaScript execute a block of code again and again while the condition is true. OR
Sarvesh Sir’s Notes
Whenever you want to execute a block of code again and again until the condition fails
you need to use loops .
1. For Loop :
The JS for loop provides a concise way of writing the loop structure. The for loop
contains initialization, condition, and increment/decrement in one line thereby providing
a shorter, easy-to-debug structure of looping .
statement(s)
Initialization condition : It initializes the variable and mark the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only .
Test Condition : It is used for testing the exit condition of a for loop. It must return a
boolean value. It is also an Entry Control Loop as the condition is checked prior to the
execution of the loop statements .
Statement execution : Once the condition is evaluated to be true, the statements in the
loop body are executed .
Increment/ Decrement : It is used for updating the variable for the next iteration .
Loop termination : When the condition becomes false, the loop terminates marking the
end of its life cycle
2. While Loop :
The JS while loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. The while loop can be thought of as a repeating if
statement . (First it will check the condition then execute the code .)
loop statements...
}
Sarvesh Sir’s Notes
Ex -: let val = 1;
console.log(val);
val += 1;
While loop starts with checking the condition. If it is evaluated to be true, then the loop
body statements are executed otherwise first statement following the loop is executed.
For this reason, it is also called the Entry control loop .
Once the condition is evaluated to be true, the statements in the loop body are
executed. Normally the statements contain an updated value for the variable being
processed for the next iteration .
When the condition becomes false, the loop terminates which marks the end of its life
cycle.
3. do-While Loop :
The JS do-while loop is similar to the while loop with the only difference is that it checks
for the condition after executing the statements, and therefore is an example of an Exit
Control Loop. It executes loop content at least once event the condition is false . (first
execute the code then check the condition .)
Syntax -: do {
Statements...
while (condition);
Ex -: let test = 1;
do {
console.log(test);
test++;
The do-while loop starts with the execution of the statement(s). There is no checking of
any condition for the first time .
After the execution of the statements and update of the variable value, the condition is
checked for a true or false value. If it is evaluated to be true, the next iteration of the
loop starts .
When the condition becomes false, the loop terminates which marks the end of its life
cycle .
It is important to note that the do-while loop will execute its statements at least once
before any condition is checked and therefore is an example of the exit control loop .
4. For-in Loop :
There are also other types of loops. The for..in loop in JavaScript allows you to iterate
over all property keys of an object .
Note: In each iteration of the loop, a key is assigned to the key variable. The loop
continues for all object properties.
// body of for...in
Ex -: const student = {
name: 'Monica',
class: 7,
age: 12
4. For-of Loop :
You should not use for...in to iterate over an array where the index order is important.
One of the better ways to iterate over an array is using the for...of loop .
The for...of loop was introduced in the later versions of JavaScript ES6 .
The for..of loop in JavaScript allows you to iterate over iterable objects (arrays, sets,
maps, strings etc) .
// body of for...of
// using for...of
console.log(element);
1. The for...of loop is used to iterate 1. The for...in loop is used to iterate through the keys of an
through the values of an iterable . object .
2. The for...of loop cannot be used to 2. You can use for...in to iterate over an iterable such arrays
iterate over an object . and strings but you should avoid using for...in for iterables .
Sarvesh Sir’s Notes
Let :
Const :
Scope :
Scope in JavaScript refers to the accessibility of variables, functions, and objects in
different parts of the code .
1) Global Scope
2) Script Scope
3) Block Scope
4) Local Scope
5) Function Scope
Hoisting :
What is Hoisting ?
Hoisting is a part of javascript in which it move the code in to top of level of the file .
JavaScript function :
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) .
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) .
// code to be executed
Function Invocation :
The code inside the function will execute when "something" invokes (calls) the function :
When JavaScript reaches a return statement, the function will stop executing.If the
function was invoked from a statement, JavaScript will "return" to execute the code after
the invoking statement .
Sarvesh Sir’s Notes
1. Anonymous function :
Syntax -: function(parameters) {
// function body
2.Named Function :
// function body
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 .
Ex -: let x=function(){
//block of code
x();
Sarvesh Sir’s Notes
4. Nested function :
Ex -: Function parent(){
let a=10;
function child(){
let b=20;
console.log(a+b);
child ();
parent ();
What is a Closure?
A closure is a function that remembers the variables from its outer function, even after
the outer function has finished executing.
Remember values
Create private variables
Maintain state between function calls
function outer() {
function inner() {
}
Sarvesh Sir’s Notes
return inner;}
JavaScript currying :
Calling a child function along with parent by using one more parenthesis is known as
java script currying .
Ex -: Function parent () {
let a=10;
function child () {
let b=20;
console.log(a+b);
return child;
parent () ();
Sarvesh Sir’s Notes
A function which is called immediately as soon as the function declaration is known as IIF
We can invoke anonymous function by using IIF .
Ex -: (function () {
console.log(“Hello”);
})();
6. Arrow function :
Let y=(a,b)=>{return a + b };
console.log(a,b);
console.log(res);
hof(10,20,(x,y)=>x+y)
8. Callback function :
A function which passed another function as an argument the passed function called
Callback function
Sarvesh Sir’s Notes
Ex -: function demo(x){
console.log(x);
console.log("callback")
demo(test)
String Methods :
console.log(str.length); // Output: 13
2. String.slice(start, end) : Extracts a part of a string and returns it as a new string. The
end index is not included .
3. String.substring(start, end) : Similar to slice(), but it does not support negative indices .
4. String.substr(start, length) : Extracts a part of a string starting from a specific index and
taking a specified number of characters .
Sarvesh Sir’s Notes
9. String.concat(str1, str2, ...) : Joins two or more strings and returns a new string .
16. String.charCodeAt(index) : Returns the Unicode (ASCII) value of the character at the
specified index .
Array Methods :
arr.push(4);
console.log(removed); // Output: 3
arr.unshift(0);
console.log(removed); // Output: 1
5. indexOf() : Returns the index of the first occurrence of a specified element. Returns -1
if not found .
console.log(arr.indexOf("banana")); // Output: 1
console.log(arr.indexOf("grape")); // Output: -1
7. at() : Returns the element at the specified index. Supports negative indexing .
console.log(arr.at(1)); // Output: 20
8. slice(start, end) : Returns a shallow copy of a portion of an array. It does not modify
the original array .
9. splice(start, deleteCount, item1, item2, ...) : It will give slice of an array and it will not
affect the original array .
Ex -: (Remove elements):
Ex -: (Add elements):
10. join(separator) : Converts all elements of an array into a string, separated by the
specified separator .
11. concat() : Merges two or more arrays and returns a new array.
Sarvesh Sir’s Notes
12. toString() : It converts all the elements in an array into a single string and returns that
string .
arr.reverse();
The spread operator helps us expand an iterable such as an array where multiple
arguments are needed, it also helps to expand the object expressions .
Note: There can be more than one spread operator in javascript functions.
console.log(array3); OUTPUT -: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
firstname: "Divit",
lastname: "Patidar",
};
console.log(obj2);
OUTPUT -: {
firstname: "Divit",
lastname: "Patidar"
Note : There are three distinct places that accept the spread syntax :
The rest parameter is converse to the spread operator. while the spread operator
expands elements of an iterable, the rest operator compresses them. It collects several
elements. In functions when we require to pass arguments but were not sure how many
we have to pass, the rest parameter makes it easier .
Note: The rest parameter has to be the last argument, as its job is to collect all the
remaining arguments into an array .
statements;
Sarvesh Sir’s Notes
1. The spread operator is used to expand 1. The rest parameter is used to collect multiple
elements of an iterable (array, string, etc.) elements and condense them into a single element .
2. The spread operator is used in function calls 2. The rest parameter is used in function declarations
and array literals . to accept an indefinite number of arguments .
3. The spread operator is used to copy the 3. The rest parameter is used to collect all the
elements of an iterable into another iterable . remaining arguments into an array .
JavaScript Promise :
To make javascript synchronous to asynchronous we use Promise. it has 3 stages :
A Promise takes a function with two arguments: resolve (success) and reject (failure).
//do something
});
It is invoked when a promise is either rejected or some error has occurred in execution. It
is used as an Error Handler whenever at any step there is a chance of getting an error.
Sarvesh Sir’s Notes
Async Function :
return "Hello";
Await Keyword :
Await is used to wait for the promise. It could be used within the async block only. It
makes the code wait until the promise returns a result.
Time delays :
setTimeOut() :
delay: The amount of time (in milliseconds) before the function is executed.
Sarvesh Sir’s Notes
setInterval() :
Dom :
What is Dom and its Methods ?
The Document Object Model (DOM) is a programming interface for web documents. It
represents the page so that programs can change the document structure, style, and
content. The DOM represents the document as nodes and objects; that way,
programming languages can interact with the page. (Dom is an API with the help of js
we can able to access Dom) OR In simple words, it can be categorized as a programming
interface for HTML as well as XML (eXtensible Markup Language) documents. It defines
the logical structure of the documents in the form of a tree of objects where each HTML
element is represented as a node and it also describes the way these documents can be
manipulated. There are 5 Method to access
This method is used when developers have defined certain HTML elements with IDs that
uniquely identify the same elements in the whole document. It returns an Element object
which matches the specified ID in the method. If the ID does not exist in the document, it
simply returns null .
Syntax -: document.getElementById(id);
Return Value -: It returns the object corresponding to the passed ID in the method, or
null if no match is found .
Sarvesh Sir’s Notes
getElementsByClassName() :
This method is used when there are multiple HTML elements with the same class name.
It returns a collection of all objects which match the specified class in the method .
Syntax -: document.getElementsByClassName(className);
className : The class name of the element(s) to locate in the HTML document. It
should be a case-sensitive string .
Return Value -: It returns a html collection and looks like an array but it is not an array if
any element is not there it will return empty array .
getElementsByTagName() :
Syntax -: document.getElementsByTagName(tagName);
tagName : The tag name of the element(s) to locate in the HTML document. It should
be a case-sensitive string .
Return Value -: It returns a html collection of objects corresponding to the passed tag
name in the method if any element is not there it will return empty array .
querySelector() :
This method returns the first match of an element that is found within the HTML
document with the specific selector. If there is no match, null is returned .
Syntax -: document.querySelector(selector);
selector : A string containing one or more selectors to match elements located in the
HTML document .
Return Value -: It return only one node or first element from multiple element if no
element is there it will return null .
Sarvesh Sir’s Notes
querySelectorAll() :
This method returns a static NodeList of all elements that are found within the HTML
document with the specific selector .
Syntax -: document.querySelectorAll(selector);
selector : A string containing one or more selectors to match elements located in the
HTML document .
Return Value -: It returns a NodeList of the objects corresponding to the passed selector
in the method if there is no node it will return empty nodelist .
innerText() :
Returns the text content of an element and all its child elements, excluding HTML tags
and CSS hidden text. innerText also ignores HTML tags and treats them as part of the
text .
document.body.appendChild(div);
innerHTML() :
Returns the text content of an element, including all spacing and inner HTML tags.
innerHTML recognizes HTML tags and renders the content according to the tags.
innerHTML allows you to see exactly what's in the HTML markup contained within a
string, including elements like spacing, line breaks, and formatting .
document.body.appendChild(div);
Key Differences :
Property Handles HTML Parses & Executes HTML Returns Hidden Text
innerText ❌ No ❌ No ❌ No
Methods :
appendchild() :
The appendChild() method adds a new child element to a parent element in the DOM. It
places the child at the end of the parent’s existing content . it can append one node at a
time .
Syntax -: parentElement.appendChild(childElement);
append() :
The Element.append() method inserts a set of Node objects or string objects after the
last child of the Element
removeChild() :
The removeChild() method of JavaScript will remove the element from the document .
Removes a specific child element from a parent and Requires the parent element to call
it and Returns the removed element .
Syntax -: parent.removeChild(child);
remove() :
Remove method removes the element itself without needing the parent and it does not
return anything and More modern and easier than removeChild() .
Syntax -: element.remove();
Attribute method :
setAttribute() :
The setAttribute() method is used to set or add an attribute to a particular element and
provides a value to it. If the attribute already exists, it only set or changes the value of
the attribute. So, we can also use the setAttribute() method to update the existing
attribute's value. If the corresponding attribute does not exist, it will create a new
attribute with the specified name and value. This method does not return any value. The
attribute name automatically converts into lowercase when we use it on an HTML
element . OR (To get the value of an attribute, we can use the getAttribute() method)
document.body.appendChild(div);
attributeValue : It is the value of the attribute that we are adding to an element. It is also
not an optional value .
removeAttribute() :
The removeAttribute() method removes the attribute with the specified name . ✅
Removes only one attribute at a time . Does not remove the element itself, only the
attribute.
Syntax -: element.removeAttribute(attributeName);
getAttribute() :
The getAttribute() method is used to get the value of an attribute of the particular
element. If the attribute exists, it returns the string representing the value of the
corresponding attribute. If the corresponding attribute does not exist, it will return an
empty string or null .
Syntax -: element.getAttribute(attributeName);
Event Handling :
addEventListener() :
event : It is a string that specifies the name of the event . events are Click , Mouseover ,
Mouseout , Doubleclick , Submit
listener : It is a function that specifies the function to run when the event occurs .
button.addEventListener("click", function() {
console.log("Button clicked!");
});
Event Bubbling :
Sarvesh Sir’s Notes
Event bubbling is the phase where the event bubbles up from the target element all the
way to the global window object .
When an event occurs on a child element, it first triggers on that element and then
bubbles up to its ancestors in the DOM hierarchy. This means the event starts at the
targeted element and moves upward to the parent, grandparent, and so on, until it
reaches the root (document).
Bubbling phase :
The bubbling phase, which is the last phase, is the reverse of the capturing phase. In this
phase, the event bubbles up the target element through its parent element, the ancestor,
to the global window object. By default, all events you add with addEventListener are in
the bubble phase .
Event Capturing :
Event capturing occurs when a nested element gets clicked. The click event of its parent
elements must be triggered before the click of the nested element. This phase trickles
down from the top of the DOM tree to the target element .
Event capturing can't happen until the third argument of addEventListener is set to the
Boolean value of true .
Whenever the third argument of addEventListener is set to true, event handlers are
automatically triggered in the capturing phase. With this, the event handler attached to
an ancestor element will be executed first when an event occurs on a nested element
within the DOM hierarchy .
Capturing phase :
The first phase is the capturing phase, which occurs when an element nested in various
elements gets clicked. Right before the click reaches its final destination, the click event
of each of its parent elements must be triggered. This phase trickles down from the top
of the DOM tree to the target element .
Sarvesh Sir’s Notes
Target phase :
The target phase is the second phase that begins immediately after the capturing phase
ends. This phase is basically the end of the capturing and the beginning of the bubbling
phase .