JS - Note

Variable- 

 typeof- 

  •  typeof undefined- is undefined 
  • let car;  then = typeof car is undefined
Equal and Strict equal- 

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 Undefined
const x; console.log(x) - gives Syntax Error
Null and Undefined difference- When a variable is undefined, it means it has been given no value to hold. Whereas, when a variable is null, it means the variable has a value, the value null.

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.- 

    switch(rollNumberToCheck) {
    case 8746: case 5649: case 3268: case 7901:
    console.log("Congratulations, you have passed the test!");
    break;

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 Smith
console.log(null ?? "Hello Guest");  -> returns Hello Guest
console.log(undefined ?? null); -> returns right handed null


TYPE CONVERSION-

to String- we can use either String(value) or  value.tostring() to convert a non-string value to a string. When we need to convert null, or undefined into a string, we can only use String(). Using toString() 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->0
null->0, undefined->NaN
isNaN 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 use typeof with any composite data type, we get the output "object". Ex- 

output
typeof null ->also returns object



FUNCTION- 

standard declaration- function functionName(){}
Anonymous Function- 
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.");}
arrow functions with only one parameter, we don't need the parentheses- ()
Default Parameter-
When we don't specify an argument when needed to be passed , it is set as undefined.
Default parameters are function parameters that use a specified value as the default value if a function call passes undefined to that parameter.


syntax-> (parameter1, parameter="default param value"){//function definition}
  • 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.


 Here it returns the value of console statement , so its undefined.









Function as Object Propoerty- 
When we store function as a property of an object those are called methods.





callback function function is  passed as an argument to another function.




ARRAY METHODS-II-

FOR EACH- 
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.

Ex- const numbers = [1, 2, 3];
      numbers.forEach(number => {console.log(number * 2);});//output- 2,4,6

Ex- const result = arr.forEach(num => num * 2); // No effect,printing result gives undefined


parameter can take-element,index,array- ex-  fruits.forEach((fruit, index, array) => {.......//here fruit is element (each element in array)})


MAP- 
Doesn't change the original array and creates new array.
Ex- const oddNumbers = evenNumbers.map((number) =>(number + 1));
       console.log(oddNumbers);
// gives number+1 of the evenNumbers array elements 

NOTE - The map() method returns an array, while forEach() does not.

FILTER-  

 const evenNumbers = numbers.filter(number => number % 2 === 0);
 console.log(evenNumbers); // Output: [2, 4, 6] // given numbers=[1,2,3]

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 


We can use Array.from() to create an array from an object too.

we can't use Array.from() on objects if it doesn't has length property, if it doesn't use length this can be done- 

const continentsArray = Object.values(continents);

Also the object properties must be indexed.(here 0,1 ...keys), if the indexes are not in sequence like 2,5,7 etc then the rest index values are filled with Undefined.

Array.isArray(value)-  checks if the given value is array or not 

LOOP

For-in loop and For-of -  For-in gives the index/keys associated with array/object,(if printed i in let i in arr -gives index, it is different than for-of as there it will give the values)
Here  it gives the values associated with the keys in object.
here in for-of ,it gives values not 0,1 ,2 (indexes) as it would in for-in 
-----------------------------------------------------------------------------------------------------------------------------

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 repeatedIf 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.

2. includes()- true if item present

3. slice(start index, end index not included) copies a portion of an array into a new array. E.g.- const fruitsSubArray = fruits.slice(1, 4).
A negative value means the index is equal to the length of the array minus the absolute value of that argument. E.g.- 
const fruits = ["apple", "banana", "mango", "orange", "kiwi"];
const fruitsSubArray1 = fruits.slice(-3);
const fruitsSubArray2 = fruits.slice(2);         // subarray1 and 2 are same
  • only calling slice() -generates copy of the array
  • .slice(3); - starts copying from index=3
4. splice(start, number of elements to remove)- modify an array by removing, replacing or inserting elements.(removes those elements from original array). E.g.- splice(1, 3); removes 3 elements starting from index 1 .
  • fruits.splice(2, 1, "kiwi");- removes 1 elements staring from index 2 ,inserts kiwi there
5.concat-arr1.concat(arr2), joins, creates new array. E.g.- evenNumbers.concat(oddNumbers, 7, "Integers", true) - creates new array -evenNum + oddNum + 7 +"Integers" +true

6. join() - creates string containing all elements of an array,  if takes argument -it uses the argument as separator of elements,e.g.-fruits.join("+");//give sapple+banana+mango+orange

7.find(test function)-executes test function on each element of array ,gives 1st elements that satisfies, ex-people.find(p => p.age >= 18);

8. sort()- changes the array ,sorts it. The 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.-
numbers.sort((a, b) => a - b); - if positive a comes after b , neagtive then a before b ,zero unchanged

9.every()-method allows us to check if all elements in an array satisfy a given condition
e.g.- array.every(callback(currentValue, index, array), thisValue);
  • 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.
10.reduce(function,initialval)- The 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.- 

const numbers = [1, 2, 3, 4, 5];
const initialValue = 5;
const calculateSum = (accumulator, currentValue) => accumulator + currentValue;
console.log(numbers.reduce(calculateSum, initialValue)); //output is 20 

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:

if any parameter is unused/not to be given , use _ in place of it. e.g.- 
forEach takes 2 parameters as default, for example-fruits.forEach((fruit,index) => console.log(index));//prints index of each element, but we can use -fruits.forEach((_, index) => console.log(index)); as index here can only be used in 2nd place

12. reverse()- reverses the original array

13.fill("value")-  changes values inside an array with a value of our choice. E.g.-names.fill("Unknown");
animals.fill("value", 1, 4);//starts changing from index 1 to index 3 (4 is not inclusive)


Rest n Spread-

1.Iterable - array , map, set,string are iterable but objects aren't.

2.spread- used to expand an iterable. e.g.-Math.max(...numbers);//finds max element of numbers array, or e.g.-const allStudentMarks = [...studentMarksSem1, ...studentMarksSem2];//creates new array containing elements of thise 2 arrays
  • 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.
3.Rest-rest parameters method enables a function to have an unspecified number of arguments. e.g.- 

const printHighestScore = (name, ...scores) => {
  const highestScore = Math.max(...scores);
  console.log(`${name}'s highest score is ${highestScore}`);
} //here it can take any number of scores

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)
Global variables that are declared with the 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.-

const count = 7;
let age = 23;
console.log(window.count);
console.log(window.age);//            gives undefined

count = 7;
console.log(count);
console.log(window.count);//         gives 7

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 declarationonly declarations are hoisted. Initializations are not hoisted. e.g.-

console.log(num);
var num = 1;  //output undefined not error, this code is converted as given below----

var num; // Declaration is hoisted to the top
console.log(num);
num = 1;

Timeout n Interval- 

1.setTimeout(function,time in ms)- 

We can only pass the name of the function as argument. If that function also requires arguments to be passed, you can pass them by adding them after the first two arguments as - setTimeout(displayGreeting, 2000, "Oliver", "Smith")
// here oliver and smith are arguments. 

Another preferred method- 

const displayGreeting = ({ firstName, lastName }) =>
  console.log(`Hello, ${firstName} ${lastName}!`);
 setTimeout(() => displayGreeting({ firstName: "Oliver", lastName: "Smith" }), 2000);
console.log("Timer started...");

2.clearTimeout(value)- cancel a timer ,takes value returned by setTimeout as argument    

const timeoutID = setTimeout(displayGreeting, 3000);
clearTimeout(timeoutID);

3.setInterval(function,interval)- another method

const displayGreeting = ({ firstName, lastName }) =>
  console.log(`Hello, ${firstName} ${lastName}!`);
setInterval(()=> displayGreeting({ firstName: "Oliver", lastName: "Smith" }), 5000);

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 
 2. const currentDate = new Date(); 
      console.log(currentDate.toString()); // to convert into string
3. for it to contain date as string use - toDateString()
4. use -.getFullYear()  to get the year only
5. The getMonth() gives the month as a number between 0 and 11. Here, 0 represents January and 11 represents December.
obj.getDate()- day , obj.getMonth()+1-month, obj.getHours()-hours ...
similarly use setDate(value), setMonth(value) to update

Storage-

Items get lost after refreshing, so solution is LocalStorage-a persistent web storage object that allows us to store key/value pairs in the browser. It remains saved in the browser and persists even when the page is refreshed or when the browser is closed and reopened.
sessionStorage- survives refresh but data delets when page is closed .

localStorage.setItem('key', 'value');- to add item in localstorage similarly in session-storage.

console.log(sessionStorage.getItem('key')) - gives the value associated with key , similar in local storage

localStorage.removeItem('key')- removes the key + value pair

localStorage.clear() sessionStorage.clear()
to clear all 

JSON(object notation)-

JSON is a way to represent JavaScript objects as strings. 
When we pass an object to 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



e.g.1- 
const userInfoJson = JSON.stringify(user, ["firstName", "lastName"]);//only 1stname, lastname
 
e.g.2- 
const checkIfStringValue = (key, value) => typeof value === "string" ? undefined : value;
const nonStringPropsJson = JSON.stringify(user, checkIfStringValue);//output filtered by function checkIfStringValue

ex3- 
const stringifiedUserInfo = JSON.stringify(user, null, "===");//indentation by ===

JSON.parse(string)- converts back into object

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 parameterskey and value.

ex-


ARRAY DESTRUCTURING-

Efficient way to assign specific array elements to other variables, not manually like x= array[0],y=array[1]...
Destructuring allows us to copy array elements into variables without modifying the array.
syntax - [...] = array

Default value-   here 0 is set as default value

OBJECT DESTRUCTURING-

copy the value of properties of objects and store them in other variables. The name of the variable we store the value of a property in, should be same as the key of that property. e.g.-
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 destructuringlink

destructuring use in Named parameters, used when we want to pass parameter to a function - link, use object to pass as parameter not simple values
instead of this-

this 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)
It is a best practice to use named parameters when a function has more than two parameters.

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 present
when 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. 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[].. remaining
Async- 
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.
  1. 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.

  2. The API responds with data in JSON format.

  3. The response.json() method processes the response and converts it into a JavaScript object. It returns another Promise containing the actual data.

  4. The .then() block receives the parsed data and logs the cat fact to the console.

  5. 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 data
POST: Submit data
PUT: Update dataW
DELETE: Remove data21 
PATCH: Modify part of the data
headers: 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.length
upper-lower case- .toUpperCase(), .toLowerCase();
padding-  "Sam".padStart(10,"*") - adds padding of * to the start to make the string of length 10 , similarly padEnd
indexOf- 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 undefinedbecause, 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"

another ex- 
 
but if -


Execution Context

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 false
number of properties- mapobj.size
delete- obj.delete(key)- true id deletion successful
The map.clear() method removes all the elements from the Map.
Map from Object- 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().
convert to object from Map- Object.fromEntries(map);, All the keys are converted into strings .If any  map has key which is an object then its converted into "[object Object]" .

How to convert array of objects into Map- 2 mathods- 

1. Map() Constructor and Array map()

To convert an array of objects to a map, we can use the Arraymap() 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-
Set is a collection of unique values. It can store values of any type. Ex- new Set(['Sam', 'Oliver', 'Adam']);
The has() method can be used to check if a given element is present in a set.Ex- names.has("Sam");// returns true or false
to convert array into set-
const array = [1, 2, 3, 3, 4, 5]; const set = new Set(array); console.log(set); // Output: Set {1, 2, 3, 4, 5}

TRY N CATCH-
using with async:

try catch normally like above doesn't workuse 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).

showing only throw


using throw new Error







handling specific error- rethrowing error-try-catch normally tells one message for every error in try, to show particular error in try we use instanceof keyword, else part rethrows other unhandled errors

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

false
because the addresses r not same but 
is true.

for DeepCopy- the data same, address different , if updated no effect on other copy, then use spread operater {...obj}
but 
when we use the ... 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.
-
instead of this(JSON) the new JS format for deep copying- copyobj= structuredClone(obj); 
note that structuredClone() is unable to perform a deep clone of functions or methods present inside the obj.

MUTATION-
avoid calling Object.asign(), sort, splice, poop, push etc on the original object or array, it will change the original also.so use rest-spread operator to create copy, ex- 
here upper format isn't recommendeed but lower one is preferred






we cannot reassign a variable declared using the const keyword.
It is possible to both mutate and reassign variables declared using the let keyword.

CALL, APPLY ,BIND-
call- if a method is present common in both the objects we shouldnot write that in both rather we write separately and call using -function.call(obj, optional argument as string) (object that the 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.
using arguments-

NUMBER METHOD 2

1.if we have to convert number other than decimal format to decimal then pass its format to parseInt(num,present_format)- 
const binaryNumber = "1111011";
const decimalNumber = parseInt(binaryNumber, 2);// decimalNumber= 123
2. instanceof, class object- 
checking obj instanceof class- true if obj os object of class, false if not.

Comments

Popular posts from this blog

The Anatomy of a Backend Request: Layers, Middleware, and Context Explained

Validations and Transformations (Sriniously)