Notes 4 Nov
04 November 2024 12:20
[Link]
Console= object
. = operator
Log = function
Object is block of memory which has states and behavior
Dot = is access operator , it will help you to use the variables and functions present inside object
Log() = It is an function which can accepts the argument
Token= smallest Unit of any programming lang is known as Token
• Keyword= a predefine reserved word which is understandable by our js engine is known as keyword
○ Eg: if for const var let
• Every keyword must be in lowercase
• A keyword can't be use an identifier
identifiers
• The name given to component of java script line, variables, function, class it is knows as identifiers
• Rules for identifiers
○ It can't start with a number
○ Accepts $ and underscore no other spial character are allowed
○ We can use keywords as identifiers
Literals
• The data which is used in js program is called as values or literal
BOM (Browser Object Modal)
Definition BOM:
It is a programming interface JavaScript tool for working with web browsers. This enables access and
manipulation of browser window, Frames
• The Brower object model allows JavaScript to "Talk to" browser.
• BOM stands for the browser Object Model. It represents the objects that a Brower provides to
JavaScript to Intertect with the Brower itself
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.
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
Confirm:
• This method displays a dialog box with a message and ok button and cancel button
• This method will return the output is in boolen format (if we will click on ok the O/P is true else false)
1. Alert()
• This method displays an alert box or popup with message and then okay button
• The alert box takes the focus away from current window and forces the users to read the massage, it
prevents the user from accessing other parts of the page until alert box is closed
2. Prompt
• This method display prompt the user for an input
• The method return the input value in is the use click on ok button or it returns null
3. Confirm:
• This method displays a dialog box with a message and ok button and cancel button
• This method will return the output is in boolen format (if we will click on ok the O/P is true else false)
4. DOM(Document object modal):
• Dom is always child of BOM
• In Dom we have 2 o/p method
• [Link]() and [Link]()
Variables
• Named a block of memory which is use to store value is know as variable
• In js variables is not strictly typed it is dynamic type
• There for it is not necessary to specify type of data during variable declaration
• In variable we can store any type of data
Keyword Declaration Initialization D+I ReD ReI ReD+ReI
var Y Y Y Y Y Y
let Y Y Y N Y N
const N N Y N N N
DataTypes:
Primitive
1. Number
2. String
3. Symbol
4. Boolean
5. Undefined
6. Null
7. Bigint
Non-Primitive
1. Function
2. Array
3. Object
• Date
• Time
• Maths
-----------------------------------------------------------------------------------------------------------
-
Type of Operator
• Its is a keyword type of data
Function:
• Function is class of operation which is perform
• Function will executed whenever it is called or invoke
• The main advantage of function is we can archive code reusability
This keyword :
• It holds the address of global window object
• With help of this variable we can use member of global window object
Types Of Functions-
1. Named Function
a.
2. Anonymous function
a. A function without a name is called as Anonymous function
function (){
[Link]("Hellow 1")
[Link]("Hellow 2")
[Link]("Hellow 3")
}
3. Function with Expression
a. Passing a function as an value to the variable we called it as function with expression
let a= function (){
[Link]("Hellow 1")
[Link]("Hellow 2")
[Link]("Hellow 3")
}
a()
4. Immediate Invoke Function Expression (IIFE)
a. we can use call one time
b. When the fun is called immediately as soon as the fun object is created it is known as IIFE
(function info() {
alert("Hellow");
})
();
5. Arrow function
a. Arrow function was introduce in ES-6 version of JavaScript
b. Main purpose of an arrow function is to reduce syntax
c. Syntax : () => (name = Fat Arrow)
//!--Arrow Function
let a= ()=>{
[Link]("Hello Arrow")
}
a()
let b=()=> [Link]("Hrllow arrow one line")
b()
//!-arrow function with parameter
let c=(a,b)=> [Link](a+b)
let n=10;
let v=()=>{
let n=20;
[Link](n)
[Link](this.n) // refer to window object
}
6. Nested Function
a. function inside another function called nested function.
b. A nested function is the fun in which a func will be inside of another function
c. Js currying calling child function using parent function by giving multiple parenthesis() using parent function.
d. when child function trying to access data from parent function, a closure is created in heap memory to store current
data.
function bank(){
[Link]("First")
var loan=2000;
function saving_account(){
[Link]("Second")
var balance=20000;
function fd_balance(){
[Link]("Third")
var fd_bal=100000;
var total_balance=balance+fd_bal-loan
[Link](total_balance)
}
return fd_balance;
}
return saving_account;
}
bank()()();
7. Higher order Function
a. Is a nothing but which is accept the function as its parameter
b. It is a function which accepts another function as parameter
c. A function which is pass as an argument '
//!--- Higher Order function
function hof(a,b,cb){
let add=a+b;
return cb(add);
}
function cb(x){
[Link]("HOF",x);
}
hof(2,5,cb)
8. Call Back Function
a. It is a function which is passed as an argument to an another function
9. Recursive Function
a. Function is calling itself from inside from body
10. Generator Function
a. It is use to generate unique code whenever function is called
b. Yield it is use to stop execution of an function in between
11. Closer
a. Whenever a child function trying to access data from its parent function a closer will be created in the heap area
12. Lexical scope
a. The ability of JavaScript engine to search for a variable in outer scope when it is not available in the local scope
------------------------------------------------------------Stirng------------------------------------------------
STRING:-Collection of characters (or) bunch of characters we called it as string
1. The length property returns the length of a string:
Ex:- let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
[Link]([Link])//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 = [Link](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 = [Link](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 = [Link](7,6);//banana
5. replace():-The replace method replaces a specified value with another value in a Sring By default, the replace() method
replaces only the first match.
Ex:- let text = "Please visit Microsoft!";
let newText = [Link]("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 = [Link]();//hello world!
7. indexOf():-
• The indexOf() method returns the index of the position of the first occurrence of a Secified text in a string.
• IndexOf() return -1 if the text is not found. Ex:- Let str "please locate where 'locate' occurs!"; [Link]("locate");//7
[Link]("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 eturns the last occurrence of the specified substring at an index less than
or equal to the pecified number.
Ex:- Let str="please locate where 'locate' occurs!"; [Link]("locate");//21
[Link]("locate");//-1
[Link]():-
• The includes () method returns true if a string contains a specified string. Otherwise it returns false,
• The includes () method is case sensitive.
Syntax:-[Link] (searchvalue, start)
Ex:- let text = "Hello world, welcome to the universe."; let result [Link] ("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
------------------------------------Array---------------------------------------------------
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
• 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.
• [Link](): It will convert string into an array
Filter(), map(), reduce()---------------------------
Filter():
filter() is Is a d HOF which will check a particular condition for each element in the original array. If the element satisfy the
condition the element will be pushed to the new array.
Syntax:
[Link]((ele,Index,arr)=>{
return condition
})
Example:
let numbers = [1, 2, 3, 4, 5];
let evenNo = [Link]((x) => x % 2 === 0);
[Link](evenNo); //[2, 4]
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.
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 Cray. 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);
[Link](doubledNumbers); // Output: [2, 4, 6, 8, 10]
Reduce():
the reduce() is a HOF which will return a single value from the original array. if no initial value is given, the accumulator will be
assigned with the first value of the array
SYNTAX:-
[Link]((acc,ele,index,arr)=>{
//statements
}.init)
Example: -
let arr = [1, 2, 3, 4, 5);
let sum = [Link]((accumulator, current Value, index,arr) => {
[Link](accumulator, current Value,index);
return accumulator+currentValue
},100);
[Link](sum)://115
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
• 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. [Link] object literal.
• [Link] creating instance of Object directly (using new keyword).
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
[Link]([Link]+" "+[Link]+" "+[Link]);
</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();
[Link]=101;
[Link]="Ravi";
[Link]=50000;
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
• In JavaScript, to access and manipulate object properties: dot notation
• 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'
};
[Link]([Link]); // John [Link]([Link]); // New York
OBJECT METHODS
• Objects can also have methods.
Methods are actions that can be performed on objects.
OBJECT METHODS:-------------------------
[Link]: 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
[Link]: We can only update the properties
[Link]: 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
DOM----------------------
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 DocumentObjectModel of the page.
• TheHTML DOM model is constructed as a tree of Objects:
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.
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
○ Doubleclick
○ Keypress
○ Keyup
○ Keydown
DOM Event Listener
• TheaddEventListener() method attaches an event handler to the specified element
• The first parameter is the type of the event (like "click" or "mousedown" or any otherHTML DOM Event.)
• The second parameter is the function we want to call when the event occurs.
Ex:
[Link]("click", function(){
alert("Hello World!");
});
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.
• [Link](): 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
• stopPropagation() in bubbling phase, it will block the progation to reach to the outer moat element from the targetted
element
• stopPropagation() in capturing phase, it will block the progation to reach to the targetted element
Promises-----------------------
• In JavaScript, promises are a mechanism for handling asynchronous operations. They provide a way to work with asynchronous
code in a more structured and readable manner. Promises represent a value that may not be available yet but will be resolved at
some point in the future, either successfully with a result or with an error.
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.
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
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.
}
)):
Promise methods
1) [Link]() ==> all promise should be in resolve state
2) [Link]() ==> either resolve/ reject, then() block will execute or else catch() block..[catch block output we cant see)
3) [Link]() ==> atleast 1 or more promises should be resolved, then() will execute or else catch() block.
4) [Link]() ==> it depends upon time, which ever comes first that promise will get executed.
Fetch API ----------
• fetch() is used to send a request to backend, it accepts a URL/API as an argument. This url should be in String
• The fetch method returns a promise object. This object need to be handled using then() and catch()
• We need to first handle the response object and parse it to get normal object using json()
• In the next then method we will be able to consume the data (using data from backed is called consuming data)
►EXAMPLE:-
fetch('[Link]
// return [Link]() //?return in array of object
return [Link](); //?return in array of object
}).then((res)=>{
[Link](res)
})
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. It allows you to write
►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