JS - Note
Variable-
typeof-
- typeof undefined- is undefined
- let car; then = typeof car is undefined
let objOne = { name: "Smith" };let objTwo = { name: "Smith" };console.log(objOne === objTwo); // output false , also false in equal operator (as the onjects are stored in different locations)
null==undefined-> true
String Interpolation
calculation inside template-string( ${}) - example- ${firstNumber * secondNumber}
Undefined & Null-
let x; console.log(x) - gives Undefinedconst x; console.log(x) - gives Syntax ErrorNull and Undefined difference- When a variable isundefined
, it means it has been given no value to hold. Whereas, when a variable isnull
, it means the variable has a value, the valuenull
.
OBJECT -
- to get keys- Object.keys(objName)- returns array
- to get values - Object.values(objName)- returns array
- to get both as array format- Object.entries(objName)
- remove element from object- delete ......//write the value as objName.key etc
Array -
- push()- array.push("value") // new element to the end of an array.
- unshift() // new element added to the beginning of array.
- pop() //removes last element of array e.g.- arrays.pop() //The
pop()
method also returns the element that was removed(store it in a variable or directly controllog it ) - shift()- The array.
shift()
method removes the first element of an array.
CONDITIONAL-
- multiple switch cases- e.g.-
Nullish Coalescing Operator-
- denoted as
??, can be used when we expect the returned valuecan be -null or undefined.
- returns the left-hand operand provided that the left-hand operand is not null or undefined. Otherwise, it returns the right-hand operand.
ex-console.log("Hello Sam Smith" ?? "Hello Guest"); -> returns Hello Sam Smithconsole.log(null ?? "Hello Guest"); -> returns Hello Guestconsole.log(undefined ?? null); -> returns right handed null
TYPE CONVERSION-
to String- we can use eitherString(value)
or value.tostring() to convert a non-string value to a string. When we need to convertnull
, orundefined
into a string, we can only useString()
. UsingtoString()
in such cases will give us an error.to Number- by Number(value) - it returns a number. If done value ="", then converts to 0, if value is string value other than number then it converts to NaN.true->1, false->0null->0, undefined->NaNisNaN method- converts the value to number and then checks if its value is NaN. Ex- isNaN(greeting) returns true and isNaN("2") gives false.composite data type-when we usetypeof
with any composite data type, we get the output "object". Ex-
outputtypeof null ->also returns object
const displayValidationError = function () {console.log("The user details are not valid.");}displayValidationError(); //Here, the variable name serves as the function name.
Arrow Function -
const displayValidationError = () => {console.log("The user details are not valid.");}
- After the return statement in a function is executed, further execution of the function is terminated.
- Arrow Function Shorthand-
const calculateSum = (number1, number2, number3, number4) =>number1 + number2 + number3 + number4;
// here it returns sum of n1,n2,n3,n4 we don't exclusively write return.
forEach
- does not return anything; it only executes a function for each element.(no new array) For Each- visit each element in an array one by one and perform a specific action on every element without changing the original array.parameter can take-element,index,array- ex- fruits.forEach((fruit, index, array) => {.......//here fruit is element (each element in array)})
map()
method returns an array, while forEach()
does not.FILTER-
In the example given above, numbers.filter(number => number % 2 === 0)
returns an array that contains only those elements of numbers
that returns true
when passed as the argument to number => number % 2 === 0
.
Array.from(element, Optional function)-
element is the thing(string/object etc) to be converted to array and function is optional
Array.from()
to create an array from an object too.const continentsArray = Object.values(continents);
LOOP-
Array method-3
1. indexOf()- searches for a given element in an array. It returns the first index at which the element is found. lastIndexOf() finds the last index of found element if repeated. If the element is not found in the array, it returns -1. E.g. - fruits.indexOf("banana", 2) starts searching from index 2 but numbering is done normally.
- only calling slice() -generates copy of the array
- .slice(3); - starts copying from index=3
- fruits.splice(2, 1, "kiwi");- removes 1 elements staring from index 2 ,inserts kiwi there
sort
method looks at the array elements as strings, ("11" comes before "2"),which can lead to incorrect sorting for numbers. so we use function as arguments.To properly sort numbers, we must use a comparison function,e.g.-every()-
method allows us to check if all elements in an array satisfy a given condition- array: The array to iterate over.
- callback: A function to test each element of the array.
- currentValue: The current element being processed in the array.
- index (Optional): The index of the current element being processed.
- array (Optional): The array every() was called upon.
- thisValue (Optional): Value to use as this when executing callback.
reduce()
method iterates over an array, applying a callback function that accumulates values into a single result, using an initial value and updating it with each element.(On the first invocation, the accumulator
is set to the initial value, and the currentValue
is the first element of the array) e.g.- 11. some(function) - check if at least one element in an array passes a specified test..some()
returns true if the callback function returns true for at least one element, otherwise, it returns false.
use of underscore:
Rest n Spread-
- Note- When you spread (
...
) multiple objects into a new object, properties from later objects override earlier ones if they have the same keys. - We can use the spread operator to split a string into an array of its characters.
Note- rest parameters can only be used once in a function definition and should be used as the last parameter.
Rest Operator collects values into a single value. On the other hand, a spread operator expands the values of an iterable into parts.
Scope-
- global
- local(function, block)
const
and let
keywords do not become properties of the global
or window
objects. A variable declared without using the const
or let
keywords becomes a property of the global
or window
objects-e.g.-we can also write - window.count = 100; or window["full name"] = "Oliver Smith";//here full name is a variable
scope nesting-inside can access outside but reverse not true
Hoisting -we can access the variables and functions even before their declaration. only declarations are hoisted. Initializations are not hoisted. e.g.-
Timeout n Interval-
1.setTimeout(function,time in ms)-
2.clearTimeout(value)- cancel a timer ,takes value returned by setTimeout as argument
3.setInterval(function,interval)- another method
here displayGreeting is wrapped inside a function as setInterval
requires a function reference, not the result of a function call.
4.clearInterval(timerID returned by setInterval method)
Date Object-
1. new Date()-
returns a Date instance representing the current date and time getMonth()
gives the month as a number between 0 and 11. Here, 0 represents January and 11 represents December.Storage-
JSON(object notation)-
JSON.stringify(),
it returns the JSON representation of that object. Output is a comma-separated list of key-value pairs. Only string values in a JSON string are wrapped in double-quotes.JSON.stringify()
method accepts three arguments -
The value to be converted into a JSON string.
Either an array or a function that can be used to filter the properties of the first argument and include only those properties in the JSON string.
Either the number of spaces or the string to be used for indentation of the JSON string
JSON.parse()
takes two arguments:
The JSON string to be converted.
A function that can be used to transform the property being parsed. The is invoked on each property being parsed. Each function has two parameters -
key
andvalue
.
ARRAY DESTRUCTURING-
[...] = array
const fruit = {name: "Apple", color: "red", weight: 100 }const { name, color, weight } = fruit;other ex- const fruit = {name: "Apple", color: "red", weight: 10 } const { name, color, weight } = fruit;solution method to the problem(same key name)- uses ':'-nested destructuring - link
destructuring use in Named parameters, used when we want to pass parameter to a function - link, use object to pass as parameter not simple valuesthis is preferred-
In the example given above, the function displayProfile
only has one parameter, which is an object - student
. However, we do not use the object student
as a whole within the function. We only use each property individually. In that case it will be better to destructure the student
parameter.(we can also use part of the elements of student as parameter when destructuring)
Optional Chaining-
optional chaining is used When accessing the property of an object that we think might be null
or undefined
, we add a conditional operator as well, i.e., ?.
so that we don't get error.
when accessing method - it can be used as -user1.showGreeting?.();, no error if the method isn't presentwhen using bracketed notation - user2?.["full-name"]
ASYNCHRONOUS CODE- code that runs in the background while the rest of the code is being executed is called asynchronous code.(setTimeout used )
PROMISES-
callback in asyn-if we want to perform some operation only after the asynchronous operation is complete.nested callback s create pyramid like structure called Callback hell , promises are solution for that. A Promise is an object that represents the eventual completion or failure of an asynchronous operation. A JavaScript promise can be in one of these three states - pending, fulfilled, or rejected. A promise is pending when it's created. It's fulfilled when the asynchronous operation is successful, and it's rejected when the asynchronous operation fails. The promise takes a callback function with two parameters - resolve
and reject
.
then method- handle a promise when it's fulfilled. It takes a callback function as a parameter. The callback function takes the resolved value as a parameter.catch method- handle a promise when it's rejected. can be written as - .then().catch().catch(rejectedValue => { console.log("'catch' method called"); console.log(rejectedValue); console.log("Rocket launch process completed."); });finally method - written at last for common/cleanup codes ,
.
.
.
Promises.all[].. remainingAsync- When we append the async
keyword to a function, it means that the function will always return a promise. Even if a function actually returns a non promise value, it will be wrapped in a resolved promise.await- await
is a keyword that can be used inside an async function to pause the execution of the function until a promise is resolved.
API-
The Fetch API is a feature in web browsers that allows developers to make network requests to retrieve data from servers or send data to servers.The fetch()
function sends a request to the CatFact API at https://catfact.ninja/fact
, which provides random cat facts, and returns a Promise object.
The API responds with data in JSON format.
The response.json()
method processes the response and converts it into a JavaScript object. It returns another Promise containing the actual data.
The .then()
block receives the parsed data and logs the cat fact to the console.
If something goes wrong during the request or response parsing like a network error, the .catch()
block handles the error and logs it to the console.
response.text() Use this for plain text like .txt or .csv files. response.json() (most widely used)-Use this for APIs that return structured JSON data. response.blob()-Use this for binary data like images, videos, or files. response.formData()-Use this for handling form submissions.
XMLfetch example- error- fetch api only shows error for network level error, not other like http error code like 404 or 500 etc so to add explicitely other errors-- The
response.ok
property provides a simple way to verify if the HTTP status code falls within the successful range (200–299)
.
Customizing fetch()
Requests:fetch(url, { method, headers, body })-
The fetch()
method takes two arguments: url
and an optional options
object.
method: Defines the HTTP request type.GET
(default): Read dataPOST
: Submit dataPUT
: Update dataWDELETE
: Remove data21 PATCH
: Modify part of the dataheaders: Set custom request headers like Content-Type
, Authorization
, etc.body: Send data (usually JSON) in the request body—used with POST
, PUT
, and PATCH
.
POST - id should be there in addition to others in the request.DELETE only requires the method ,no request body is required,PUT (the url be likehttps://jsonplaceholder.typicode.com/users/<id>
.) e.x-
STRING METHODS- string characters- can be accessed as array ,e.g.- string[0] ...length- string.lengthupper-lower case- .toUpperCase(), .toLowerCase();padding- "Sam".padStart(10,"*") - adds padding of * to the start to make the string of length 10 , similarly padEndindexOf- The indexOf()
method helps us locate a substring inside a string. The method accepts two arguments - substring and fromIndex. The default value of fromIndex is 0
.ex- message.indexOf("es", 9);//starts searching for 1st occurance of "es" from index 9 to last , if no matches then returns -1.lastIndexOf() finds last instance of given value. ex- message.lastIndexOf("es", 10);//searches from index 10 to 0.check if present- message.includes("mangoes");startsWith("val")- checks if string starts with val.....NUMBER METHODS-
var.toFixed(2)- 2.43519 to be represented as 2.44. The toFixed()
method fixes the number of digits after the decimal point.parseInt(string)- converts a string to an integer, parsing from the start until a non-digit; returns NaN if it doesn't start with a number, +
, -
, or 0x
.parseFloat(string)-converts a string to a floating-point number, parsing until a non-numeric (excluding .
and e/E
); returns NaN if it doesn't start with a number, +
, -
, or .
.Infinity- Infinity = NaN
THIS-
this
refers to the object that calls the function, not where the function is defined.inside arrow function-this works fine in normal functions(using function keyword).here it is undefined
because, arrow functions do not have their own this
binding and capture the this
value from the surrounding context. If it doesn't find a this
, it will default to the global context. In the browser, this
will be the window
object. And the fullName
property does not exist in the window
object. We can access here if we do - window.fullName = "Sam Smith"
but if -Execution context is the environment where JS code runs.
There are two types:
-
Global Execution Context (GEC): Runs top-level code; only one per program.
-
Function Execution Context (FEC): Created on each function call; stores function's variables and has access to outer scope.
It includes a variable environment and a lexical environment for tracking variables and scope.
Lexical Environment is a structure created when JS runs a block or function. It stores variables (in the environment record) and links to its parent scope (via the outer reference).
-
If a variable isn’t found locally, JS follows the scope chain (outer references) until it finds the variable or reaches global scope.
Lexical Environment vs Lexical Scope:
-
Lexical Environment: Stores variables and scope relationships.
-
Lexical Scope: Rules that define how and where variables can be accessed, based on where they're declared, not called.
MAP-Maps store key-value pairs like objects, but allow any key type, maintain insertion order, and are iterable.created using -new Map([[key,value], [key2,value2]])add value- mapobj.set(key,value)fetch data- mapobj.get(key)contain or not- mapobj.has(key) - returns true or falsenumber of properties- mapobj.sizedelete- obj.delete(key)- true id deletion successfulThe map.clear()
method removes all the elements from the Map.
using Object.entries() as- new Map(Object.entries(userObj));as
new Map() only accepts an iterable, like an array. Since an object is not iterable, we create an array of all the key-value pairs of the object, using the Object.entries method and pass that to new Map()."[object Object]"
.1. Map() Constructor and Array map()
To convert an array of objects to a map, we can use the Array
map()
method to create an array of key-value pairs, and then pass the resulting array to a Map()
constructor to create a Map
object.
const arr = [
{ key: 'user1', value: 'John' },
{ key: 'user2', value: 'Kate' },
{ key: 'user3', value: 'Peter' },
];
const map = new Map(arr.map((obj) => [obj.key, obj.value]));// Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' }
console.log(map);
In the callback passed to the map()
method, we return an array containing the key and the value for each object. This will result in an array of key-value pairs:
// [ [ 'user1', 'John' ], [ 'user2', 'Kate' ], [ 'user3', 'Peter' ] ]
console.log(arr.map((obj) => [obj.key, obj.value]));
The Map
constructor can take an array of this form as an argument to create a Map
object.
2. Map set() and Array forEach()
Another way to convert an array of objects to a map is with the Array
forEach()
method. First, we create a new Map
object. Then, we add entries for all the array elements to the Map
, by calling the Map
set()
method in the callback passed to forEach()
. Here's an example:
const arr = [
{ key: 'user1', value: 'John' },
{ key: 'user2', value: 'Kate' },
{ key: 'user3', value: 'Peter' },
];const map = new Map();
arr.forEach((obj) => {
map.set(obj.key, obj.value);
});// Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' }
console.log(map);
Set
is a collection of unique values. It can store values of any type. Ex- new Set(['Sam', 'Oliver', 'Adam']);has()
method can be used to check if a given element is present in a set.Ex- names.has("Sam");// returns true or falsetry catch normally like above doesn't work, use
try...catch
inside the definition of the function passed as argument. like below(only error causing part of function will be in try)-Error object- in JS error is represented as object, name is name of error , message is its description, here error variable stores the error object.
What if I try to show an custom error- use throw keyword , using only throw
errormsg returns string type error but , to throw error object we type throw new Error(errormsg).
COPYING -
when we copy a composite data(object, array...) type, we are copying the address of the memory location where the data is stored.if -let user= {name:"jk"}, user only holds the address where the object is stored. so if we update in one , other is also updated, so its called shallowcopy...
operator to create a copy of an object, any nested objects will be shallow copied. we can avoid using JSON.stringify(user)
converts user
object into a JSON string. Then, the JSON.parse
converts that JSON string back into an object.structuredClone()
is unable to perform a deep clone of functions or methods present inside the obj.MUTATION-
const
keyword.It is possible to both mutate and reassign variables declared using the
let
keyword.this
keyword inside the function will refer to.)apply(obj, argument array)- similar to call() but the diff is - bind()- The
bind()
method is used to create/returns a function that invokes a specific function and provides the object that the this
keyword inside the function should refer to.
Comments
Post a Comment