js for (client side hacking)(learning daily)
ALL THE STUFF IS WRITTEN ARE MY NOTES . MY EXPERIMENTS ARE BEEN DONE HERE , AS A SOURCE CODE REVIEW , CLIENT SIDE REVIEW PERSON I HAVE TO CHECK THE CODE ANALYSE IT , UNDERSTAND IT !!
ALL THE STUFF IS WRITTEN ARE MY NOTES . MY EXPERIMENTS ARE BEEN DONE HERE , AS A SOURCE CODE REVIEW , CLIENT SIDE REVIEW PERSON I HAVE TO CHECK THE CODE ANALYSE IT , UNDERSTAND IT !!
AIM BIG ( DO WORK DAILY , SURROUND PEOPLE WHO WORK DAILY GRIND DAILY !!! TRUST ME !!! )
THERE ARE MANY CODES PRESENT LIKE I WAS PRACTISING ONE CONEPT A LOT , ITS TODAY 27/09/2025 AND I STARTED AT 18 OR 19 SEPT , DAILY I AM DOING THIS STUFF , AND YEAH I HAVE ALL THIS STUFF PRESENT IN MY HANDWRITTEN NOTES (VAHI SE TOH THODA EASY ANALYSIS HUA HAI LIKE CONCEPTS KI)

the following was nice code must run \
const max = prompt("Enter the value"); // 1. Ask user for input (string)
const a = Number.parseInt(max); // 2. Convert input to number
const actual = a - 13; // 3. Subtract 13
const percentage = actual / a; // 4. Calculate percentage
alert(percentage); // 5. Show result in alert

let sale = true; sale && console.log("Time to buy!");
Conditional Statements
Comparison Operators
7 min
When writing conditional statements, sometimes we need to use different types of operators to compare values. These operators are called comparison operators.
Here is a list of some handy comparison operators and their syntax:
less than:
<greater than:
>less than or equal to:
<=greater than or equal to:
>=is equal to:
===is not equal to:
!==
HERE IN THE BELOW CODE JUST CHANGE THE GREATER THEN SIGN THEN LIKE TRY OUT ALL THE SIGNS PRESENT THERE
truthy and falsely && Truthy and Falsy Assignment
Truthy and Falsy Assignment


Logical Operators
These operators combine multiple boolean expressions or values to provide a single boolean output:
&&(AND): Returnstrueif all operands evaluate totrue.||(OR): Returnstrueif one or more operands evaluate totrue.!(NOT): Returns the logical opposite of an operand’s boolean value (i.e.,!(true)returnsfalseand!(false)returnstrue).
The following example showcases the usage of logical operators:
truithly and falsey Assignment
Ternary Operator
here we are converting the code into the ternary , simple one !!!
corrected command down here !!!!
Else If Statements
10 min
We can add more conditions to our if...else with an else if statement. The else if statement allows for more than two possible outcomes. You can add as many else if
Preview: Docs Loading link description
as you’d like, to make more complex conditionals!
The else if statement always comes after the if statement and before the else statement. The else if statement also takes a condition. Let’s take a look at the syntax:
else if statements


the switech keyword
else if
Preview: Docs In JavaScript, a statement is a unit of code that performs a specific action or task.
are a great tool if we need to check multiple conditions. In programming, we often find ourselves needing to check multiple values and handle each of them differently. For example:

my own code
FUNCTIONS
What are Functions?
1 min
When first learning how to calculate the area of a rectangle, there’s a sequence of steps to calculate the correct answer:
Measure the width of the rectangle.
Measure the height of the rectangle.
Multiply the width and height of the rectangle.
With practice, you can calculate the area of the rectangle without being instructed with these three steps every time.
We can calculate the area of one rectangle with the following code:
Imagine being asked to calculate the area of three different rectangles:
In programming, we often use code to perform a specific task multiple times. Instead of rewriting the same code, we can group a block of code together and associate it with one task, then we can reuse that block of code whenever we need to perform the task again. We achieve this by creating a function. A function is a reusable block of code that groups together a sequence of
Preview: Docs Loading link description
to perform a specific task.
In this lesson, you will learn how to create and use
Preview: Docs Loading link description
, and how they can be used to create clearer and more concise code.

Calling a Function
Parameters and Arguments
1.
The sayThanks() function works well, but let’s add the customer’s name in the message.
Add a parameter called name to the function declaration for sayThanks().
default paramaters !!
RETURN
important codes just read and understand it please !!
hard code bellow try to understand
must try to understand please please
function expressing !!!
just keep grinding become js master atleas u should understand the code
concise body arroy functions


more easy to understand !!!
below the code are my takeaywas and experiments on this !! high level experiments on my own !!!!
🔥 Question 1:
Ek function banao squareNumber jo ek number lega aur uska square (number × number) return karega.
👉 Example:
squareNumber(5)→25squareNumber(10)→100
BELOW IS THE CODE LIKE I WANT TO DO IN SHORT ARROW FUNCTION FORM ;) ||| BEST CONCEPT OF FUNCTIONS CONVERTING IS PRESENT HERE !!
TUFF QUESTOIN
WRITE A CODE FOR A PRIME NUMBER
just read and understand the code use programizz to test the code by yourself
Blocks and Scope(codecadmey)
some leetcode questions to be solved ( after learning js )
Global Scope
Block Scope
Scope Pollution
must try to find the bug below , just analyze the code see that let num = 500 is global one and geetin reassigned into the function
here we can return only one single return only so we tried to return both declared variables in a single reutrn ;)
below is some correct and some wrong code ;) isske upper accha code hai !!!!!!!!!!!!!
bug finding
revised once !! done !!! , if i came here back i will be writeing revised second time !! and below code has nice catches !!!!
Review: Scope
• Scope refers to where variables can be accessed throughout the program, and is determined by where and how they are declared.
Blocks are statements that exist within curly braces
{}.Preview: Docs In JavaScript, a statement is a unit of code that performs a specific action or task.
Global scope refers to the context within which variables are accessible to every part of the program.
Global variables are variables that exist within the global scope.
Block scope refers to the limited reach of variables that are only available within the specific code block where they are defined.
Local variables are variables that exist within the block scope.
Global namespace is the space in our code that contains globally scoped information.
Scope pollution is when too many variables exist in a namespace or variable names are reused.
Arrays
RUN BELOW CODE TO LEARN THE CONCEPT OR SIMPLY TRY TO UNDERSTAND HERE !!!!!!
Creating an Array
Arrays can also be created with the Array class by using the new keyword and passing in the elements as comma-separated arguments:
THE BEST CONCEPT (JUST KEEP IN MIND LAZY ONE)
An array can also be created as empty and have its values added later through the help of the .push() function:
Accessing the Elements of an Array (this is all the theorey and practical did by the website , so i also have done some experiments inside , and if we move down the practicall continous !!
Array elements are ordered by index values, starting at 0:
Index 0 has the first element.
Index 1 has the second element.
Index 2 has the third element.
Index n-1 has the nth element.
Individual elements in the array can be accessed/changed using the array name and the element’s index surrounded by square brackets.
Run the code below to see how the element at index 0 in the musicGenres array can be accessed and have its value updated:
ANALYZE THE CODE PERFECTLY

ANALYZE THE CODE BELOW PERFECTLY !!! SOURCE CODE ANALYSIS (NEW CONCEPT )

CATCH HERE !!! NICE CONCEPT EXPERIMENT !! OF PREVIOUS ONE !!!

NESTED INDEX ARRAYS ( IMPORTANT AND EASY CONCEPT BUT LOOKS HARD)
ANALYSE THE BELOW CODE ;) —> AS I HAVE TO DO SOURCE CODE ANALYSIS IN FUTURE !!
below is the whole practical things we will be learning , above were the theorey and live concepts written and i readed that practised them a lot seiously and its helping me here wihle writing the practical code here !!!!!!!!
acessing elements
Update Elements && Arrays with let and const
The .length property
The .push() Method
const itemTracker = ['item 0', 'item 1', 'item 2'];
itemTracker.push('item 3', 'item 4');
console.log(itemTracker)
// Output: ['item 0', 'item 1', 'item 2', 'item 3', 'item 4'];
The .pop() Method javascript.pop method
basic example
above code defines that if i puted any index value inside the pop value , that element will be removed !!!
question practical solve
Use the
.pop()method to remove the last element fromchores.Checkpoint 2 Passed
2.
In a line after you called
chores.pop(), logchoresto the console to make sure it worked.
More Array Methods
Some other array methods that are available to JavaScript developers include: .join()Preview: Docs Elements of an array are converted to strings and concatenated together, returning the resulting string., .slice(), .splice()Preview: Docs Loading link description, .shift()Preview: Docs Removes and returns the first element of the array. All subsequent elements will shift down one place., .unshift()Preview: Docs Adds one or more elements to beginning of array and returns new length., and .concat(). Using these built-in methods makes it easier to do some common tasks when working with arrays.
syntax ---> array.method --> array.shift()
below is the nice code do review it !!!
JavaScript .slice()
so basically i had a nice doubt here like see , when i was using the conept of array.push and more like that i was getting the array changed , but in array.slice case iwasnt getting it changed ,
but jab mai .push , .pop aur like shift also i was just reassinging it brother ! and it was wokring but in slice its differnt why ?
Brilliant question bhai! 🔥 Ye bohot important concept hai!
Difference:
Mutating Methods (Original array ko change karte hain):
.push().pop().shift().unshift().splice()
Ye methods original array ko directly modify kar dete hain, isliye reassign karne ki zarurat nahi!
javascript
Non-Mutating Methods (Original array ko nahi change karte):
.slice().concat().map().filter()
Ye methods new array return karte hain, original ko nahi chhute!
javascript
Easy Yaad Rakhne Ka Tarika: (easy rembemring )

Rule: Jab method original array ko modify karta hai, toh reassign ki zarurat nahi. Jab new array return karta hai, toh variable mein store karo!
so here the catch is like non mutating array.methods!!
.slice().concat().map().filter().indexof()
so these are the arrays we have to declare the new functions nicely !!!
So below is the code for the nice and nice , we have to declare before using these exceptional array.methods !!!
so also review the below code and must type or paste into the online compiler and analyze calmly ---->>> lala bahut bada client side hacker bana hai brother !!!!
FUNCTIONS AND ARRAYS MIX (AT THIS TIME I AM SERIOUSLY HARD TO UNDERSTAND CALLING FUNCTIONS )
DO TRY TO UNDERSTAND THE CODE !! JUST PASTE THE CODE AND TRY TO EXPERIMENT AND ANALYSE IT PLEASE REVISE --->
some alternatives i practised !!!
below is the arrow function nicely done !!!


Arrays and Functions (nice concept one )
below is the nice concept to dont confuse ;)
NESTED ARRAYS S(PRACTICAL CODING WITH QUESTIONS )
so the notation below i did for the declared variable i.e , target , defining the proper number 6 so , just note that we have numberClusters[2][1] this is the type we have to do declare the concept!!!
javascript.entries() /noted this for myself to do learn this concept after my practical
JavaScript .entries()
BELOW IS THE JAVASCRIPT.MAP CONCEPT
array.forEach() quite intresting (we can define the function here !!!;)
javascript.every
synatx
array.every(callbackFn);
array.every(callbackFn , this Arg);
try the below code and analyse it in the online js compiler !!!!
important concetp functions
javascript.filter method
understand the below code and try to review the code !!
javascript.fill() method
understand the below code calmly !!! calm your mind with full focus !!!
javascript.find() method
Finding the first temperature that’s over 90°:

JavaScript .findIndex()
if nothing is satisfied than the result will be -1
JavaScript .findLast()
read the syntaxx .....and then understand the code carefully with the source code analysis !!!!!!!
JavaScript .findLastIndex()
JavaScript .flatMap()
read the below code and undestand it nicely !!!!!!.......

below is the best code to undestand perfectly and perfectly !!!!!!!

before understanding the above code we have to understand array.form !!!!!

loops (understand the concept by reading and then writing on your own );)
for loop
below is the quesation and i solved it myself ......
1.
Now, let’s make our own loop! Create for loop that iterates from 5 to 10 and logs each number to the console, including both 5 and 10.
When writing/changing loops, there is a chance we will get a dreaded infinite loop, which essentially stops our programming from running anything else! This occurs when the loop’s stopping condition is never met, causing the loop to continue iterating, blocking the rest of the program from executing.
To exit an infinite loop in an exercise, refresh the page — then fix the code for your loop before running it again.
ans;

question is
.
Update the for loop so that it loops backwards, printing 3 to 0 to the console, including both 3 and 0. Make sure to adjust all three expressions to achieve this, and be careful to avoid an infinite loop!
ans 👍
do solve the question below;
1.
Write a for loop that iterates through our vacationSpots array using i as the iterator variable.
Inside the block of the for loop, use console.log() to log each element in the vacationSpots array after the string 'I would love to visit '. For example, the first round of the loop should print 'I would love to visit Bali' to the console.
When writing/changing loops, there is a chance that our stopping condition isn’t met and we get a dreaded infinite loop which essentially stops our programming from running anything else! To exit out of an infinite loop in an exercise, refresh the page - then fix the code for your loop.
nested loops [hard]
IT MAY BE HARD BUT SERIOUSLY I UNDESTOOD ALL THE CODE HERE , AND IT TOOK ME AMOST HOURS TO UNDERSTANT THIS CODES , JUST OPEN THE ONLINE JS COMPILER AND TRY TO DO UNDERSTAND IT , READ THE CODE MULTIPLE TIME UNDERSTAND EACH AND EVERY LINE PRESENT !!!!!!!!!! THATS THE KEY
below are the starting example code ;)
below is the mine code after reading the previous code , i understood the code and then writed the logic code by myself and if incorrect always do chatgpt or any ai , claude one too
just understand by reading(like a source code reviewer) and then write that code on yourself!!!!
note: in above code i have given second for loop inside the first one , like call back function to check it
➤ Logic:
Pehla loop (
i) — array1 ke har element ko ek-ek karke uthata haiDusra loop (
j) — array2 ke har element ko check karta hai uske againstYani:
i = 0 → array1[0] = 1
check against array2[0], array2[1], array2[2]
i = 1 → array1[1] = 2
check against array2[0], array2[1], array2[2]
i = 2 → array1[2] = 3
check against array2[0], array2[1], array2[2]
Har element of array1 compare hota hai har element of array2 se. 👉 Isliye nested loop (ek loop ke andar doosra loop) lagaya gaya hai.
alternative
key point is array.includes which is working like call back function inside the if statement !!!!!!!
sed but too hard to understand the below code ..................
BELOW CODE IS ALL ANALYSED AND MADE BY ME THROUGHT UNDERSTANDING
1.
Imagine you’re a big-wig programmer for a social media platform! You have been tasked with building a prototype for a mutual followers program. You’ll need two arrays of “friends” from two mock users so that you can extract the names of the followers who exist in both lists.
Make a variable called
bobsFollowersand set it equal to an array with four strings representing the names of Bob’s friends. Each of the array elements should be uniqueCheckpoint 2 Passed
2.
Make a variable called
tinasFollowersand set it equal to an array with three strings representing the names of Tina’s friends. Make exactly two of these the same as two of the friends in thebobsFollowersarray.Checkpoint 3 Passed
3.
Create a third variable named
mutualFollowersand set it to an empty array.Checkpoint 4 Passed
4.
Create a nested loop that iterates through
bobsFollowersas the array for the outer loop andtinasFollowersas the array for the inner loop. If the current element from the outer loop is the same as the current element from the inner loop, push that element into themutualFollowersarray.
The While Loop
so below is the code and this is the starting of learing while loop and i just tried to understand it by pastying it in the compiler no running it , before running it , i understood (by understood meaning is i am totally focusing to understand the code what will be output (and for output you have to analyse the code in the compiler and try to understant it before running )


sing Date.now() (time-based randomness)
do while loop
so this is the do while loop section
below code is too nice to undestand just go on online compilers and try to read the code !!!
so the concept here is that if the code runs and do loop is matching the conditions as above code (one of the best examples here , ) if the condition is true than it will check the next , else (false) it will be stopped......
in below code analyse that the after console.log first msg , there is a condition and in js the condition is false for true === false as stated above !!!! and the loop stops
so thats the concept buddy!!!
now here the condition is true ..............so therefore and the loop become recurring (just running .....)
practise question
1.
We’d like a program to simulate part of the cake-baking process. Depending on the recipe, a different number of cups of sugar is required. Create the variable
cupsOfSugarNeeded, and assign it a number value of your choosing.The cups of sugar must be added to the batter one at a time. Declare the variable
cupsAddedand assign it the value0.Checkpoint 2 Passed
2.
We have a sweet tooth, so we want to add at least one cup of sugar to the batter even if the value of
cupsOfSugarNeededis0.Create a
do...whileloop which incrementscupsAddedby one whilecupsAddedis less thancupsOfSugarNeeded.In order to help us visualize the output on each iteration of the loop, add a
console.logwithin thedo...whileblock and log the value ofcupsAddedafter it is incremented.
The break Keyword

practical
1.
Log each element from rapperArray using a for loop.

2> After the for loop, log the string "And if you don't know, now you know." to the console. Note that since there’s a single quote character, ', in our string, we can use double quotes around the string to make sure the character prints.
3> Add a break inside your loop’s block that breaks out of the loop if the element at the current index in the rapperArray is 'Notorious B.I.G.'.
Log the element before breaking out of the loop.
so this is the final code present with us !!!!!
Functions as Data

🟦 Step 1 — Long Function Definition
Explanation
A long-named function is defined.
It checks 2 + 2 = 4 a million times.
If the calculation ever fails, it logs an error.
This function is slow to type because of its long name.
🟦 Step 2 — Create a Shorter Variable with const
constExplanation
We make a shorter name: isTwoPlusTwo
We assign the long function to this shorter variable.
We are not calling the function — just referencing it.
🟦 Step 3 — Invoke the Short-Named Function
Explanation
Here we execute the function using the new short name.
Parentheses
()means: call the function.
🟦 Step 4 — Print the Original Name Using .name
.nameExplanation
Every function in JavaScript has a built-in
.nameproperty..namereturns the original function name, even if assigned to a new variable.Output will be:
Anonymous Functions
functions as Parameters
hard concept present here !!!!!
param(); inside the function present here .............
must understand the below code perfectly again and again !!!! note it down ....
PART 1 — func aur val BAS ARGUMENT HAIN
Tu bilkul sahi soch raha hai:
“I can write func or val as ashu or pratik”
Correct.
Ye sirf variable names hain.
You can write:
best example from the reddit
below i understood the concept mannuall took whole day but worth ........
preety nice concept of high order function ...
do understand the below code perfectly !!!!!!
Introduction to Iterators

Yeh methods array par call hotey hain aur automatically har item ke upar loop chalate hain.
below code analyze karte hai ..........

array methoda revision plus basic logic behind the code
so basically it is going through each and every array present there ...........
array.forEach
and the output will be
below one !!
array.map so basically , numbers.map is going through each and every array elements and made a call backfunction like a function that will go with each and every element in the present array
[ 1, 4, 9, 16, 25 ]
so below method does the work of the filtering the numbers, [ 5, 3.14, 100 ]
array.filter(newfunction) or callbackfunction
output [ 5, 3.14, 100 ]

METHODS(important concept present here!!)
Syntax
The .forEach() Method Iterators
syntax

listen a, b,c is present there then the call backfucntion is that goes with in the each of the elements of the array and then it passes !!
callback function --> <--
some important notes !!!
Another way to pass a callback for .forEach() is to use arrow function syntax.
We can also define a function beforehand to be used as the callback function.
example is here
another high order function
high order function !!!!!
function .(...) => ... JavaScript me function keyword + arrow function kabhi saath nahi aate.
The .forEach() Method
Iterate over the fruits array to log I want to eat a plus the name of each fruit to the console. For example, I want to eat a mango.
You may use any form of callback you prefer.
🔥 Example With forEach() this concept is much needed to understand !!!
✔️ One parameter
✔️ Two parameters
✔️ Three parameters
The .map() Method
Iterator KYA hota hai?
Iterator = ek aisa object jo values ko ek-ek karke deta hai, jab tak sab values khatam na ho jaye.
numbersis an array of numbers.bigNumberswill store the return value of calling.map()onnumbers.numbers.mapwill iterate through each element in thenumbersarray and pass the element into the callback function.return number * 10is the code we wish to execute upon each element in the array. This will save each value from thenumbersarray, multiplied by10, to a new array.
below screenshot just shows the best concept within the function and call backfunction !!!!!!!!!!

question ;->
1>
Add your code under the animals array and before the line console.log(secretMessage.join(''));
Use .map() to create a new array that contains the first character of each string in the animals array. Save the new array to a const variable named secretMessage.

questions
2.
Use .map() to divide all the numbers in bigNumbers by 100. Save the returned values to a variable declared with const called smallNumbers.

the final code is here !!!
The .filter() Method
Another useful iterator method is
.filter()Preview: Docs Creates a new array containing the elements from the original array that pass a test implemented by a provided function.. Like .map()Preview: Docs Loading link description, .filter() returns a new array. However, .filter() returns an array of elements after filtering out certain elements from the original array. The callback function for the .filter() method should return true or false depending on the element that is passed to it. The elements that cause the callback function to return true are added to the new array. Take a look at the following example:
as i readed the above para i can see that this means , the result will be either true or false ........
so basically it does the work of the filtering out something or like filters out the condition as the user wants and dosent affect the original array!!!!!!!
wordsis an array that contains string elements.const shortWords =declares a new variable that will store the returned array from invoking.filter().The callback function is an arrow function that takes a single parameter,
word. Each element in thewordsarray will be passed to this function as an argument.word.length < 6;is the condition in the callback function. Anywordfrom thewordsarray that has fewer than6characters will be added to theshortWordsarray.

practise question
1>
Call the .filter() method on randomNumbers to return values that are less than 250. Save them to a new array called smallNumbers, declared with const.


nd question
Now let’s work with an array of strings. Invoke .filter() on the favoriteWords array to return elements that have more than 7 characters. Save the returned array to a const variable named longFavoriteWords.
just to knoe i had a nice struggle at this making my own ideology ,
most longer version but i did it myself ..........

medium version not making it complicated !!! just using the return keyword nicely !!!!

shorter version


The .findIndex() Method
We sometimes want to find the location of an element in an array. That’s where the .findIndex() method comes in! Calling
.findIndex()Preview: Docs Loading link description on an array will return the index of the first element that evaluates to true in the callback function.
jumbledNumsis an array that contains elements that are numbers.const lessThanTen =declares a new variable that stores the returned index number from invoking.findIndex().The callback function is an arrow function that has a single parameter,
num. Each element in thejumbledNumsarray will be passed to this function as an argument.num < 10;is the condition that elements are checked against..findIndex()will return the index of the first element that evaluates totruefor that condition.
after reading this , actually this means that this method is used to get that particular location of the element present in the array !!!!!!!!!
key concept ;
so basically , this means that i "" jo number pahele less than 10 rahega vohi , call hoga !!!!!!
in this below case , we can see the first number to be less than 10 is 5 and its index number is 3 .
so yeah , its 3 !!
If there isn’t a single element in the array that satisfies the condition in the callback, then .findIndex() will return -1.
practise set
Invoke .findIndex() on the animals array to find the index of the element that has the value 'elephant' and save the returned value to a const variable named foundAnimal.
code no.1
code no.2
2.
Let’s see if we can find the index of the first animal that starts with the letter 's'.
Call .findIndex() on the animals array and return the index of the first element that starts with 's'. Assign the returned value to a const variable named startsWithS.
important concept , findIndex() , anything[] , charAt()
below i used nice[0] this , this means that like it goes from each letter , i am saying each letter , like each word mai first letter check karega
nice[0] = h t l s m
nice[1] = i i i e e o1
so basically , if i put something on the the second letter , like suppose there is hsppo , so here second letter is s in the hippo
if i type " return nice[1] " so basically it will be doing that s , i i e e o
so the ans will be , 0 yeah 0 , like index zero
if nice [0] then it will go for first letter present in the array that starts with the letter "s"
but the condition is this will lookout for just first letter triggered here , like that seal word , not the next one and printing the ans as 3 !!
so thats all the cocept
and yeah same as we can also use that nice.charAt(0) exactly working same as that !!
nice[0] and last if its not present there it will be -1 .......
charAt(0)
in below code i wrote a hsppo for a purpose , so that if i do nice.charAt(1)
so the ans will be index 0

startsWith little example !!!!
here , array.startsWith method use kiya hai
here i am using the lowercase and also startsWith combination !!
The .reduce() Method
so basically , accumulator and current value are the main functions of this reduce method ,
so acc ad current will be like this for stage one ,
1> (1,2) which return like in addition as per the call backfunc!!
2> (3,4) = 7
3> (7,10) jiks aaddition 17 and thats final !!!!!
so bascially , array.reduce(accumulator , currentvalue) ⇒ important concept here !!!!
Here are the values of accumulator and currentValue as we iterate through the numbers array:
Iteration
accumulator
currentValue
return value
First
1
2
3
Second
3
4
7
Third
7
10
17
second case
so yaha pe 100 as a sceond arguement diya hua hai for .reduce so that ,
Iteration #
accumulator
currentValue
return value
First
100
1
101
Second
101
2
103
Third
103
4
107
Fourth
107
10
117
second question
Provide .reduce with an argument of a callback function. The callback function should have two parameters, accumulator and currentValue, in that order. Use either a function expression or an arrow function.
third question
To check the value being used as we iterate through the array, add 2 logging statements to the body of the callback function:
Then, add a return statement that adds accumulator to currentValue.

4.
Log the value of
newSumto the console to see the return value of calling.reduce()onnewNumbers.Checkpoint 5 Enabled
5.
While we have this code set up, let’s also check what happens if you add a second argument to
.reduce(). The second argument acts as an initial value for theaccumulator.Add a second argument of
10to.reduce().
noticable thing or the best concept here is that !! here is that , to add the thing , 10 , we hvae to use that ,10 to add second arguement !!

Iterator Documentation --> array.some method
iterator methods !!!! --> mdn docs reference
very important , understanding the below code will be best !!! , i have to just try myself a lot at least 1 hrs!!
--
--
--
--
so BIND METHOD is present here , like that call backfunction !!
In the code editor, there is an array called words. We want to create a new array of interesting words. The first thing we want to do is check if there are words that are fewer than 6 characters long. There is something missing in the words.some() method call. Fix this method so that true is printed to the console.
For more information browse MDN’s documentation on .some() .
must read all the methods !!!!

uunderstand the below code very nicely like there is few methods concepts present there !!!!!
array.every method

Choose the Right Iterator
task to read it more and more times and analyse it more and more !!!
jsut on js compiler put this in front on the js compiler , just source code review please!!

for map !!!

for every !!!
Array.prototype.every()
array.every() and array.includes() mdn docs !!
!!!!!!!!!!! Using the third argument of callbackFn !!!!!!!!!!
1> so below code ka matlab hai ki positive numbers lega , num >0
2> so here now , num = 4, 16 , idx=0,1 , [4,16] aur idx === 0 toh true !! , so array is of [4,16] that is , index 0 and index 1 , so there will be two indexs only !!!!!!
num= 4, 16 --> two elements
and idx is only 2 here , i.e 0,1
3> now round 2 , jab
num = 16 , idx = 1 , array=[4,16]
idx is equal to 1 not 0 , because in round 1 , idx was equal to 0 and we got it true !!
now in second round idx = 1 , and aage jaake voh , idx-1 will go in the idx-1 condition so that it will be zero again and the ans will remain true !!
16> array[1-1] i.e 16> array[0] i.e 16>4 i.e because array[index0] is 4 and index 1 is 16
so its true again like 16 is greater than 4 , so at the end its true in the both cases !!!!
above one is best best explanation , took 2 hours to understand , so basically as a source code review i just putted this code infront of my took notebook and understanding the concept it really took very long just to understand this concept !!! , so basically , also a online js compiler to test each line !!
🔹 JavaScript me iterator ka simple example
Jab tum likhte ho:
Yahan kya ho raha hai?
JS khud ek iterator banata hai
iterator bolta hai:
“lo pehla item”
“lo doosra item”
“lo teesra item”
“bas khatam”
Tumhe kuch bhi manually nahi karna padta
Creating Object Literals
A JavaScript object is a non-primitive data type that can assume the properties and behaviors required for a given programming need
Spaces and line breaks are not important. An object definition can span multiple lines:
objects
The spaceship we have so far looks good (see the code block in the narrative text), but unfortunately, it is not very fast at hyperspace travel due to having an inferior fuel source. Make a new spaceship object named fasterShip with the same color as spaceship but with a Fuel Type equal to 'Turbo Fuel'
important code here

Accessing Properties
We’ve used dot notation to access the properties and
methodsPreview: Docs Methods are object properties that contain functions. of built-in objectsPreview: Docs A data type for organizing a set of custom properties and behaviors. and data instances:
seeing down image for my referance !!
spaceship.favoriteIcecream; // Returns undefined
Q1> 1.
Let’s use the dot operator to access the value of numCrew from the spaceship object in the code editor. Create a variable crewCount and assign the spaceship object’s numCrew property to it.
2.
Again, using the dot operator, create a variable planetArray and assign the spaceship object’s flightPath property to it.
Bracket Notation
We’ve used bracket notation when indexing an array:
1.
Let’s use bracket notation to access the value of 'Active Mission' from the spaceship object in the code editor. Create a variable isActive and assign the spaceship object’s 'Active Mission' property to it.
spaceship['object name ']
Using bracket notation and the propName variable provided, console.log() the value of the 'Active Mission' property.
🔹 Ye kaam kaise kar raha hai?
Step-by-step:
1️⃣ propName ki value hai
2️⃣ Bracket notation me variable pass kiya:
➡️ JavaScript internally isko aise padhta hai:
3️⃣ Value milti hai:
4️⃣ console.log() usko print kar deta hai
IMPORTANT CONCEPT OF CALLLING BRACKETS
2> Using bracket notation and the propName variable provided, console.log() the value of the 'Active Mission' property.
so basically the catch was that , propName=active mission kiya hai
so that if agar mai consolemai console.log(spaceship[propName]) karu toh js will read it as
spaceship['Active Mission']
Property Assignment
It’s important to know that although we can’t reassign an object declared with const, we can still mutate it, meaning we can add new properties and change the properties that are there.
We can delete a property from an object with the delete operator.
q1>
Reassign the color property of the spaceship object to have a value of 'glorious gold'
important
q2> Without changing lines 1 - 6, add a numEngines property with a numeric value between 1 and 10 to the spaceship object.
spaceship['numEngines'] = 6; --> we can also make assign new object inside already present object , instead of dot operator !
using the dot operator !! , spaceship.color='glorious gold'
i did this using bracket this time !! spaceship['numEngines'] = 6;


q3> 3.
Use the delete operator to remove the 'Secret Mission' property from the spaceship object.
so BASICALLY BRACKET OPERATOR IS SO EASY TO UNDERSTAND AND DO IT !!,
HERE I JUST USED THAT delete spaceship['Secret Mission']
i was using my brain like this like using spaceship.Secret Mission or like Secret_Mission
but all were wrong !!



as i have to be a source code review i have to keep my code in editor and understand the code by reading it more and more times till i understand it !! if error comes i have to analyse myself first !!
Methods
method defination Method → object ke andar function , Callback → function jo argument ke roop me kisi aur function ko diya jata hai
When the data stored on an object is a function, we call that a methodPreview: Docs Methods are object properties that contain functions..
with function
With the new method syntax introduced in ES6, we can omit the colon and the function keyword.
alienShip
call back functions difference , jus tunderstand it !!
so basically we are learning to create a new function in the object !! (object)
1> Below the retreatMessage variable in the code editor, create an alienShip object. It should contain a method .retreat(), which should console.log() the retreatMessage.
2.
Add another method to the alienShip object literal. This method, .takeOff(), should console.log() the string 'Spim... Borp... Glix... Blastoff!'
3.
Invoke the two methods: first .retreat(), then .takeOff().
Nested Objects
nest objects ka same meaning rehta hai jaise nested arrays tha ,
so nested means ek ke andar ek chije defined !!
just like this happened !!! please !!!
1> Create a variable capFave and assign the favorite food of captain (the element in the “0th” index of 'favorite foods' array) to it. Make sure to use bracket and dot notation to get the value of the food through nested access (don’t just copy the value into the variable!)
2.
Right now, the passengers property has a value of null. Instead, assign as its value an array of objects. These objects should represent the spaceship object’s passengers as individual objects. Make at least one passenger object in the array that has at least one key-value pair.
see this section concept might be easy but we have to just keep focus on source code review !!
just keeping in code editor and trying to build logic by reading the code again and again !!
Pass By Reference (important one for source code review !!)
below code is too important to see and review by just analysing the code !!
part code !
this code is basically based on the function and then inside the object is introduced there !!
so basically there is a arrow function ,
obj ⇒ {} which is function (obj) {}
so instead od thsi we have to do that !! , obj parameter introduce kiya toh uske andar ek object mai store karr rahe hai !!!!
function ke andar function hi hai its like we are creating our own function !!

so basically here the happening word is like spaceship is on going to the obj!!

1>
Write a function greenEnergy() that has an object as a parameter and sets that object’s 'Fuel Type' property to 'avocado oil'.
2.
Write a function remotelyDisable() that has an object as a parameter and sets (or reassigns) that object’s disabled property to true.
3>.
Call your two functions with the spaceship object in the code editor, then console.log() the spaceship object to confirm those properties were changed/added.


Looping Through Objects important one !!
LoopsPreview: Docs A loop is a programming tool that is used to repeat a set of instructions. are programming tools that repeat a block of code until a condition is met. We learned how to iterate through arraysPreview: Docs Arrays are lists of ordered, stored data that can be of any data type. using their numerical indexing, but the key-value pairs in objectsPreview: Docs A data type for organizing a set of custom properties and behaviors. aren’t ordered! JavaScript has given us an alternative solution for iterating through objects with for…in syntax.
analyse the code below and trry to understand the code perfectly !! as this is just a learning phase but as i have to be a best source code reviewer !! i have to do it !
reviewing the below code was hard but i understood it ! by makeing changes to the code and writing !
below understanding is very important !! very very important as this is for in concept !!!
as i can see this //code
so understanding it carefully i get that , its creating the new variable
let crewMember --> creating a new variable inside for loop
then using " in " inside the for loop ,
crewMember in spaceship.crew --> which means a nested object reference , like spaceship and then crew !! yeah there are more inside that like captain liek that !!
so as i can see the above string means that as we have defined a variable crewMember in spaceship.crew so basically it means it will print all the crews !! as we can see in the below screenshot !!

so crew = captain chief officer medic translator etc !!
and what we told about is for there names as i can see below !! , crew roles and there names in particular given format !!
for (let crewMember in spaceship.crew) { console.log(${crewMember}:${spaceship.crew.name}) }
if i used above for loop i was getting something as undefined !! as we can see below !!

so basically , we have to add that crewMember that is spaceship.crew i,e equal to captain , translator and more like all the crew name , so here we have to present all the crew roles and there names , and for names we have to include the spaceship.crew[crewMember].name !!
spaceship.crew[crewMember].name
and finally thats the yep moment for me !!

1.
Using for...in, iterate through the spaceship.crew object in the code editor and console.log() a list of crew roles and names in the following format: '[crew member's role]: [crew member's name]', e.g.,'chief officer: Dan'.
2>
2.
Using for...in, iterate through the spaceship.crew object in the code editor and console.log() a list of crew names and degrees in the following format: '[crew member's name]: [crew member's degree]', e.g.,'Lily: Computer Engineering'.
this was pretty again confusable i tried different methods there !!

{spaceship.crew[crewMember].name
so the above string means that spaceship then crew and then go in spaceship.crew(that is crewMember!!).name so it prints the name of all the crew members , if i want the particular name like lily : than degree , then i have to do spaceship.crew.captain.name
so basically as we can see that , if i add particualr crew member and there name its the output !! or else if i want to do more better , like printing each one crew member ! that i have to use
spaceship.crew[crewMember].name --> this will print all the crew member names and there degrees !!

Array Destructuring (funny and easy and important too )
Array destructuring extracts values from arrays in order, assigning them to variables in a single statement:
The output for this is:
so basically just do that , const nice =[ashu , nicey] then in second line we can do is [ first, second, third] = nice;
its pretty nice a lot nice funny way !! and easy !!

Object Destructuring
so here , its same as the array destruction !!
Variables can also be renamed or assigned default values:
as this is also nice like , we can make a new variable like color = white and editing the model to the carmodel !!
Nested Destructuring
The output of this code is:
codebyte example !!
above example is best and best example !! just read and analyse the code , i can see that , firstHobby which automatically considered as the first as reading !!
below code is experiment !!
so here , we just tried to have that hobbies a new reassign , so that i can have that new variable present there !
const { hobbies } = user; <=>const hobbies = user.hobbies;
hobbies === user.hobbies // true
hobbies.push('gaming');
in above we can push the gaming into the arrya dirctly !!
if i do like this const { hobbies: heythere } = user; then it wil be sucessfully changed !!
const { hobbies: heythere } = user; console.log(heythere); // ['reading', 'cycling', 'coding'] as this is renamed perfectly !!!
The this Keyword
below code is for totally error !
below is corrected code of above !!!!!!!!
1.
Let’s create a new object to practice using this.
In main.js, there is an object called robot. Add a property called model and assign to it a value of '1E78V2'. Add another property, energyLevel, and assign to it a value of 100.
2.
With the robot object, add a method named provideInfo() that returns the following string using interpolation:
Replace <MODEL> and <ENERGYLEVEL> with the calling object’s model and energyLevel properties, respectively. Remember, to get access to the calling object’s properties inside a method, you have to use the this keyword!

i was getting continiously errors here !!!

so basically issue was , i just have to return the statement instead of console.log!!

3> Now, check that .provideInfo() has access to the internal properties of robot. Log the result of calling the .provideInfo() method on robot to the console.

Arrow Functions and this
practise question !! --> for understanding the code !!
1.
Currently, the
.checkEnergy()method is not producing the correct output because it is using arrow function syntax (it printsundefinedinstead of the correctenergyLevelvalue).Refactor, or change, the method to use a function expression. You can write the function using either longhand or shorthand format.
After refactoring the method, notice that
.checkEnergy()has access to the other internal properties of therobotobject.
below is the shorthand method like just checkEnergy(){}
Option 2: Function expression (also correct)

Privacy
so here , energyLevel is too 100 and i can see that this.energyLevel is +- 30 i.e this is the compact way to update a variable by adding a value to its existing value !!!


Getters
Getters are methodsPreview: Docs Methods are object properties that contain functions. that get and return the internal properties of an object. But they can do more than just retrieve the value of a property! Let’s take a look at a getter method:
analyse the above code in online js compiler !! try to under stand
analysing the above code to make sure i understand it !!
2.
Inside the getter method, add an if statement to check if this._energyLevel is a number using the typeof operator. If that condition is truthy, return 'My current energy level is <ENERGYLEVEL>'. Replace <ENERGYLEVEL> with the value of this._energyLevel.
Make sure you return the string instead of logging it to the console.

3> If this._energyLevel isn’t a number, it could be that the _energyLevel property was altered. Let’s add a default return statement for when such a scenario arises.
Add an else statement that returns 'System malfunction: cannot retrieve energy level'.
4> Log the result of calling the getter method energyLevel on robot to the console.
Notice that the method will return a formatted response rather than just accessing a property!
dont have to put () bracktes after that energyLevel !!! in getter function !!

Setters
setter methods, which reassign values of existing properties within an object. Let’s see an example of a setter method:
below code is hard to understand please do keep calm and understand
so basically there is a object and then there is something called set function which basically sets a function to a specific or particular value !! , then setting robot.numOfSensors = num which is equal to 100;
factory functions
https://www.codecademy.com/courses/introduction-to-javascript/lessons/advanced-objects/exercises/factory-functions ---> very helpfull and like easy to understand and in big code this will help a lot !!
const monsterFactory =(name , age, energySource,catchPhrase
its just a beautifull code ,just keep understanding !!, variable and inside there is a function and then there is parameters present inside like name age energySource catchPhrase introduced these variables !! , then returned all the parameters in a particular object !!
here in this code i have added , so basically here the issue is like catchphrase is present in the function scare but in that place there is another one present like BOO and if i call like ghost.scare so it will call "BOO"
const monsterFactory = (name, age, energySource, catchPhrase) => { return { name: name, age: age, energySource: energySource, scare() { console.log(catchPhrase); } } };
so the above code is just a private my own function for the purpose of the particular object selection easily later !!
then i added below code !!
const ghost = monsterFactory('Ghouly', 251, 'ectoplasm', 'BOO!'); ghost.scare(); // 'BOO!'
so thsi makes the perfect sense like there is a
1.
Instead of making individual robots like we’ve been doing, let’s make a factory function to make robots as we please!
Create a factory function named robotFactory that has two parameters, model and mobile (in that order). Make the function return an object. In the object, add a key of model with the value of the model parameter. Add another property that has a key of mobile with a value of the mobile parameter.
Then add a method named beep that takes no parameters and logs 'Beep Boop' to the console.
here i understood the code properly and then tried to analyse the code !!
2.
Use your factory function by declaring a const variable named tinCan. Assign to tinCan the value of calling robotFactory() with 'P-500' as the first argument and true as the second.
3.
Let’s now check what tinCan can do! Call .beep() on tinCan.
You should see 'Beep Boop' printed to the console, which means the factory function produced a robot object! Play around with tinCan to check the other properties!

Property Value Shorthand
1.
Use the property value shorthand to refactor the factory function in main.js.
instead of using model:model i used model , mobile , then something !!

Destructured Assignment
const { functionality } = robot;
const functionality = robot.functionality;
Since functionality is referencing robot.functionality we can call the methods available to robot.functionality simply through functionality.
Take advantage of this shortcut and call the .beep() method on functionality.
Built-in Object Methods
Object.keys()
1.
In main.js, there is an object, robot. We’d like to grab the property names, otherwise known as keys, and save them in an array assigned to robotKeys. However, there’s something missing in the method call.
Find out what we have to include by reading MDN’s Object.keys() documentation.
2.
Object.entries() will also return an array, but the array will contain more arrays that have both the key and value of the properties in an object.
Declare a const variable named robotEntries and assign to it the entries of robot by calling Object.entries().
To learn more about Object.entries(), read the documentation at MDN.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
this was about object.entries()
3.
Now, what if we want another object that has the properties of robot but with a few additional properties? Object.assign() sounds like a great method to use, but like the previous examples, we should check Object.assign() documentation at MDN.
Declare a const variable named newRobot. newRobot will be a new object that has all the properties of robot and the properties in the following object:

object.create , object.entries , object.keys
introduction to classes
Constructor
1.
Create an empty class named Surgeon.
2.
Inside the Surgeon class, create a constructor method that accepts two parameters, name and department, in that order.
3.
Inside the Surgeon constructor, create name and department properties and set them equal to your input parameters.
Instance
We create a new variable named
halleythat will store an instance of ourDogclass.We use the
newkeyword to generate a new instance of theDogclass. Thenewkeyword calls the constructor, executes the code inside of it, and then returns the new instance.We pass the
'Halley'string to theDogconstructor, which setsPreview: Docs Loading link description thenameproperty to'Halley'.Finally, we log the value saved to the
namekey in ourhalleyobject, which logs'Halley'to the console.
1.
Create an instance of the Surgeon class — set the name to 'Francisco Romero' and department to 'Cardiovascular'.
Save the instance to a variable called surgeonRomero.
Checkpoint 2 Enabled
2.
Create another instance of the Surgeon class — set the name to 'Ruth Jackson' and department to 'Orthopedics'.
Save the instance to a variable called surgeonJackson.
Methods
1.
In the Surgeon constructor, prepend the name and department properties with an underscore (_) to indicate they should not be accessed directly.
2.
Inside the constructor, add a property named _remainingVacationDays and set it equal to 20.
3.
Under the constructor, create a getter called name that returns the value saved to _name.
4.
Under the .name() getter, create a getter called department that returns the value saved to _department.
5.
Under the .department() getter, create a getter called remainingVacationDays that returns the value saved to _remainingVacationDays.
6.
Under the .remainingVacationDays() getter, create a method called takeVacationDays that accepts one argument named daysOff.
Inside the method, subtract daysOff from the number saved to _remainingVacationDays. Set _remainingVacationDays to the result.
Method Calls
1.
At the bottom of main.js, use console.log() and the .name getter to print the value saved to the _name property of the surgeonRomero object.
2.
Call .takeVacationDays() on surgeonRomero, with an input of 3.
3.
After the call to .takeVacationDays(), use console.log() and the .remainingVacationDays getter to print the value saved to the _remainingVacationDays property of the surgeonRomero instance.
understand the above code nicely !!! i took time and then i got to understand this nicely !!!
understand the code nice so nicely , our goal is like a massive source code hacker !!!analyser !!
Inheritance I
Inheritance II
1.
In the next few exercises, you will create two subclasses (
DoctorandNurse) from a parent class namedHospitalEmployee. Below, we have listed the properties and methods you will find in theDoctorandNurseclasses.Doctor
Properties:
_name,_remainingVacationDays,_insuranceMethods:
.takeVacationDays()
Nurse
Properties:
_name,_remainingVacationDays,_certificationsMethods:
.takeVacationDays(),.addCertification()
In
main.js, create a parent class namedHospitalEmployeebased on the shared properties and methods. Add a constructor method withnameas a parameter.Checkpoint 2 Passed
2.
Within the constructor, set the instance’s
_nametonameand_remainingVacationDaysto20.
3.
Under the constructor, create getters for your
_nameand_remainingVacationDaysproperties, callednameandremainingVacationDaysrespectively.Within each getter, return the respective property’s value.
Checkpoint 4 Passed
4.
Under the getters, add a method called
takeVacationDays.This method should accept one argument, called
daysOff.Inside the method, subtract
daysOfffrom_remainingVacationDays. Save the result to_remainingVacationDays.
Inheritance III
1.
In this exercise, you will begin to create the Nurse class as a child of the HospitalEmployee class. The Nurse class has the following properties and methods:
Nurse
Properties:
_name,_remainingVacationDays,_certificationsMethods:
.takeVacationDays(),.addCertification()
Under HospitalEmployee, create an empty class named Nurse that extends HospitalEmployee.
we have to add following !!! under means new !!
2.
Inside the Nurse class, create a constructor that accepts two parameters. Use the list of properties from the previous step to name these arguments. Order the parameters in the same way they are listed.
In the Nurse constructor, call the parent’s constructor method and pass the appropriate value(s).
Use the super() method to call the parent’s constructor(). Since the HospitalEmployee class also expects a name, pass this argument into super().
4.
Inside the Nurse constructor, under the call to super(), set _certifications based on the corresponding argument.
Checkpoint 5 Passed
5.
Under the
Nurseclass, create a new instance ofNurseand save it to a constant variable namednurseOlynyk. Pass in the following values for each property:name:'Olynyk'certifications:['Trauma', 'Pediatrics']
Inheritance IV and extend method
Inheritance V
Parent class = Father 👨🦱
Child class = Son 👦
super() parent class ke constructor ko call karta hai.
Real-life analogy 🧠
Soch:
Parent class = Father 👨🦱
Child class = Son 👦
Father ke paas kuch common cheezein hoti hain (name, salary, house). Son bhi wahi cheezein inherit karta hai.
👉 Lekin jab son ka constructor chalta hai, usko pehle father ka constructor chalana padta hai.
Wahi kaam super() karta hai.
Example (step by step)
Parent class
Child class (Doctor)
getter ka kaam value RETURN karna hota ha
1.
Use the properties and methods below to help you complete the tasks that follow.
Nurse
Properties:
_name,_remainingVacationDays,_certificationsMethods:
.takeVacationDays(),.addCertification()
Under the Nurse constructor, add a .certifications() getter that returns the value saved to the Nurse instance’s _certifications property.
2.
Add a method called
addCertificationunder the.certifications()getter.This method should accept one input,
newCertification. Inside the method, use the push() method to add thenewCertificationvalue to the nurse’s_certificationsarray.Checkpoint 3 Passed
3.
At the bottom of
main.js, call.addCertification()onnurseOlynykwith an argument of'Genetics'.Checkpoint 4 Passed
4.
Using the
.certifications()getter, log the value saved to the_certificationsproperty ofnurseOlynykto the console.
Static Methods
1.
Within the HospitalEmployee class, create a static method called generatePassword. When it’s called, this method should return a random integer between 0 and 10000.
The following code will compute a random integer between 0 and 10000:
Introduction to JavaScript Runtime Environments
What is a Runtime Environment?
A runtime environment is where your program will be executed. It determines what global objects your program can access and it can also impact how it runs. This article covers the two JavaScript runtime environments:
the Node runtime environment
file:///C:/Users/OMEN/OneDrive/Desktop/jav/index.html
i saw this vedio and started and made this
i added a folder jav and in that i created a fiel named index.html and in that above code is present and i learned to make a alert () and also having a <img src="whatever image link"
The window.alert() method is built into this environment and any program executed in a browser has access to this method. In fact, the window object provides access to a huge amount of data and functionality relating to the open browser window beyond just .alert().
Try replacing window.alert() with window.prompt() or window.confirm()

in above ss we can see that there is that windwos,alert present as the js file isnt present there !!!

Implementing CommonJS Modules
Consider the following diagram of an imaginary program written in a file my_app.js:
Instead of having the entire program written within my_app.js, its components are broken up into separate modules that each handle a particular task. For example, the database_logic.js module may contain code for storing and retrieving data from a database. Meanwhile, the date_formatting.js module may contain functions designed to easily convert date values from one format to another (a common headache among programmers!).
the above learning or advice is best !!!
Think of a few ideas before expanding to reveal the reasons:
By isolating code into separate files, called modules, you can:
find, fix, and debug code more easily
reuse and recycle defined logic in different parts of your application
keep information private and protected from other modules
prevent pollution of the global namespace and potential naming collisions, by cautiously selecting variables and behavior we load into a program.
require() (do give a read this )
require()
require()The require() function accepts a string as an argument. That string provides the file path to the module you would like to import, generally using the relative path based on the file where require() is being called.
Let’s update water-limits.js so that it uses require() to import the .celsiusToFahrenheit() method from the module.exports object within converters.js:
In this case, ./ is a relative path indicating that converters.js is stored in the same directory as water-limits.js. When you use require(), the entire module.exports object is returned and stored in the variable converters. This means that both the .celsiusToFahrenheit() and .fahrenheitToCelsius() methods can be used in this program!
below is the coding challenge !!!

so from below code i understood and tried to get myself understood everything nicely !!!


after looking into the code and had a revise at the concept i got the backend is nodejs on the codecadmey!!
1️⃣ ES6 Modules (Modern JS, React, Browser)
✔️ React ✔️ Frontend ✔️ New projects
2️⃣ CommonJS (Node.js, Codecademy backend)
Complete the program in app.js:
First, import the
shape-area.jsmodule using therequire()function (shape-area.jsis in the same directory asapp.js). Choose one of the two options below for storing the returnedmodule.exportsobject:A) Store the entire
module.exportsobject in the variableareaFunctions.B) Use object destructuring to extract the
.circleArea()and.squareArea()methods into their own variables,circleAreaandsquareArea.
Next, call the
circleArea()function with the provided variableradiusas an input. Assign the returned value to the variableareaOfCircle.Then, call the
squareArea()function with the provided variablesideLengthas an input. Assign the returned value to the variableareaOfSquare.
You may print the values of areaOfCircle and areaOfSquare to the console to see your code work!
Code
123456789101112131415Previous Line 7 had errorOutput:
RunLoading CompleteAnswer Check Complete👏You got it!
Review
In this article, you have learned the following:
the benefits of implementing modular programs
how to use the CommonJS
module.exportsobject to export code from a file, meaning its functions and/or data can be used by other files/moduleshow to use the CommonJS
require()function to import functions and/or data from another modulehow to use object destructuring to only import the desired components of a module.
Congratulations on reaching this milestone! With a little more practice, you will soon be able to handle CommonJS modules with ease. For a more comprehensive resource on CommonJS modules, check out the Node.js modules documentation.
BackNext...data: any[], , , hint
DOM AND MAKING WEBSITE WITH HIDDEN BUTTON ELEMENT !!
To create this website, you could create two files, secret-messages.html and secret-messages.js, and store them together in a folder called secret-messages:
Let’s take a look at the HTML file first:
secret-messages.htmlrenders a<button>element and a hidden (fromdisplay: none) paragraph element.It then loads the script
secret-messages.jsusing the relative file path,"./secret-messages.js". The./before the file name is how you indicate that the file being referenced (secret-messages.js) is in the same folder as the file referencing it (secret-messages.html).
Speaking of which, let’s take a look at the JavaScript file:
In
secret-messages.js, DOM (Document Object Model) objects are created to reference the button and paragraph elements using the DOM API, viadocument. These objects are stored inbuttonElementandpElement, respectively.The function
toggleHiddenElementis declared. It can accept a DOM element as an input calleddomElementand will either show or hide that element depending on its currentstyle.displayvalue.An event listener is added to
buttonElementto listen for'click'events and respond by callingtoggleHiddenElement()withpElementas the argument.


so basically there is document.getElementById -=? so this means that there is a "id" present in the html and we are getting that particular " id " document.getElementById('secret-button')
style="display: none" → page load hote hi invisible
document = poori HTML page
getElementById() = “bhai mujhe yeh id wala element de”
buttonElement → button ka JS object
pElement → paragraph ka JS object
5️⃣ 🔥 sabse confusing line (main explain karta hoon)
Break karte hain 👇
domElement
domElement➡️ actual HTML element (jaise <p>)
.style
.style➡️ inline CSS access
.display
.display➡️ CSS ka display property
🧠 Matlab:
=
👉 current display value (none ya block)
Condition ka real-life logic
👉 Agar element abhi hidden hai
THEN 👇
block= dikh ja // important one !!Paragraph screen pe aa jayega
7️⃣ 🔁 TOGGLE ka matlab
none ❌
block ✅
block ✅
none ❌
Isliye function ka naam: 👉 toggleHiddenElement
ddEventListener
Matlab:
“Bhai, jab yeh button click ho, tab yeh kaam karna”
🔹 'click'
'click'Event ka naam (mouse click)
🔹 () => { ... }
() => { ... }YES bhai 💯 👉 yeh callback function hai
🧠 Matlab:
“Abhi mat chalao jab click hoga tab chalaana”

Reading below to create my own live server for website !!!

In this module you will find two functions which have been declared for you, changeText() and changeToFunkyColor() but currently, they aren’t being exported.
Using the named export syntax, export changeText() and changeToFunkyColor() from this module.
Code
Answer Choices
👏You got it!
so below the fucntions js !!! , in which i stated the changetext and change to fdunky color and exported the functions so that i can do work on the another file with this functions !!!


ES6 Modules Challenge #3
Multiple choice
Questions
The <script> element below loads a JavaScript file, which makes use of ES6 import/export syntax. Which of the following changes must be made in order to properly load this module and avoid errors in the browser console?

so basically there is the code below and we have an example like there are two functions present here and both are almost same at all i.e greet and another one greet
so basically if we try to import this in the main.js
we will get encounter by this !!!
The code above will throw an error on line 2 due to the fact that the identifier greet has already been defined on line 1. Thankfully, ES6 includes syntax for renaming imported resources using the as keyword. Here’s an example:
Let’s apply this syntax within main.js to avoid a naming collision:
/* main.js */ import { greet as greetEspanol } from 'greeterEspanol.js';
import { greet as greetFrancais } from 'greeterFrancais.js';
greetEspanol(); // Prints: hola greetFrancais(); // Prints: bonjour
so basically we have to do is like we have to change that greet as greetEspanol and another function greet as greetFrancais from file name whatever
following is the best example i tested on the vs code !!
my main.js

if its a module i have to present it in the type ( its the attribute !!) i.e type attribute and present it like
in body section of the html !!, so that we can understand that !! , main.js

so now i have two files
another file is like this circlearea.js
above is my area-calculator.js
then i created the area.html

The syntax for exporting a default object looks like this:
below is the best link for understanding the concept of website !!
You may also see this shorthand syntax, where the value following export default is the default value to be exported:
Importing default values.
The syntax for importing default exports is written like this:

Let’s return to the prior example. The dom-functions.js module from before could be rewritten to use a default export like so:
What is a Promise? ( please do read the following all by speaking it all with mouth so that it does fit in our mind !! )
Pending: The initial state — the operation has not completed yet.
Fulfilled: The operation has completed successfully, and the promise now has a resolved value. For example, a request’s promise might resolve with a JSONPreview: Docs Loading link description object as its value.
Rejected: The operation has failed, and the promise has a reason for the failure. This reason is usually an
Errorof some kind.
We refer to a promise as settled if it is no longer pending — it is either fulfilled or rejected. Let’s think of a dishwasher as having the states of a promise:
Pending: The dishwasher is running but has not completed the washing cycle.
Fulfilled: The dishwasher has completed the washing cycle and is full of clean dishes.
Rejected: The dishwasher encountered a problem (it didn’t receive soap!) and returns unclean dishes
If our dishwashing promise is fulfilled, we’ll be able to perform related tasks, such as unloading the clean dishes from the dishwasher. If it’s rejected, we can take alternate steps, such as running it again with soap or washing the dishes by hand.
All promises eventually settle, enabling us to write logic for what to do if the promise is fulfilled or if it is rejected.

summary of the concept
Related learning
Free courseLearn JavaScript: Asynchronous ProgrammingCreate efficient asynchronous programs using Promises and the async/await syntax.
Beginner Friendly.Beginner Friendly3 hours3 hours
In progress...Learn Intermediate JavaScriptTake your JavaScript knowledge to the next level by learning how to use advanced functions to create more efficient programs.
Intermediate.Intermediate11 hours11 hours
States of a JavaScript Promise
A JavaScript Promise object can be in one of three states: pending, resolved, or rejected.
While the value is not yet available, the Promise stays in the pending state. Afterwards, it transitions to one of the two states: resolved or rejected.
A resolved promise stands for a successful completion. Due to errors, the promise may go in the rejected state.
In the example code block, if the Promise is on resolved state, the first parameter holding a callback function of the .then() method will print the resolved value. Otherwise, an alert will be shown.

.then() → success handle karta hai
so baiscally this is the perfect exampole by the chatgpt and this is the sucess handle so that when we are fetching something we will be getting some error handlings !!! , r


do read the following code nicely a lot nicely !!!
Constructing a Promise Object
the following code is the best way to understand !!!
so now the following code is corrected !!

following is the best practise !!!
1.
You’ll be writing your code in the code editor, but we won’t be running it until the final step. To check your code for a step, you can press the “Check Work” button.
We’re going to create a promise representing ordering sunglasses from an online store. First, create the function, myExecutor(). Later on, you’ll pass this function into the Promise constructor.
myExecutor() should:
Have two parameters:
resolveandrejectCheck if the
sunglassesproperty on theinventoryobject has a value greater than zeroIf it does,
myExecutor()should invokeresolve()with the string'Sunglasses order processed.'If it does not,
myExecutor()should invokereject()with the string'That item is sold out.'
When you’re ready, press the “Check Work” button.
2.
Create a function, orderSunglasses(), that takes no parameters. It should return a new promise constructed by passing your myExecutor function into the Promise constructor.
3.
Create a variable orderPromise assigned to the returned value of your orderSunglasses() function.
const orderPromise = orderSunglasses();
4.
At the bottom of app.js, log orderPromise to the console.

Constructing a Promise Object
the above code is the best code for understanding the core concept of the "".then"" and ""catch""
JavaScript .finally()
Syntax
JavaScript .race()
Syntax
JavaScript .reject()
Syntax
Example
A new Promise, myPromise, is rejected with an Error message by default. Lastly, the error message, err.message, is logged to the console through the catch-block.
JavaScript .resolve()
Syntax
The value can be most data types, including:
numbers
strings
objects (even other
Promiseobjects)
Example #1
With non-Promise values:
Example #2
With Promise values:
JavaScript .all()
JavaScript Promise.all() Syntax
Promise.all() SyntaxParameters:
iterableObject: An iterable (such as an array) of promises or values.
Return value:
Returns a new Promise object that can be accessed as an array of resolved values of fulfilled promises.
Example 2: Using Promise.all() with Asynchronous Tasks
Promise.all() with Asynchronous Tasksthe following is the best asynchronous function code writtern here!!! do please read it !!!
function myPromise() { return new Promise((resolve) => { resolve('Successful promise!'); }); } function mySecondPromise() { return new Promise((resolve) => { resolve('Second successful promise!'); }); }
async function someAsyncAwaitFunction() { try { const promise = await myPromise(); const promiseTwo = await mySecondPromise(); console.log(promise); console.log(promiseTwo); } catch (error) { console.log(Error from async function: ${error}); } } someAsyncAwaitFunction();
JavaScript .any()
Syntax
Example 1
If the iterable object is empty or all the Promises within are rejected, an AggregateError is thrown.
Example #2
Below is an array of promises contains 3 Promise objects.
2 of them,
promiseAandpromiseB, will be rejected.The other one,
promiseC, will fulfill and resolve with a message.
Using Promise.all, the value of the first successfully resolved Promise will be logged to the console.
The Node setTimeout() Function
so the aboce code will be printing the result after 3 sec !!
Example 1: Basic Timeout
The output produced by this after two seconds will be:
Example 2: Cancelable Countdown Timer
below code must be seen and read once to understand the code nicely reading line by line is the best !!
The output produced by this code is:
If cancelled after 2.5 seconds, the output of this code will be:

Example 3: Debouncing User Input
1.
Create a function, usingSTO(), that takes no parameters. Inside the function body, it should print a string to the console. This can be any string you want (as long as it’s not either “This is the first line of code in app.js.” or “This is the last line of code in app.js.”).
Check your work to move on to the next step.
2.
Now, let’s invoke the setTimeout() function. Remember, setTimeout() has two parameters. Invoke setTimeout() with your usingSTO() function as the first argument and a number between 0 and 3000 as the second argument.

3. How do I pass parameters to the timeout function? most important one
There are two ways to pass parameters:
Add parameters after the delay argument:
setTimeout(myFunction, 1000, param1, param2)Use an arrow function or closure:
setTimeout(() => myFunction(param1, param2), 1000)
Consuming Promises

Success and Failure Callback Functions
so basically below code represents the setTimeout here so that it works out !!!
1.
Take a look at the provided code in app.js. We use require() to include the function checkInventory() from library.js. It builds on the logic of the orderSunglasses() function you wrote in a previous exercise.
checkInventory()takes in an array representing an order and returns a promise.If every item in the order is in stock, that promise resolves with the value
"Thank you. Your order was successful."Otherwise, the promise rejects with the value
"We're sorry. Your order could not be completed because some items are sold out".
We used setTimeout() to ensure that the checkInventory() promise settles asynchronously.
If you’d like, check out the library.js file to see how it works. Press “Check Work” when you’re ready to move on.

2.
Write a function, handleSuccess(). You’ll use this function later on as your success handler. handleSuccess() should take one parameter, representing a resolved value. Inside the body of handleSuccess(), log the parameter to the console.
4.
Invoke checkInventory() with order. This will return a promise. Attach a .then() function to this. Pass into .then() the two handlers you wrote as callback functions.
Type node app.js in the terminal and hit enter.
Be sure to click “Check Work” after running the command to pass this checkpoint and move on to the next exercise.

Using catch() with Promises
1.
We’re going to refactor the functionality of the previous exercise but this time we’ll use
.catch()! First invoke thecheckInventory()function with theorder. Remember, this function will return a promise.Checkpoint 2 Passed
2.
Add a
.then()to the returned promise and pass in the success handler,handleSuccess.
3.
Add a .catch() to the returned promise. Pass in the failure handler handleFailure().
4.
We set our inventory of sunglasses to 0, so the order shouldn’t go through. Let’s make sure our code has the expected results. Type node app.js in the terminal and hit enter.
Be sure to click “Check Work” after running the command to pass this checkpoint and move on to the next exercise.

Chaining Multiple Promises
Let’s break down what’s happening in the example:
We invoke a function
firstPromiseFunction()which returns a promise.We invoke
.then()Preview: Docs Returns a new Promise object. with an anonymous function as the success handler.Inside the success handler we return a new promise — the result of invoking a second function,
secondPromiseFunction()with the first promise’s resolved value.We invoke a second
.then()to handle the logic for the second promise settling.Inside that
.then(), we have a success handler, which will log the second promise’s resolved value to the console
We set up a promise chain, but it’s missing a couple of important lines of code to make it function properly.
We invoked checkInventory() with order and chained a .then() function to it. This .then() has an anonymous function as its success handler, but it’s missing a return statement.
The success handler should return a promise that results from calling processPayment() with the resolved value of checkInventory(order).
return processPayment(resolvedValueArray);
})
3.
We have a second .then() function on the chain. This .then() also has an anonymous function as its success handler and is missing a return statement.
following code is from library.js and the best thing about code is it make a proper real website type orders !!
project based code practise
folder name --> modules
library.js and app.js two files present
app.js
library.js
last one order.html

Avoiding Common Mistakes
2.
Refactor, or rewrite, the code to avoid the two common mistakes: nesting and forgetting to return properly.
so below was the previous code !!

Mistake 1: Nesting promises instead of chaining them.
do understand the below code nicely !! like the promise thing is very very important !!
suppose there are two functions so i can literally state that , nice (resolve, reject){
if (blah){
resolve (nice)}
else ,reject("wow")
}
p.then((msg) ⇒ {
console.log("this is our"+ msg)
}
.catch((err)=>{console.log("this is the err" + err}
}
so the above one is the best example present here !!! i can state , promise is the best best thing i learned !!!
Using Promise.all()
3.
Invoke Promise.all() with an array containing checkSunglasses, checkPants, and checkBags.
Chain a .then() to the promise returned from Promise.all(). You should pass in onFulfill to serve as the success handler.
Add a .catch() to the chain. You should pass in onReject to serve as the failure handler.
library.js
aboce code is very important to understand as the set timeout is defined there inside the promise

Getting Started
XMLHttpRequest can be used in two modes: synchronous and asynchronous.
1. Asynchronous Method
There are 4 steps to do this:
1.Create XMLHttpRequest:
The constructor has no arguments.
2.Initialize it:
This method specifies the main parameters of the request:
method: HTTP-method. Usually"GET"or"POST".URL: The URL to request, a string, can be URL object.async: If explicitly set tofalse, then the request is synchronous.user,password: login and password for basic HTTP auth (if required).
3.Send it out.
This method opens up the connection and sends the request to server. The optional body parameter contains the request body.
Some request methods like GET do not have a body. And some of them like POST use body to send the data to the server.
4.Listen to xhr events for response.
These three events are the most widely used:
load: When the request is complete and the response is fully downloaded.error: When the request couldn’t be made successfully, For example, network down or invalid URL.progress: Triggers periodically while the response is being downloaded, reports how much has been downloaded.
so basically its , on error , on load , on progress
onload, onerror , onprogress
xhr.onload = function () { alert(Progress: ${xhr.status} ${xhr.response}); };
xhr.onerror = function () { alert(Network Error Occurred); };
xhr.onprogress = function (event) { // Triggers periodically // event.loaded - how many bytes downloaded // event.lengthComputable = true if the server sent Content-Length header // event.total - total number of bytes (if lengthComputable) alert(Received ${event.loaded} of ${event.total}); };

2. Synchronous Method
Response Type
xhr.responseType property can be used to set the response format:
""(default): get as string,"text": get as string,"arraybuffer": get as ArrayBuffer"blob": get as Blob,"document": get as XML document (can use XPath and other XML methods) or HTML document (based on the MIME type of the received data),"json": get as JSON (parsed automatically).https://www.youtube.com/watch?v=PZIvYmj_Rls&t=51s
Introduction to ASYNC AND AWAIT MOST IMPORTANT !!
1.
In this lesson, you’ll be given a code editor to write your code and a bash terminal to execute your code. To execute your program, you’ll type node app.js in the terminal and hit enter (or return). You’ll press the “Check Work” button to submit your code for evaluation.
Check out the code we provided. It shows three ways of accomplishing the same task: reading and printing from two files in a specified order:
The first version uses callback functions.
The second version uses native promise syntax.
The third version uses
async...await.
Don’t worry about understanding the async...await syntax — that’s what you’ll learn in this lesson! If you haven’t already, type node app.js into the terminal and press enter. Then, press “Check Work”.
utf8 meaning
'utf-8' = bytes → readable text (string)
The async Keyword
we can also create async function expressions:
2.
Write an async function, withAsync(), that reproduces the functionality of withConstructor(). Though your function will return a promise, it should not construct the promise using the new keyword. Instead, it should rely on the fact that an async function automatically returns a promise.
When you’re ready, check your work to move on to the next step.
The await Operator
Within our async function, asyncFuncExample(), we use await to halt our execution until myPromise() is resolved and assign its resolved value to the variable resolvedValue. Then we log resolvedValue to the console. We’re able to handle the logic for a promise in a way that reads like synchronous code.
NEW CONCEPT !!! FOR CLIENT SIDE HACKING !!
SO BASICALLY THERE ARE TWO FILES PRESENT IN THE BELOW SCREENSHOT , AND ONE OF THEM IS LIBRARY.JS

LIBRARY .JS
SO ABOVE CODE IS INCOMPLETE SO BASICALLY ITS A PROMISE CONCEPT AS THERE IS RESOLVE PARAM PRESENT SO WE HAVE TO USE PROMISE ALSO AT THE LAST ITS NOT ASYNC , SO
THIS WAS THE FUNCTION AND IT WILL PRINT EACH AFTER ONE SECOND !!! , JUST LIKE A BELOW SCREENSHOT !!!

BUT BUT THIS I HAD TO UNDERSTOOD BY RUNNING THE CODE !! ,ELSE you can see in the below screenshot that its totally confusing abot the code of the file library.js

so the main aim was to understand what is app.js saying i was condused unitl i tried this code in the online js compiler ,
this much was written in the app .js and i was confused as the promisses are too different as i can use any name at the parameter of the error handling like catch and then methods !!
as we can see above i called the function above nicely
otherwise the aboce is the best way to learn !!
so below is the key how i would add the async
down code is another example of async
JUST LOOK AT THE CODE AND JUST JUST JUST DO ONLINE JS COMPILER AND DO TRY EVERYTHING PLEASE !!
just read the whole code of the library.js and run it !!! with calling a function
Writing async Functions
Now we’ll write two async
functionsPreview: Docs Loading link description which invoke myPromise():

2.
Uh oh, getBeans() is logging '3. Great! I'm making [object Promise] beans for dinner tonight!' to the console. Take a moment to understand why this is happening, and then refactor getBeans() so it works as intended. Check your work when you’re ready to move on to the next step.
Handling Dependent Promises
2.
In the following checkpoints, you’ll create an async function that handles the three dependent promises we just walked through. It will simulate shopping for, soaking, and then cooking the beans. To get started, declare an async function, makeBeans(). You can leave the function body blank for now.
Check your work to move on to the next step.
3.
Inside your function, declare a variable, type, assigned to the resolved value of shopForBeans(). This must be accomplished in one statement.
here we have to declare a variable only!!!
4.
Next, still in makeBeans, declare a variable, isSoft, assigned to the resolved value of soakTheBeans(). Don’t forget: the soakTheBeans() function expects an argument. Make sure to pass the expected value into soakTheBeans().
5.
Next inside your function, declare a variable, dinner, assigned to the resolved of cookTheBeans(). Don’t forget: the cookTheBeans() function also expects an argument. Make sure to pass the expected value into cookTheBeans().
Handling Errors
2.
Declare an async function, hostDinnerParty(). Inside your function, create a try...catch statement. The catch statement should specify an identifier, error. You can leave both the try and catch blocks empty.
3.
Inside your try block, log a string in the following format: '[resolved value of cookBeanSouffle() promise] is served!' ie. 'Bean Souffle is served!'. Make sure to await the cookBeanSouffle() promise. For more guidance, check out the hint.
4.
Now let’s fill in the catch block! First log the error to the console, and then log the string: 'Ordering a pizza!' to the console.
Handling Independent Promises
2.
Declare an async function, serveDinner(). Within the function body, create four variables:
vegetablePromise, which should be assigned the return value ofsteamBroccoli()starchPromise, which should be assigned the return value ofcookRice()proteinPromise, which should be assigned the return value ofbakeChicken()sidePromise, which should be assigned the return value ofcookBeans()
These variables should be assigned the promise objects themselves, not their resolved values.
3.
Next, console.log() a string in the following format:
Dinner is served. We’re having [resolved value of the
vegetablePromise], [resolved value of thestarchPromise], [resolved value of theproteinPromise], and [resolved value of thesidePromise].
i.e., “Dinner is served. We’re having broccoli, rice, chicken, and beans.”
You’ll need to await each promise, but there are a few different ways you can accomplish the desired functionality. Check out the hint if you want some guidance.
4.
Awesome! Let’s see your function in action. Beneath your function declaration, invoke
serveDinner().Checkpoint 5 Passed
5.
In the terminal type
node app.jsand press enter to run the code.Be sure to click “Check Work” after running the command to pass this checkpoint and move on to the next exercise.

3.
Next, console.log() a string in the following format:
Dinner is served. We’re having [first item in
foodArray], [second item infoodArray], [third item infoodArray], and [fourth item infoodArray].
i.e., ‘Dinner is served. We’re having broccoli, rice, chicken, and beans.’
There are a few different ways you can accomplish the desired functionality. Check out the hint if you want some guidance.
4.
Ok great! Now let’s see your function in action. Beneath your function declaration, invoke serveDinnerAgain().
Intro to GET Requests using Fetch (client side deep understanding !!)

The fetch() function:
Creates a request object that contains relevant information that an API needs.
Sends that request object to the API endpoint provided.
Returns a promise that ultimately resolves to a response object, which contains the status of the promise with information the API sent back.
First, call the fetch() function and pass it a URL as a string for the first argument, determining the endpoint of the request.
making a GET REQUEST (CLIENT SIDE )
1.
At the top of main.js, create a const variable called url. Assign url to the following URL as a string:
The ?sl= portion of the string will be the start of your query string, which will be used to pass parameters to the Datamuse API. The query string will be used by the engine to narrow the search to words that sound like your word.
2.
Within main.js, we have provided an empty getSuggestions() function. In the function body, create a const variable called wordQuery and assign it inputField.value.
We’ll need wordQuery to store the value of what is being typed into the input field.
Create another const variable called endpoint and assign it the value of a string that is url, and wordQuery concatenated in that order.
We will be working inside getSuggestions() function for the remainder of this exercise.
3.
Inside the getSuggestions() function, call the fetch() function and pass in endpoint as an argument. For this API to work within the Codecademy browser, add { cache: 'no-cache' } as the second argument.
fetch(endpoint, { cache: 'no-cache' });

5.
Inside the success callback function, create a conditional statement that checks if the ok property of the response object evaluates to a truthy value.
If so, return response.json().
By returning response.json(), the next .then() method chained to it will receive a Promise with JSON data.
🔍 Ab Ye Line Dekh:
Break karte hain:
🔹 document
Ye pura webpage hai.
🔹 querySelector()
Ye ek function hai jo HTML me se koi element dhoondta hai.
🔹 '#input'
Ye CSS selector hai.
# ka matlab → id
Matlab:
HTML me jiska id="input" hai, mujhe woh element de do.
so basically # means id its css !!
we can also use document.getElementById('input')
document.getElementById() title.inner.HTML title.innerText title.textContent
documentr.getElementById('title').getAttribute('id')
title.style.backgroundcolor = "green"
title.style.padding='15px'
Handling a GET Request
1.
After the existing .then() method, chain another .then() method.
As the first argument of our second .then() method, pass an anonymous arrow callback function that takes jsonResponse as its single parameter.
2.
Inside the callback function we just created, call the renderRawResponse() function and pass in jsonResponse as its argument. Run the code.
In the input field, type in a word and click the submit button.
If all went well, we should see an array of words that the Datamuse API responded with!
Note that you can find the renderRawResponse() function declaration in public/helperFunctions.js. In this context, the function is available in main.js without any import statement.
3.
Let’s format our response from the Datamuse API to look presentable on the webpage. To do this, we will use the renderResponse() function that’s been defined in public/helperFunctions.js.
Comment out renderRawResponse(jsonResponse). Then, call renderResponse(jsonResponse) instead.
Run your code.
Try the webpage again with another word!
Intro to POST Requests using Fetch

2.
We will make our POST request inside the shortenUrl() function. Inside the code block of shortenUrl(), create a const variable named urlToShorten and assign it inputField.value. urlToShorten will keep the value of what is being typed into the input field.
Note that we will be working inside shortenUrl() for the remainder of this exercise.
3.
Underneath the urlToShorten declaration, create another const variable named data and assign it to the stringified version of {destination: urlToShorten}. We can use the JSON.stringify() method to do this.
The data variable will be used to send the information, which needs to be in string format, to the request body.
4.
Below our data variable declaration, call the fetch() function. Pass url as its first argument and an empty object as its second argument.
5.
Now it’s time to add some properties to the empty object that you just created. Add a property with the key method and the value 'POST'.
6.
In the same object, add another property. The key for this property is headers, and the value will be the following object:
below code is so nice to understand !!!
Handling a POST Request
4.
As the second argument of the .then() method, add another arrow callback function that takes networkError as a single parameter.
Log the networkError.message inside of the callback function.
By adding this second callback, you’re safeguarding yourself in the rare event that the network returns an error!
5.
Chain another .then() method to the end of the previous .then() method.
6.
Pass in an anonymous arrow function as an argument for our second .then(). This callback function will take jsonResponse as its single parameter.
Inside the callback function, call renderResponse() and pass in jsonResponse.
The renderResponse() helper function can be viewed at public/helperFunctions.js.
Run the code.
Put in any URL in the text field, and then click the shorten button on the webpage. Make sure you include the entire link, including 'http://' or 'https://'.
6.
Pass in an anonymous arrow function as an argument for our second .then(). This callback function will take jsonResponse as its single parameter.
Inside the callback function, call renderResponse() and pass in jsonResponse.
The renderResponse() helper function can be viewed at public/helperFunctions.js.
Run the code.
Put in any URL in the text field, and then click the shorten button on the webpage. Make sure you include the entire link, including 'http://' or 'https://'.
json stringify()
this is how we can stringify !!
intro to async GET Rquests !!

Intro to POST Requests using Fetch

The
asynckeyword is used to declare anasyncfunction that returns a promisePreview: Docs Loading link description.The
awaitkeyword can only be used within anasyncfunction.awaitsuspends the program while waiting for a promise to resolve.In a
try...catchstatement, code in thetryblock will be run and in the event of an exception, the code in thecatchstatement will run.
Study the async getData() function to the right to see how the request can be written using async and await.
1.
Under the comment “Asynchronous function”, create a const variable called getSuggestions and set it to a new arrow function using the async keyword.
You’ll be coding inside the getSuggestions() function for the remainder of this exercise.
Making an async GET Request
1.
Under the comment “Asynchronous function”, create a const variable called getSuggestions and set it to a new arrow function using the async keyword.
You’ll be coding inside the getSuggestions() function for the remainder of this exercise.
2.
Inside the getSuggestions() function, create a const variable named wordQuery and assign it inputField.value.
3.
Create another const variable called endpoint and assign it the value of a string that is url, queryParams, and wordQuery concatenated in that order.
4.
Add a try statement with an empty code block. Outside the code block for try, add a catch(error) statement with a code block that logs error to the console.
try {
// code goes here
} catch (error) {
console.log(error);
}
5.
Inside the try code block, create a const variable named response and assign it to await the result of calling fetch() with endpoint as the first argument. For this API to work within the Codecademy browser, add {cache: 'no-cache'} as the second argument.
6.
Below the response variable declaration from the previous step, create a conditional statement that checks if the ok property of the response evaluates to a truthy value.
Inside the code block of the conditional statement, await response.json() and save it to a new const variable called jsonResponse.
7.
Still inside the conditional statement, call the function renderResponse() and pass in jsonResponse. Then, run the code.
In the input field, type in a word and click the submit button on the web page.
Great, now we have an organized list of words from the GET request!
The declaration of the renderResponse() function can be found at public/helperFunctions.js.
renderResponse(jsonResponse);

Intro to async POST Requests

Review
1 min
In this lesson, we learned how to make GET and POST
requestsPreview: Docs Loading link description using the Fetch API and async/await keywords. Let’s recap on the concepts covered in the previous exercises:
GET and POST requests can be created in a variety of ways.
We can use
fetch()andasync/awaitto asynchronously request data from APIs.Promises are a type of JavaScript object that represents data that will eventually be returned from a request.
The
fetch()function can be used to create requests and will return promises.The
asynckeyword is used to create asynchronous functionsPreview: Docs Loading link description that will return promises.The
awaitkeyword can only be used with functions declared with theasynckeyword.The
awaitkeyword suspends the program while waiting for a promise to resolve.
Congratulations on learning all about asynchronous requests using fetch(), async, and await! These concepts are fundamental to helping you develop more robust web apps!
witten some nice notes on the async await POST !!
bug bounty links present inside this !
Error Stack Traces

sovle the below code on my own next time i revise !
JavaScript Error Types
4 min
Now that you can identify the type of error from an error stack trace, you might be wondering what the different types of
errorsPreview: Docs Loading link description mean.
Here are three common error types:
SyntaxError: This error will be thrown when a typo creates invalid code — code that cannot be interpreted by the compiler. When this error is thrown, scan your code to make sure you properly opened and closed all brackets, braces, and parentheses and that you didn’t include any invalid semicolons.
ReferenceError: This error will be thrown if you try to use a variable that does not exist. When this error is thrown, make sure all variablesPreview: Docs Variables are used to store a piece of data at a named location in memory. are properly declared.
TypeError: This error will be thrown if you attempt to perform an operation on a value of the wrong type. For example, if we tried to use a string method on a number, it would throw a TypeError.
find the bug !!! and fix it !!!

Locating Silent Bugs
In the code editor, we’ve given you a function that is supposed to take a string containing a single word as an argument and return the capitalized version of that word. If the string contains multiple words (contains a space character,
' '), it should returnnull.Currently, this code is not working as expected. Take a look at our tests on lines 16-19. We expect the first function call to return
'Hey'and the second function call to returnnull. Run the code to see that it is not working as expected but also not throwing any errors.Checkpoint 2 Passed
2.
Let’s use
console.log()to debug this code! Start by adding aconsole.log()statement to line 2 and printing out thewordbeing passed into the function. This will help us ensure our function is being called properly and thewordvariable is set as we expect at the start of the function.Checkpoint 3 Passed
3.
Looking at the console output, both
'hey'and'hey ho'are being printed as we expected. No bugs yet.Comment out the
console.log()statement from the beginning of the function. Then add the followingconsole.log()statement inside theifstatement to see if it is working properly:The behavior we want is for
'hey ho'to enter theifblock and returnnulland for'hey'to skip theifblock and get capitalized.Checkpoint 4 Passed
4.
Look at the console output.
'hey'is being printed from inside theifstatement block and'hey ho'is not. This is the opposite behavior we expected. We found a bug!Looking at our
ifstatement, we accidentally included a!that is negating our condition. It is saying that if a word does not have multiple words, go into theifblock, and if it does, move past it.Delete the
!character from the beginning of theifstatement condition to fix the bug, then re-run our code.Our function now appears to be working as expected, so there is no need to continue stepping through the rest of the function.
Debugging with console.log()
below code is incorrect try to fix the bugs !!
this was so nice !!!
Finding Documentation
1.
In the code editor, we’ve included a function that is supposed to take a string and return a version of that string repeated twice. For example, you can see in the test case at the bottom of the file, we expect doubleString('echo') to return 'echoecho'.
However currently, when we run our file, nothing happens. Clearly we are using the .repeat() method incorrectly. Let’s find the MDN documentation for String.repeat().
Find the link to the documentation for String.repeat() and paste it to the end of the comment on line 1.
Introduction to Error Handling
Runtime Errors
Constructing an Error
The throw Keyword
1.
Use the throw keyword to throw an error with the message 'Username or password does not match'
After you clear this checkpoint, try adding some code after your throw statement. Also, try to throw a new error and other data types to see what happens!
The try...catch Statement
1.
Create a try...catch statement that doesn’t have any code in the try block or the catch block. Make sure to use e as the error object.
2.
In the try block, throw an error using the Error() function and pass into Error() a string containing a message of your choice!
3.
Inside the catch block, log the error to the console
Handling with try...catch
1.
In
main.js, there is a function calledcapAllElements()that takes an array of elements and capitalizes each element.Currently, it’s written in such a way that the function will execute regardless of what argument is passed in, but what if the argument isn’t an array? As written, an error would be thrown, and our program would stop running.
Run the code as it is to see what error shows up in the console.
Let’s handle that error:
Put the existing
arr.forEach(...)code in atryblock.Add a
catchstatement after thetryblock and inside thecatchblock, log the error to the console.
Error Handling Review
<1 min
Great job with handling errors!
In this lesson, we went over:
How mistakes in programming lead to errorsPreview: Docs Loading link description.
Why errors are useful for developers.
Errors will prevent a program from executing unless it is handled.
How to create an error using the
Error()function.How to throw an error object using the
throwkeyword.How to use the
try...catchstatement to handle thrown errors.Evaluating code in a
tryblock to anticipate errors.Catching the error in a
catchblock to allow our program to continue running.Why the
try...catchstatement would be useful in a program.
Currying in JavaScript
Concurrency Model and Event Loop in JavaScript
The Event Loop in Action
Now that we know all of the pieces of the event loop, let’s walk through some code to understand the event loop in action.
console.log("This is the first line of code in app.js.");is added to the stack, executes, then pops off of the stack.setTimeout()is added to the stack.setTimeout()’s callback is passed to be executed by a web API. The timer will run for 3 seconds. After 3 seconds elapse, the callback function,usingsetTimeout()is pushed to the Event Queue.The Event Loop, meanwhile, will check periodically if the stack is cleared to handle any messages in the Event Queue.
console.log("This is the last line of code in app.js.");is added to the stack, executes, then pops off of the stack.The stack is now empty, so the event loop pushes
usingsetTimeoutonto the stack.console.log("I'm going to be queued in the Event Loop.");is added to the stack, executes, gets poppedusingsetTimeoutpops off of the stack.
The Heap
Memory in JavaScript
JavaScript has two data structures for memory:
The heap
The stack
The stack is used for static storage, where the size of an object is known when the code is compiled. Since the size is known, a fixed amount of data is reserved for the object, and the stack remains ordered. The stack has a finite amount of space provided by the operating system, which you typically only exceed when you have problems in your code, like infinite recursion or memory leaks.
Primitive values, references to non-primitive values, and function call frames are stored in the stack. You can think of references as a parking space number in a massive (but disordered) parking garage telling JavaScript where to find objects and functions.
The Heap
The heap provides dynamic memory allocation at runtime for data types that don’t have a fixed size, like objects and functions. These are reference values and we keep track of where to find them in the unstructured heap using a fixed-size reference in the stack. If you modify an object, you are modifying a reference to the object and not the object itself.
In the example, cat is stored in the heap, a reference to cat is stored in the stack, and the property name is stored in the stack. The pets array is stored in the heap, while a reference to it is stored in the stack.
In the example, object and object2 are pointing to the same object in memory in the heap, but with different variables that are saved in the stack.
design patterns !!
What an Anti-Pattern Looks Like
In the example below of what not to do, Customer objects are all-knowing and have too much responsibility–this code follows the “God Object” anti-pattern.
Let’s look at what is going on in the Customer class that is not working well. This class creates a Customer object with properties about a customer and their transactions.
Learn Intermediate JavaScript: Next Steps
You’ve completed the Learn Intermediate JavaScript course! What’s next?
Congratulations, you’ve successfully completed the Learn Intermediate JavaScript course! You got an introduction to intermediate programming topics in JavaScript. More specifically, you learned to:
create classes and use inheritance to minimize redundancy
use JavaScript modules to define reusable logic
identify the ways currying and hoisting contribute to how JavaScript works under the hood
write asynchronous JavaScript with promises and async/await
create calls to various APIs using requests
identify and handle errors
understand the concurrency module and event loop in JavaScript
Your learning journey into JavaScript isn’t over yet! There are plenty of other topics that you can dive into to continue learning. Here are our recommendations for the next steps:
Last updated
Was this helpful?


