Introduction to JavaScript
JavaScript is a high-level, versatile programming language primarily used for creating interactive web and mobile applications. It ranks as one of the most popular programming languages globally, favored by developers for its flexibility, with a strong job market and lucrative salaries.
1. What is JavaScript and its Common Usage?
A language for interactive browser effects and app development, JavaScript handles client-side and server-side programming.
2. Template Literals
Use backticks () and ${}` syntax to embed variables and expressions directly into strings, improving readability and maintainability.
3. Hoisting
JavaScript hoists variable and function declarations to the top of their scope, allowing functions to be called before their declaration without errors. Variable hoisting behavior differs between var, let, and const.
4. Difference between var, let, and const
var: Function-scoped, globally accessible, prone to unexpected behavior.let: Block-scoped variable, mutable.const: Block-scoped, prevents reassignment, preferred for safer code.
5. JavaScript Data Types
Primitive (immutable): Number, String, Boolean, Undefined, Null, Symbol, BigInt. Non-primitive (mutable): Object, Array, Function.
6. Arrays
Ordered collections; access via zero-based indexes; can iterate with loops or forEach.
7. Double Equality (==) vs Triple Equality (===)
==performs type coercion before comparison.===compares both value and type without coercion.
8. isNaN() Function
Checks if a value is 'Not a Number'; useful for input validation.
9. Null vs Undefined
- Undefined: Variable declared but not assigned.
- Null: Explicitly assigned absence of value.
10. typeof Operator
Returns a string indicating the data type of a value or variable.
Medium Level Concepts
11. Array map() Method
Creates a new array by applying a function to each element. Does not modify the original array.
12. Event Capturing and Bubbling
- Capturing: Events propagate from outermost to innermost elements.
- Bubbling: Events propagate from innermost to outermost.
13. Higher-Order Functions
Functions that take other functions as arguments or return functions, e.g., map.
14. Immediately Invoked Function Expressions (IIFE)
Functions defined and executed immediately, useful for encapsulation.
15. Closures
Inner functions retaining access to outer function variables even after outer function execution completes; enables private variables.
16. setTimeout vs setInterval
setTimeout: Executes once after a delay.setInterval: Repeatedly executes at specified intervals.
17. Promises
Handle asynchronous operations with states: pending, fulfilled, rejected, providing cleaner alternatives to callbacks.
18. Async/Await
Syntactic sugar over promises to write asynchronous code in a synchronous style; improves readability. For a structured learning path on JavaScript fundamentals and asynchronous programming, consider our Complete JavaScript Beginner Course: Projects, Fundamentals, and API Integration.
19. Difference between Call, Apply, Bind
call: Invokes function immediately with arguments individually.apply: Invokes function immediately with arguments as an array.bind: Returns a new function with bound context and arguments, executed later.
20. Event Delegation
Attaching a single event listener to a parent element to manage events on child elements efficiently using event bubbling.
Advanced Topics
21. Event Loop
Manages asynchronous callbacks by using the call stack and callback queue, allowing non-blocking operations.
22. Async/Await vs Promises
Async/await improves code readability by pausing execution until promises resolve or reject.
23. Array reduce() Method
Transforms an array into a single value by applying a reducer function cumulatively.
24. Currying Functions
Transforms a function with multiple arguments into a sequence of functions with single arguments, enhancing reusability.
25. Generator Functions
Functions that can pause and resume execution, preventing infinite loops and managing asynchronous flow.
26. WeakMap and WeakSet
Memory-efficient collections storing objects that allow garbage collection of unused keys.
27. Memory Management in JavaScript
Uses stack for primitive data and heap for objects; garbage collection removes unreferenced memory.
28. Shallow vs Deep Copy
- Shallow copy replicates top-level properties; nested objects still linked.
- Deep copy duplicates all properties and nested objects, preventing side effects.
29. Strict Mode
Enables safer coding by disallowing certain unsafe actions like undeclared variables or duplicate parameter names.
30. Observer Pattern
Design pattern where subjects notify observers about state changes. Commonly used in event handling and reactive programming.
This comprehensive review covers key JavaScript concepts critical for interview success, with practical insights, coding examples, and clear distinctions between related terms. For those preparing for broader tech interviews including frameworks often paired with JavaScript, explore our Top 10 Angular Interview Questions for Beginners and Juniors and 25 Essential Angular Interview Questions with Code Demonstrations to deepen your understanding in modern front-end development. Preparing with these questions will enhance your understanding and confidence in JavaScript programming.
hello and welcome to this session on JavaScript interview question and answers by intellipath JavaScript is
widely known for its flexibility and adaptiveness yet because of these same traits it's often regarded as a weird
programming language and that's because in JavaScript null which basically translates to nothing in Latin is
treated as an object n an or not a number even with the name not a number is treated as an actual number string 5
minus number two is is three but string five plus number two is 52 and this list just goes on yet the survey conducted by
stack Overflow proves that more than 65% of people prefer JavaScript over other programming languages another article by
Fortune recommends declare JavaScript to be the most used language in both stack Overflow and GitHub in 2023 now if this
wasn't enough to convince you let's take a look at the salaries with over 16,000 job opportunities and an average salary
of five lakhs perom JavaScript continues to be the programmer's favorite language for both front-end and backend
development before we start this session if you want more such content then make sure to hit the Bell icon And subscribe
to Intel's YouTube channel for this video we have as usual divided the content into three modules easy medium
and hard with 10 questions each we have compiled these questions and their answers after observing the commonly
repeated questions in almost every real life JavaScript interview we even went one step further and consulted industry
experts with eight plus years of experience working in the web development field keep in mind that in
almost every interview the next question is asked from your previous answer so keep your answers as concise as possible
and only include the terms and definitions that you are familiar with on that note let's start with our first
and obvious question what is Javascript and where is it commonly used JavaScript is a highlevel programming language that
is widely used to create interactive effects within web browsers a highlevel programming language is a human
understandable language it is commonly used for developing both web and mobile applications moving on to the next
question which is what are template literals in JavaScript template literals are what you get when you combine the
dollar sign curly brackets and the back ticks now the reason why we need them is to Simply make our coding lives easier
let me tell you how if we have two variables a with the value 10 and B with the value 20 and we want to print their
sum on the console it would look something like this this code is now not so clean and requires a lot of work
hence we use template literals they neatly enclose everything within back ticks with executable code placed inside
the dollar signs and curly braces like this so in a nutshell template literals are used to embed variables and
expressions directly into a string making the code more readable and flexible moving on to the next next
question what is hoisting and give an example we started this video by discussing the weird nature of
JavaScript hoisting is one such weird nature let me show you how here I'm declaring a function called as greet
which prints hello on the console now in case of any normal programming languages say python calling a function before it
is declared will throw an error like this but since JavaScript is Javascript this will actually execute the code and
print the output as well now this fin nomena is called as hoisting where variables and functions declarations are
moved or hoisted to the top of their scope before their execution hosting is of two types variable hosting and
function hosting the code we looked at previously is function hosting and as for variable hoisting the where keyword
will give undefined as output whereas let and const will throw a reference error if you try to access these
variables without initializing them first initializing means assigning values to them now that we have brushed
the topic of let where and const it's only fair that the next questions should explore these Concepts further which
brings us to the next question explain the difference between let war and const here I have three variables V A let B
and const C enclosed within an if block now if you try to access the variables a b and c inside the if block you'll get
the expected output that is 10 20 and 30 however if you try to access these variables outside the if block you'll
only be able to access where A's value let B and con c will throw a reference error this happens because let and const
have block scope meaning they are only accessible within the Block in which they are declared such as the if block
or a for Loop Etc but the V keyword has a function scope meaning it can be accessed globally keep in mind that if a
v is declared inside a function it can only be accessed within that function trying to access it outside will throw
another reference error hence it is known to have a function scope however being globally accessible is not a flex
because of all three V is preferred the least because this same Global accessibility can sometimes lead to
unexpected behaviors V is followed by let and const with const being prioritized due to its ability to
prevent reassignment helping prevent unexpected data leaks so to sum up using V is generally discouraged due to it
being function scoped both let and const have blog scope but only const can prevent reassignment moving forward to
the fifth question what are data types available in JavaScript data types in JavaScript can be categorized into
primitive and non-primitive primitive data types are immutable meaning they cannot be modified whereas nonprimitive
data types are mutable primitive data types includes number string Boolean and define null symbol and B let's start
with number number represents both integer and floating Point numbers it also includes special variables like
infinity negative infinity and N an or not a number next we have string which represents a sequence of characters or a
text strings can be created using single quotation marks double quotation marks or back tcks on number three we have
Boolean which represents a logical entity and it can have two values true or false next we have undefined which is
a default value provided to the variable that have been declared but not been assigned a value yet next is null null
is commonly used when you have declared a variable but either you do not want to assign it a value yet or it should not
have a value at all next we have the slightly complicated symbol symbol represents a unique and immutable
identifier which is often used for object properties to avoid naming conflicts as shown in the code Sim 1 and
Sim 2 even after having the same description will give the output as false lastly we have big int big int is
used for very large integers that exceed the limit of the number data type bigant values are created by appending n to the
end end of any integer that's all for primitive data types next we have non-primitive data types like object
array and function let's start with object object is a collection of key value pairs object can contain other
objects functions and data types next we have arrays which is a list like structure used to store multiple values
in an ordered fashion arrays in JavaScript are zero IND text lastly we have function a function is a block of
reusable code in JavaScript functions are treated as objects and can be assigned to variables passed as
arguments or returned from other functions now that we have explored the different types of data in JavaScript
let's look at the collection of this data by moving on to our next question which is what is an array in JavaScript
and how do you act access its elements an array in JavaScript is an ordered collection of values or elements the
elements stored in the array can be of any data type but they all must belong to the same data type in JavaScript you
can create an array either using the array literal syntax or you can take the road not taken with array Constructor if
you want to access a specific element in the array you can directly access them using their indexes as shown in the code
or if you want to iterate through the whole array you can use a for Loop or make it even simpler and use a for each
loop with that we reach the end of this question moving on to our seventh question which is explain the difference
between double equal to and triple equal to in JavaScript this is true and this is false if you look closely enough
everything is same in both the codes except the operator double equal to is known as the equality operator and
triple equal to is known as the strict equality operator the difference arises because double equal to performs type
coercion which converts the string five to number five resulting in the output being true triple equal to on the other
hand does not perform type coercion resulting in the output being false type coercion is another interesting topic
we'll explore it further with our next question what is the purpose of the is not a function or the is naan function
as the name suggests is not a number is a special JavaScript value that checks if a given number is not a number if the
output cannot be coerced or converted into a number then is n an returns true as in case of these three hello being a
string cannot be converted to a number although type of Nan is a number it's still treated as not a number and type
of undefined is undefined so it's also not a number however if you consider this string here string 1 2 3 can be
converted or coerced into number 1 2 3 resulting in the output being false because it is a number the same goes for
an actual number as well here's an interesting fact null is also treated as a number in JavaScript which brings us
to our next question what is null and undefined null and undefined both indicate the absence of a value on one
hand undefined is used when a variable is declared but has not been assigned a value yet it's more of a default State
as shown in this code the variable a has been declared but not initialized hence it is given the default value of
undefined null on the other hand is the intentional absence of any value is when you don't want to assign any value to a
variable because either you might assign it later or you just want to leave it empty like in the case of this variable
B which has been declared null for the time being but it can be assigned a value later moving on to our next
question explain the use of the type of operator we have already used type of a lot so you must have some idea about the
type of operator it determines the data type of a given value or a variable and returns a string this becomes useful
when you you are validating the user input or handling data differently based on its type and with that we reached the
end of this particular module moving on to our next module moving on to our next module that is the media module and we
have our 11th question on screen which is what is the purpose of the map method in JavaScript now to understand exactly
what map method means in JavaScript we'll have to look at the code to exactly understand what difference it
brings in the code um let me open my WS code really quick and this is question 11 yes
okay um let me create an array first called numbers all right now it has values
stored from 1 to 5 now what I want to do here is I want to multiply all these numbers into two all these values inside
the number array should be doubled that is what I want but I don't want this original array to be modified I want to
create a new array for doing this you can simply do this using a for Loop but the problem there would be I'll have to
create a new array and then I'll have to itate through every single element and then every single time I'll have to push
these elements into the new created array and it's not that big of a deal but still it'll take at least three to
four lines of code including the parenthesis being a programmer it's your duty to be lazy and that is exactly why
we have the map method let me show you how these three to four lines we can shrink it down to one line while we are
creating a new array and doing all of this in one single line let me create another array cons
double numbers dot map I'll take a variable called as num num multiply by
two now if I try to console Lo this value 2 4 6 8 10 and that's done in one single line so this is exactly what map
does now if I try to another best thing I like about Maps a lot is it doesn't mess around with the original array so
if I try to run this code you can see the original array the numbers array is not modified at all while I'm getting
another array I'm modifying every single element inside this Nary in one single line now doubling it is not a big deal
that's why this code might seem too small for you but if this was a complicated particular line of code then
reducing three to four lines of code into one single line can and make a lot of difference and that's exactly why map
is existing there let's look at the proper technical definition that you can use in the interview which is the map
method in JavaScript is used to create a new array by applying a specified function to each element to an existing
array I hope that was enough to clear what exactly map is and how it works in JavaScript moving on to the next
question which is what is even bubbling and event capturing in JavaScript this is one of the really interesting
questions in JavaScript let me take an analogy so that you can understand it better because these words are used so
commonly even bubbling and even capturing you can get confused with both of them which is even bubbling and which
is even capturing so let me just take an example um say you have a particular company you have the CEO you have the
manager and then you have the employees so a new feature is introduced into the company right and now this new
feature the CEO first knows about this particular new feature the CEO talks to the man about this new feature then the
manager also knows about the feature next the manager goes and communicates about this new feature to the
employees that is called as event capturing when the action is performed from the outermost element and it
reaches the innermost element that is called as event capturing next you have event bubbling how I like to think of it
as bubbling is like it starts from the bottom and it goes to the top like the bubbles if you if you've ever drunk soda
lime or something you can see the bubbles it starts from the bottom and it goes to the top that's how event
bubbling also works that is say if the employees in the particular company have certain concerns related to the
management the these concerns will first be communicated to the manager and then the manager will communicate this
further to the CEO that is called as bubbling starting from the innermost and going to the outermost or starting from
the bottom going to the top now let's look at the code example so that you can see this in action let me open my V code
again this is question to 12 oh I need an HTML for this
okay I close this I need three elements here uh
parent or let's just call it top top div mid div
or let's just call it inner div oh I put it as a class okay ID this is
the uh outer div mid
intive all right now comes the important part which is the JavaScript part that is to detect The
Click writing JavaScript in HTML file is really difficult but let's do it anyways ad listener
we're going to add a click event and when the click does happen we're going to conso
log outer oh God outer div has been clicked okay now we'll have to repeat this three times two
times top div is done mid div and
intive mid div has been clicked and inner div has been clicked if let's run this code okay this looks
very bad let's just try to add a little bit of styling so that you can differentiate
between them so first we have the top div um border first um or maybe I'll just give it
purple okay let's add a little padding
okay this is why you should not start styling then you just can't stop margin is 10 pixels okay
now that looks really good we need to do the same thing for uh mid
div and intive although we need to change the color and
uh this should be pink okay oh that's horrible yeah and let's call this yellow okay should not have started
this okay all right now let's see if it's it is working as per we wanted it to work so right now we're doing event
bubbling and according to event bubbling if I click on the inner div right here then the inner should come first then
mid should come first then outer as in going from the employees manager CEO however in case of event capturing for
event capturing all we need to do is allow the default setting okay that is put this as true allow the
capturing in the ele ad event listener by default it's turned off it's turned as false so you need to turn that on
turn the capturing on and that is why you're writing true that is you're saying true you're saying okay to the
capturing part now if you enable that and then I reload this page now if I click on this inner div outer div should
come first like this outer div then mid then inner outside to the inside CEO manager employees like that that is
event capturing now if we were to look at the technical definitions event bubbling is a
propagation model where events are handled from the innermost element to the outermost whereas event capturing is
a propagation model where events are handled from the outermost element to the innermost now let's move on to our
next question which is what are higher order functions can you give an example higher order functions are another
interesting Concept in JavaScript because these are the kind of functions which can accept another function as
their parameter let me show you how we just talked about map right we're going to look at the map function here map in
itself is a function which accepts another function so that is why map is called as an higher order function if
you were to look at the definition of this a higher order function is a function
that can either take out the function as an argument or return a function as a result now our map method can take a
function as an argument and return the function as an argument as well let me show you
how now we did it in a very simplified way this one particular line but you know we can make this complicated and we
can make this look as though map is accepting a function and returning a function
let me show you how I need the same numbers here
double num not null numbers. map last time we just directly created a variable this time let's write function which is
taking num as the parameter and then it is
returning that num multiplied by two map right here is accepting a function hence it is termed as a higher order
function so any particular function not just map you can also create functions like that which can accept an argument
as a function is called as a high order function or it can return a function as well that is also called as a higher
order function okay so let's move on to the next question which is what is I if or
immediately invoked function expression in JavaScript um technical definition an immediately
in invoked the function expression is a JavaScript function that is defined and executed immediately after it's
created let me show you the code so that you can understand better and why exactly you need an immediately invoked
function say I have a regular function here called as say greet which says
hello world this is a regular function let me just write that Here
regular function now let me show you what immediately invoked a function is if I
could create a function which would run automatically without calling because right now if I have to run this if I run
this code nothing would happen but if I call this function and then run this code only
then am I getting my result as hello world but what if I had to make a function which doesn't needs to be
called and it'll run automatically every single time I run my whole code that is called as an iif or an immediately
invoked function expression in JavaScript now let me write let me show you how to create an iif I'll create a
function here wrap this up in the parenthesis another interesting fact about if is that you don't even need to
give it a name because names are usually given because you need to call them but in case of IFA you don't need to call
them they're automatically called hence no name required
okay now if I run this code the second hello world with a capital W is called by your nameless iif function and that
is how it works it is executed even without you calling it so immediately invoked function as a name suggests is a
function that can run every single time your code runs without being called so moving on to our next
question which is what do you understand by closures in JavaScript closures in JavaScript is a
little bit of a tricky topic and you'll understand why when you look at the definition in JavaScript a closure is a
function that remembers the environment in which it was created even after the outer function has finished finished
executing I know this sounds confusing so because of that let me just show you this with the help of a code and let me
just try explaining to you what exactly the definition meant so uh it's a function which remembers the environment
in which it was created even after the outer function has finished executing right so let's create an outer function
first and inside of this we need to create an inner function all right now if I were to declare a
variable say outer variable uh then this variable is being accessed
inside the inner function and this outer function is returning this in a
function now if I create another variable say closure function you can call it anything you don't have
to necessarily name it closure closure function I've just named it closure function because we're talking about it
so if I call out a function in here then I write I try to run closure closure
function my inner function is being able to access the variable which is inside the outer function now keep in mind that
first when you when you run this particular code outer function is being called so after outer function finishes
executing inner function starts executing now keep in mind that just look at this particular block of code
now if you see outer variable is inside inner function and outer variable has not been declared or initialized inside
the inner function it has been declared and initialized in the outer function so that means the outer variable is being
accessed from the outer function that is the concept of closure now why to complicate it so much or what is even
the need for this closure functions in JavaScript is more like a compensation because in JavaScript there is no
official way by which you can declare private variables there is no concept of declaring private variables inside an
object that is why we need closures now as to answer the question why we need closures let's take a look at another
code um say I have a function called as uh counter now inside counter I have a variable called as
count now count is not exactly a now count is not exactly a private variable it's just a let variable which is
accessible inside the counter now let me just return a function called as
increment um by the way this is how when you're returning multiple functions or multiple outputs in a function this is a
default JavaScript uh syntax so inside this uh increment function I'm going to increase the value of count and it's
going to return count as well similarly I want to create a decrement function which will do the opposite of
this and we need a comma here and yeah okay and we also okay need a display count function which
will okay I need a message which will show the current count
as current count I'm going to return this message now let's just did what we did
before or let's just call it uh my counter which accesses this counter function
now this count has become a private variable which is only accessible which is only modifiable if you call onto the
counter function so in a nutshell if you have to modify this count variable it can only be done through the counter
function hence it's essentially been declared private now like I said there's no official method for declaring private
variables inside an object this is like the compensation for that so if I write my counter do increment
and then I write uh display the count it is increasing if I call this
first and then I show this initially the value was Zero we call increment and the value is one so if I call uh let's check
if decrement is also working okay okay decrement is also working so
that that is why we need this closure function again as a compensation for declaring for for javascript's inability
to declare private variables inside object we have closure functions let's move on to the next
question which is again another very common question in JavaScript interviews which is how do set timeout and set
interval work now set timeout and set interval are both which functions which are used to schedule tasks to run after
a specific amount of time and both of these are part of web apis which is provided by the browser or nodejs in a
server environment and they allow you to create delays or repeated actions in your code how do they differ though set
timeout is more is used to execute a function after a specific delay like if you want to send a particular
notification to your user after sometime um you must have seen how notifications come on your phone from certain apps in
a certain duration of time that is when you need set time out set interval is more like when you have to repeat the
same action after a period of time so that is like maybe rotating an image or something in JavaScript that is where
you use set interval let me just show you the code as to how to run them so I'll need to create a new file here 16th
question so first let's start with the set timeout set timeout works
as [Music] in say I'm going to
say hello after 2 seconds this code should run
after 2,000 milliseconds or 2 seconds if I run this code okay the hello was printed after 2 seconds that is after
the timer finished of 2 seconds this code got executed that is Timeout that is executing after the specified amount
of you can even add clear interval to this but for that you'll have to actually
like um create this inside a variable say timer ID inside of which I'm creating
this so if I clear the interval uh timer ID it has cleared the interval hence
this won't work because this was scheduled to work after 2 seconds but we uh cleared the interval before the 2
seconds could ever happen hence this didn't run now moving on to set interval which means set interval
is used when you have to run a particular code after certain intervals of
time so set interval this is hello after 2 seconds
this is hello after uh every 2 seconds and let's put the time here I can just comment it out that on
this cord right oh no no okay okay hello after 2 seconds hello after 2
seconds and it's just keep it will just keep on going now this is again where our clear interval comes into play uh if
you don't want this to happen if you don't want your code to constantly keep on running you need to clear the
interval now because this code will keep on going you need to call clear interval but like we saw earlier there's a
problem with clear interval if you try to run clear interval it will clear the interval before the code even has the
time to run so that is if I call this function here oh it's running and then I try to
run this I'm clearing the interval but because the timer ID the clear interval
is happening before this function can even execute it is clearing the whole interval hence this clear interval is
not allowing set interval to run so the problem with using clear interval is that it is running even before the timer
ID could start so what if I could specify the time as to when the clear interval should happen when the
notification should stop that is where you can add set time out that after the interval has run for maybe 5 minutes
clear it out stop the interval from running set timeout that is when you have to combine set timeout and set
interval together let me show you how so if I create a set time out here inside of which I'm going to call
this clear interval and this is going to happen say after 4 seconds so at least
for 4 seconds my set interval will be able to run okay all right it should only run once
yeah and after it's run only one time the code is getting stopped so that is how you combine set interval and set
timeout and make something useful out of your code this you can use for this is commonly used for your clock
applications and all where you need to fetch the time after every 1 second now let's move on to the next
question which is explain the concept of promise proes in JavaScript promises in JavaScript is similar to our promises
how it is used in other programming languages so promises handle asynchronous tasks in JavaScript by
providing a more readable and structured approach rather than call backs for handling outputs so the major reason why
we use promises is so that even if a particular request or maybe you were trying to fetch an API say if you were
creating a weather application and you want to make sure that you're when you're trying to fetch the weather API
for some reason you weren't able to fetch the API you your code shouldn't crash it needs to show something else
and with the help of promises you can make sure that every single time the code crashes or if the message fails you
will always have a backup and in a more elegant and uh decent way that is why you that is a major reason for you using
promises in mostly every programming language so promises are split into three parts pending fulfilled and
rejected pending is when the promises neither it it has run yet it just got initialized so we haven't got a request
yet fulfilled is if the promise was uh like if your API fetching was done successfully then the promise is
fulfilled successfully but the fetching if it got failed then the promise is rejected let me show you with the help
of the code I need to create a new file instead of API let's make it easier I'm just going to create a Json object
here uh with the name say John and the age of John is 30 now I'm going to create a function called as fetch
data which returns a new
promise which has a resolve and reject oh all right
now I'm going to create a time out here uh so the data should be fetched in 2 seconds if that fails the promise
fails if your if your code is not able to fetch this particular data within 2 seconds then we'll have to go to the
rejected part so now this function is done now if fetch data is promis was successful
then this data data uh will be logged into the
console data if the promise got fulfilled then the this block will be executed but if the promise got
rejected then the catch block will work which means it will throw an
error it will show whatever error has happened so now you can see how cleanly we're resolving the error if if if the
promise is fulfilled then this code will be executed else the catch block will be executed let's try to run it after 2
seconds the data is fetched and we can see it was a success then method was initialized however if within 2 seconds
the data is not being able to fetch then it's going to throw an error data is not defined that is the error
um so that's basically what you use promises for moving on to our next question which is a continuation of
previous question and you need to expect that if promises are asked then the question of async and await will be
asked as well so what is the use of async and await in JavaScript so async is basically
declaring a function with async makes it return a promise now basically promise is like inside async and await so you
have to declare a function with async and then await is used when you pause the execution of the code until the
promise it's waiting for his result then Returns the result value now the benefit of using async await and promise
everything combined together is your code will wait like we used the set timeout in promise so your code will
wait for that to happen it's happening in the background and it will continue on with other activities now this is
like when you're installing an application from Play Store you're clicking on app stores is install uh
button so the app is getting installed in the background and while the app is getting installed you able to say open
WhatsApp or Instagram scroll through re you're able to do all the other tasks while the installation of that
particular app is happening in the background in your phone that is how asyn inovate works let me show you the
code for this as well so this is question 18 all right so for this uh a weight is declared inside
an Asing sync function so if I'm calling a function I need to use the async keyword I'm going to call this fetch
data there are no parameters for this one let's add a dry block now this is going to a wait um
this time not fetch data it's just fetch let's call an a API for that uh this is
the one I use a lot Jason typ code.com let me take that API and uh go back to my
code place it here now we're going to fetch values from this but we need to add something
else 22s one or else it won't know what to fetch all right now
uh data uh let's create a variable data which will keep the response do Json response is what we're
getting from here inside of data we're storing the result of this uh now if this doesn't
work we can write a catch block and then just log on to the error or maybe we can just oh no we need
to write it all right let's just write error so that we'll know it's an error from our side all right now towards the
end and all we need to do is fetch the data and hope that everything is working and the data fetching was successful but
we didn't write anything here data fetched all
right and we need to show the data as well and this is the data that we fetched from that API um now if
something were to go wrong say if I don't I write something like this and then I try to run it
oh God that is an actual thing okay okay I'll write it like this yeah now that is an error so this is our error with
whatever error was given by the code that is how your async and await works now if you see closely in this code you
can see we call the response we are waiting for the Fetch and once the fetch is happened we are passing it into Json
format and we're pasting the data over here moving on to our next question which
is what is the difference between call apply and bind to understand this better let's take a
example say you and your family went to a restaurant to eat food now call is when you order a particular food and the
waiter uh goes to the kitchen to talk with the chef say you ordered you wanted to eat rice and beans now the waiter
goes to the kitchen and he has to tell every single order individually so you will say Chef cook for Adam with
ingredients rice then the chef will come back to you you will tell the next ingredient that is beans then the chef
will go back to the kitchen again and this time they'll say oh the next item which is beans so what happens in call
is that you specify the parameters one by one it's not specified together rather it is specified one at a time let
me show you in code how that is working all right so say I have a function cook which uh takes ingredient ingredients
one and ingredients two this function cook is basically our Chef uh the chef in the kitchen and it
will log onto the console uh I'll show you what this is later but
just beer with me right now is having a me with ingredient
one and ingredient two okay
now let me just create a guy called as Adam whose name is Adam this is an object where we're storing the name as
Adam and this name is being used here now I'm going to call cook this function call with the object Adam now the
parameters I'm going to give it one by one rice next parameter beans and this comma specifies the we coming back to
you taking the next order and then going back that is one by one and if I need another ingredient which is not pretty
much accepting if I write an ingredient three then I'll need to write it here and U say
water so it will be specified one by one so now if you try to run this code
you'll see that this particular line this do name is having a meal with whatever ingredients we specified is
being printed here so that's basically how call works it calls the parameters one by one next we have bind
um all right here's the technical definition so call invokes the function immediately with this set to this ARs
and accept arguments one by one moving on we have apply now apply is more like instead of coming to you and then taking
your order and then going back to the chef and then telling her the order this waiter can note it down like normal
waiters do they noted down all of your ingredients that is in the form of a list so this guy can go to the chef and
say Chef cook for Adams with ingredients rice and beans that is inside a list if you look closely enough this is a list
so when you look at this in code format um this would be apply and this whole thing will be
wrapped in a list um instead of specifying this one by one you can specify it in a list when it comes to
apply lastly U let's just look at the technical
definition so for technical definition apply is it invokes the function immediately with this set to this ARS
but takes argument as an array instead of taking the arguments one by one it takes the argument all at
once next we have bind now instead of taking it in the list format you just tell the Chef
that okay this is the list of ingredients that we have this is the food that you need to cook and you can
cook it whenever you're free like in a practical scenario the chef will be cooking something it's not like the
waiter will just go there give some ingredients and the chef will just throw the previous dish away and then cook the
new dish that's not what happens right so the chef Waits until the current dish is prepared and then she or he prepares
the next dish so that is what basically bind is it gives it ingredients but Waits and bind is not executed until and
unless you actually call it you can specify the ingredients call it later or you can specify the arguments and call
it later so let me show you in code so now bind I'll need to create a whole
variable let's call it cook for Adam this will be bind and uh say Adam uh and keep in mind that this is
again one by one again this same format uh we'll see take the same thing put it
here and now this is done this we have given the list and it's there okay this is the ingredients everything is ready
and we can call it whenever we want to yeah it will not be printed until you call it or it will not be executed until
you call it so that is what makes Bind different from both of these going back to the pbd
uh so technical definition bind returns a new function with this set to this ARs and add any present arguments but
doesn't invoke it immediately it is invoked whenever you think it should be invoked in your code so the basic
difference between the three of these call runs the function immediately passing each argument separately like
the rice beans and water apply runs immediately but takes the arguments in form of an array binds create new
function with present this and arguments this present this that we're talking about is the this do name that we used
and this you can call later now you might have a very good question here why do we need to use these now you must
have heard about the this keyword we have already discussed as well so this keyword can be accessed globally
sometimes we need to explicitly make sure where to point to and that is when use all three of these because even if
you look at the code here you can see that we're making sure that the this keyword is pointing to the name right
here and we're providing it there so that is why we need these moving on to the next question
what is event delegation now event delegation is a technique that allows you to manage
events for multiple elements more efficiently by using a single event listener on a common parent element
rather than on each individual child elements now we already discussed about event capturing and event bubbling event
delegation is something that utilizes event bubbling and event capturing or more precisely it is what utilizes event
bubbling capability so in case of event bubbling we already saw how when we were clicking the inner element the mid
element and the outer element were also getting clicked at the same time so instead of specifying an event listener
to the inner element and then to the mid element and to the outer element if I were to add a common event listener to
all three of this so wait let me just open the code so instead of doing it this way because even even if I am doing
the inner div this mid div and top div will get affected anyways so if I have to add a specific say event listener or
maybe when I click on that inner div the mid div and outer div also need to get affected I can just add if I add a
certain kind of pro property inside this inner div anyways this mid div and top div will get affected so instead of
specifying the three of them differently I can combine them together and that particular property of JavaScript is is
known as event delegation Okay the reason why we use event delegation is because it improves the performance it
handles Dynamic events like I said um instead of specifying one by one you can specify it for together so the best part
about this is that even if I were to add say if in the middle I were to add another uh mid and uh then if I were to
wrap this div up inside this div then again due to event bubbling even though I'm
not adding any event listener to this div and I've just added this the because of the event bubbling property this will
also get affected that is whatever event listener have attached to this inner div will be affected for this
another mid mid and top div and no matter how many Dives I add in the middle every single thing will get
affected so I I don't have to manually specify for every single divid it's happening
dynamically um that is what handles Dynamic elements mean and then we also have cleaner code obviously if I have to
write uh add an event list for every single line it's going to be really big but because of even delegation I can
compress it and put it all in one single line now let me show you how much easier even listener can make your lives
so um this is question number 20 now first let's try to run a course without event listener so that I can
show you how efficient it is inside uh inside this I'm going to create a div box and uh inside of this I'm going to
create a UL with the ID item list next I need a list with uh item one item two item three uh now for the
JavaScript part I will have to select it DOC you oh this is going to be hard
query selector all item
list Li item I miss my auto complete so
much item is okay now we're going to add an event listener for this one so we're selecting
these allies one by one with this query selector all inside the item list inside UL all these allies we're selecting them
one by one and that is what this const means here uh next we are adding a for each Loop where we are adding the event
listener to every single list inside of this UL uh so item do ad event
listener I pronounce it like that click function and
oh okay console.log cck this dot text context
content okay what is this what did I do wrong so now if I try to run this all right
we need the console okay so it has successfully been applied so that is how your code Works
without even delegation now if I were to apply event delegation to this code uh now this is easier if the code is very
small as in case of this particular code because we only have three elements so adding it to the same list over here
doesn't complicate anything much so in this particular code right now it's just the LI elements and it's very small code
hence it's not too overly complicated so this is fine this will make it work but what if the code was a bit more complex
and complicated then this thing might become too hectic especially query selector all is not exactly something
you are suggested to use right so that's why we add even delegation here now let me show you how even delegation makes
this so much more simpler uh we still need this but instead of uh getting the list elements we will Target the UL list
elements because anyways because of event bubbling this will also get triggered so we will uh select
the item list ID we don't need that okay now items
dot instead of the for Loop We'll add an event list now I'll remove the whole
thing and uh we're going to detect The Click event then we'll add a function with an event
e and uh if e. Target do tag name is equals to
Li then we log click and uh e do Target
dot t text content all right okay and it's working again okay now if you look at this code
we're using an add event listener instead of the for Loop that we used earlier let me just copy
that and I'll just put the okay I'll compare them side by side so that it's easier for you H now you
can see it's an ad event listener here which obviously improves the performance drastically and again like I said before
also if it's a small code it doesn't matter a lot but if it's a really long complicated code then your performance
really does matter and that is exactly why event delegation is happening so I hope that was enough to clear what event
delegation is let's move on to our next question which is explain the event Loop in JavaScript
now um let's consider an analogy for you to understand this so say you have a chef our chef from earlier event looping
is similar to your apps installing in the background and how your phone still keeps on working even if the apps are
working in the background so to understand event Loop in JavaScript better let's take an example so we have
this chef and kitchen from earlier now say our Chef is boiling water in the beginning now the chef also has to chop
the vegetables at the same time but now the problem is if she puts water to boil obviously it will take some time so she
can cannot just stand there and watch the water getting boiled she has to do other stuff as well that is exactly how
event looping works so by the time the water gets boiled she can go around and chop the vegetables now who makes sure
that the water is boiled and the vegetables are cut that is when the assistant comes in the assistant keeps
on going around and checking that if the vegetable chopping is done is the boiling water done and if it's done
he'll signal the main thread or the main Chef that uh the particular event has been completed so that the chef can go
and finish wrap that up completely like the water has boiled so the assistant will inform the chef that the water has
boiled so the chef will go take the water out and then proceed with the other activities so boil water till that
time chop the vegetables then make pasta then add vegetable it's like a whole process and this this assistant is the
arrow which keeps on checking which one is done so as the chef keep on adding more task like boiling the water
chopping the vegetable making pasta the assistant goes around and keeps on checking is this done is boiling water
done is chopping the vegetable done have you added the vegetable that is what the assistant does and it keeps on going in
a loop that is called as an event Loop in JavaScript moving on to the next
question what is the difference between a promise and an async await function we have already discussed both promises and
Asing Coit but there is a difference between the two of them as well let me show you asyn AIT is like this main box
that you can see and promise is contained within that as in AIT the last time we used ASN AIT we did it with the
try and the catch block instead of the promise this time I'll show you how to use async and await with promise but
before that let's just look at the definition so async and await is basically inside these functions you can
use await to pause execution until the promise resolves and for promise promises are the building blocks that
Asing and awake work on top of but promises themselves don't enclose Asing a like I said uh promise is contained
within asnin AIT but it is not the other way around now let me just show you the code so that you will have a better
understanding this is question 22 uh now let me show you how how promises and as CID work very differently so say you
have a method called as fetch data one which returns a promise and uh this gives Result One and
this result one is further used for fetch data 2 which takes the parameter fetch Result
One and this further goes into another then which takes result two
and logs result to okay and finally you can
catch this if any error occurs you can do the error handling
here which will just log the error now this is how a promise looks like and this can keep on going forever right it
I can add multiple then then then then it just keeps on going and going so this now again looks not so clean and that is
exactly why we need async in a wig because this code will get a lot more cleaner if you use asyn C weight let me
show you how if you use asyn of weight this becomes a function uh and you have to
wrap this whole thing inside a function this whole thing will be gone this is like the last time we did
let's do it with try catch first result one is fetch data one
result two which takes the value of result one this is f data
2 then like we did last time we can just put result data 2 here and we can put our error catching statement here and
then all we need to do is fetch data this is not fetch data one this will be fetch
data you can just have all that code inside one single function and keep it tucked away neatly that is why acing
Coit is preferred a little bit more promises are also used but they are used inside Asing Coit promises being used
individually for complex and really long codes is quite rare so that's because of asyn and a providing much more cleaner
code and much more in increasing the readability async and await is preferred much higher to promises okay so if you
were to come back to the PBT asyn and await is just a more cleaner and readable way to handle
promises whereas promises are the underlying mechanism now moving on to the next question which
is describe the purpose of the reduce method in Array now reduce method is a very powerful method in uh in JavaScript
reduce method is basically used to again we talked about the map method reduce method is something close enough and
similar to that except when you're using the reduce method it is used to reduce an array to a single value by applying a
function on each element in the array when you use reduce method it takes two arguments the first one is your current
value and the second one will be your accumulator now let me just show you how reduce exactly Works in JavaScript
behind the scenes with the help of an example say we have an array called as numbers which again contains the values
from 1 to five now you have a current value you have the accumulator and the result the accumulators value is default
starting with zero you can keep whatever value you want to keep right now I am using reduce method to find the sum of
this particular array unlike map when you are using map you were applying a specific change to every single elements
in the array but with reduce I'm trying to find the sum of this array that is I'm trying to reduce the array so that
you can reduce to find the average of this array or the sum of this array or the median of this array that is what
you use reduce for unlike map now look at this code very clearly so that you will understand what exactly current
value is and what exactly accumulator is these two values you have to specify when you're using reduce So currently
our current value is one that is because the first value in our array is one hence the current value is one so if you
add one plus the accumulator accumulator is the default zero value or accumulator is you can say the sum right now if you
only add the first value it's 0o so 0 + 1 is 1 so the result is one next time your current value becomes two because
the pointer shifts to the next value inside your array hence the current value becomes two and the accumulator
the previous value was one because this is only one hence the one is here now the current value plus this previously
existing value gives you three hence accumulator becomes three and the current value becomes three also next 3
+ 3 gives you 6 6 go goes to the accumulator current value becomes 4 6 + 4 10 10 goes to the accumulator 5 5 + 10
15 and your final answer you get the result as 15 so if you were to look at this in
code format I I feel like you'll have a better understanding if I show you in the form of code
so we need a numbers array okay uh now I'm going to call a variable
called as sum numers dot I'm going to call it to reduce
accumulator or the current sum keeper and the current value uh this is going to return
accumulator plus the current value and here we can put the zero this zero is the current value or the default
value of accumulator so if I were to run this code it will give me answer 15 again you
can change the value of accumulator if I put this as default 10 then I believe it should be 25 yeah okay you can change
the default value here and this accumulator and current value I showed you how it works this is basically how
reduce works now let's look at why you should use reduce or why reduce is common L used in uh JavaScript the main
reason why reduce is used is because it's very concise again if I have to find the sum of the elements in the
array I have to iterate through it with the for Loop but with reduce it's again just simplified to one single line again
I can also change the initial value without creating a lot more additional variables and everything so that's why
we primarily use it again because it reduces down everything to one line of code versatile as in um you can use
reduce for a number of methods you can use it to find the average you can use it to find the sum the median etc etc
then functional programming you already uh if you were to look at this particular code you'll see that the
original numbers array is not affected we had created a new array called a sum in which the sum was stored so when it
comes to functional programming this provides a cleaner code as it doesn't touch the original
array moving on to the next question which is explain the concept of currying in JavaScript
now carrying in JavaScript is a concept in functional programming inside JavaScript where a function that takes
multiple arguments is transformed into a sequence of functions each accepting a single argument now I'll tell you where
this is useful so for example consider that you have a project in which you have to make a PPT for five animals or
maybe more than that any animals your tiger lion giraffe elephant or maybe deer you have to make PPS on all of them
you have to write about them maybe write 10 slides about all of these individual animals now naturally you're going to
use the same template for all these five animals now if You observe very closely or if you think very closely you will
notice that the PPT remains constant or the template that you're going to use for all the animals is going to stay
constant just the animals are going to keep on changing right their information the animals is name the animals is photo
only that is going to change but the template will be the same that is similar to how currying Works in
JavaScript in currying one factor Remains the Same or maybe more than one factors remain the same and then you can
make some of them constant and the other ones keep on changing so it keeps on changing dynamically part of it stays
static part of it stays Dynamic now this is again another very uh powerful method to improve the performance you know when
you talk about JavaScript performance is very important because websites needs to have a really good performance so that
is why JavaScript has all of these different terminologies and functions solely focused on improving the
performance and this is one such concept let me show you how curing Works in JavaScript okay I'll open
my okay this is the file say if I had a regular function uh so this is a function add now inside of this I'm
going to return another function which is B uh so inside again like our closures
example like when we discussed about closure outer function and an inner function similar concept return a +
b in closures you're not taking anything here but in uh case of this currying you're using an input in the inside
function as well and also we're directly returning the function here if you see closely now the benefit of this is if
say I'm going to fix this outer parameter this outer parameter is fixed regardless this B keeps on changing
outer parameter say I'm going to fix it to two Okay now uh or maybe let's put it as
multiply we're going to uh call this as double this is
double every single parameter passed into this double function is going to be doubled that is multiplied by two so
we're going to uh double to uh say we're going to multiply three now
this two is going to remain static because we know that every single time we have to multiply it by two so inside
this function I don't have to specify the value of a every single time because a will be two regardless doubling it
means multiplying it by two so two will be constant so I'm just going to keep this constant the first parameter a this
is a I'm just going to keep it constant then I'm going to give it three next time say I'll give it five which gives
me 10 that's how it works one function stays constant the other one you keep keep on giving now again this code is
very small so it doesn't really matter a lot but imagine like in case of that PP it would contain 10 different slides in
every single PP so if you have to create 10 ppts for like five different animals it will take 50 slides so instead of
creating 50 new slides you can use the same template for every single uh animal and that will only that means you only
have to create what 10 slides so that improves your performance a lot that's exactly how this is also working
okay now the reason why we use cutting so much is because it makes your code more flexible and reusable like I
discussed already moving on to the next question what is a generator function and how it is used this is another
interesting concept generator function is basically a function which can pause its in execution you must have used
while loop at least once in your life and got into an infinite Loop because that is so common when I used while loop
for the first time it just suddenly went to an infinite Loop and then it just goes out of control completely now it's
because it was my first time coding so the code wasn't that big hence it wasn't enough to crash my computer but imagine
if the code was like gigantic and then the while loop runs and infinite Loop runs what would have happened my system
would have just crashed completely right and Generator function is another one such concept which can prevent this from
happening because this basically just executes the function and pauses executes once and then it wa it's there
okay you call again then I'll execute that is why generator function generator function exists to solve such kind of
Errors so let me show you with the help of a code how this works so to declare a generator function
you write function star in finite sequence num equal to
1 while through yield oh God I didn't this is supposed to close here not like
this num and uh num is going to be Plus+ now imagine if I did this without generator function this would just keep
on going in a loop now because this is enclosed in a generator function I'll show you how this works I'll have to
call this so let's call it infinite sequence sequence do
next okay it's one I'll call it again and it's two see how my infinite
Loop is only uh moving when I'm calling it so if I were to create a for Loop here
say 10 times and uh
okay it only printed 10 times and that too because I called it for 10 times again for Loop is controlling Loop now I
know don't think like we're going to put while true and then you know put it like this I mean that is a
possibility you can try that and here's an infinite Loop don't do this you can do this but don't to
prevent this we have create a generator function so don't do this don't try to become over smart okay to solve the
problem of infinite Loops generator functions exist and you know how it looks so moving on to the next
question what are weak maps and weak sets in JavaScript now this is weak maps and weak sets after looking at the
definition you will be like why do you even want to study these because this is that kind of a concept but this is very
important I'll tell you why first let's look at the definition first let let me make sure that you don't like it so weak
map is a collection of key value pairs where the keys are required to be objects and weak sets is a collection of
unique object references that only stores objects and does not allow any Primitives I know it didn't make any
sense to you so let's look at another uh definition both weak map and weak set are non iterate atable have no size
property and are ideal for temporary data storage and memory efficient management of objects basically what
happens in both weak map and weak set is that you store value in Weak map and like the name set set does not allow uh
duplicate values so inside we set you can store unique values inside week map you can store anything you want to so
the reason why we use both of them is when we have to store temporary objects that is when you're working on something
and you need to must have heard about cash so the cash memory it's also a memory you need to store it somewhere
but that's temporary and as soon as your current whatever process you are working on as soon as that process ends you just
clear out the cache so for that time being you don't need to store it in some permanent variables you only need to
store it in some temporary space and that temporary space is called as week map or a week set let me show you how
both of these are written in code okay as for weak uh map it's
new Wick map and uh let's just create an object save with the
name Adam U and now let's add a key value pair because it's a map you need to add
a key value pair week map. uh set it's an object and Adam is an employee right now let's try to oh I did
something wrong oh I put equal to okay all right now week map. let's try to get it this
object so right now Adam is linked to employee but the moment I remove the reference I put it to null
this becomes undefined so that is what happens the moment it is its reference is every single object inside your
memory is referencing to a certain value so right now Adam was referencing to employee hence it was existing but now
it's referencing to null so the whole value is removed from your memory that is why we need weak maps for
understanding weak set let's just change this to weak set we set we set has
ADD and it has has has let's just remove that for now so
this is true weak set does have this object but if I put it like this that becomes false meaning we set
is also again the difference is that we set allows unique values we map doesn't and U it's again used for fire storing
temporary is like your cash moving on how does JavaScript handle memory
management memory management in JavaScript has broken down into two steps mainly two steps which is the
memory allocation part where uh there are two types of memory stack memory Heap Heap memory in stack memory mostly
your temporary variables are stored like your primitive data types like your number string Boolean null and undefine
like we talked about before these are temporary you create a number a variable and then you just throw it away after
some time don't need to store it forever so that's why they're stored in the stack memory or the temporary memory
then there are your non-primitive data types like your object function arrays these all are stored in the permanent
memory or the Heap memory now this is how memories are located for these primitive and non-primitive data types
next comes the garbage collection cleaning of this data so like I said in the previous question as well all the
variables say you have a next name flag all of these are variables that I created in my code all of these
reference to certain objects now you can see X is referencing to 10 name is ARA flag is true table Joker is not
referencing to anything that's null book data is referencing to an object you can see that this table Joker it's not
referencing to anything it's referencing to null so there's a s function in JavaScript which checks for the
variables which are not referencing to anything null means basically there's nothing it's void so hence this table
Joker or whatever variable which is not referencing to anything substantial like uh any object or any value that is
marked and then sometime later whatever variables are marked are swept away with the sweeper function hence that place is
left empty or cleaned for next variable that is how memory management memory allocation and delocation works in
JavaScript moving on to the next question describe the difference between shallow and deep copying shallow copying
is say you have a tree and you take a photograph of this tree now shallow copying what happens is if you make any
changes to the photo of the tree that same change will appear in the actual tree as well this is like a
cursed photograph if you do something with the photograph the tree will also be affected so that is shallow copying
so in technical definition in the shallow copy of an object the main properties are copied but any nested
objects or arrays are still linked to the original meaning if any changes you made it will be applied to the original
array as well but in case of deep copying say there's a tree you are able to replicate a clone of an exact clone
of the tree so that even if you were to make any changes like cut down the branch of the tree nothing will happen
to your original tree it will remain as it is or in technical terms with a deep copy every part of the object including
all the nested objects or arrays is fully copied ensuring the modification to the copy does not affect the original
one so if you were to look at the code for this one question
[Music] 28 oh so say you have an array called as an
original array or your tree uh so this is an I will call create create as an object so the name of
this oh sayon and the address is say
uh the city I'm going to put it as Delhi John lives in Delhi okay and that is closed if I were to create a shallow
copy of this there are two ways to create a shallow copy the first one wait I need
to write shallow copy here oh God why did I write shallow Co oh my God okay coopy okay this is shallow copy so there
are two ways to create a shallow copy the first one is using object do assign I'll show you
how Okay so object do assign create a new object and the or with the help of the original object or
you can create it using the spread operator you must have heard a lot about spread operator in JavaScript and I
really do like this one so all you have to do is just put three dots and then put original that's it so now the
problem with shallow copy is if I take this shallow copy do address. City and I change his
address to say new city any new city then if I try to keep in mind that I'm changing the address for the shallow
copy 2 the second shallow copy Creator it's not in the first one it's the second one so if I try to write the
original addresses City now if I try to console. log it it has been modified although I changed the value for the
second shallow copy the original value still got modified let me just remove all of that
now if I try to do uh deep copy instead which is for which you have to create a whole
object uh you're going to pass the Json array after stringifying the original basically what you're doing the
original AR is there you're putting it converting into a string first then you're passing it putting it together to
an object uh so that is the way you create a deep copy now deep copy I'm going to do the same
thing here address city is equals to New City and then if I try to console. log
it the original one is still the same uh however for uh deep copy it should it should have changed yeah the Deep copy
one is changed but the original one is unaffected that is the difference between deep copy and shallow copy
moving on to the next question which is what is javascript's strict mode and how is it
enabled in Java script it is a set of rules uh you know sometimes you get warnings but you ignore them you're like
oh it's just an orange or a yellow warning who guess and then sometime later down down the lane when you when
your code gets even more complicated that same yellow or orange line because of that a major code major error is
thrown and then your code doesn't work so to prevent that orange or yellow error strict mode exists now because of
strict mode it doesn't allow Undeclared variables re only property this is eliminates okay let's look at them all
of them one by one how strict mode prevents all of these so the first one is Undeclared variables all right so
this is question 29 so as for Undeclared variables it does not allow you to declare an
Undeclared variable let me show you how uh say I have an X as 10 now without using the strict mode if I try to access
X it will be printed however if I put UST strict here then it throws an error X is not defined
hence it cannot be used next this is for Undeclared variables okay let me just comment that
out next we have readon properties as for readon properties it throws errors if you if you create an
object which only allows read only properties if you try to modify that so if UST strict is not there you can do
that but if UST strict is there for read only properties you cannot modify the object let me show you how um let me
remove that for the time being if you want to know what this is this is called prettier this extension I
believe everybody must use it but yeah uh so we have an object an empty object now object. Define property
object prop value let's say 40 writeable no we're not going to give
it right access now even though we have given it uh we are not allowing right
Axis if I change the value value changed the value got changed it didn't even
throw an error uh now however if I enable us strict here cannot assign to read only properties of prop
object that's another use case of UST strict okay now we have the next one which is this as a global object now
there's a problem with this I'll show you what is the problem with this because of this problem with this
keyword we had that call bind and apply method because let me show you what happens if you do not tell this which
particular this to access uh so say you have a function show and then inside of that I'm just
calling this randomly I'm not saying anything I'm just calling this now I'm going to call this function
here disable this now see what is happening it's not an error but it's just showing every
single thing it's just printing out every single thing that this can possibly Point huh so it is defaulting
and showing me every single thing which is there in the window which made this as a global object so because I didn't
assign any particular value to this I didn't point this to point to something I didn't give a reference to this it is
just it became a global variable now this can cause data leaks to prevent this
undefined another now this this won't even throw an error and your this has officially become a global object and it
won't even throw an error that is the reason why UST strict is very important these are some of the instances when
ustri becomes very crucial okay next one eliminates with so with statement is disallowed as withd statement makes the
code harder and easier to predict and debug let me show you say you have with math console log s of 90 now this will
right or it will run but if you use UST strict now because withd statements make
the code a lot more unpr predictable and harder to debug you you stri just simply removes it doesn't let you use with
statement at all the next one that we have over here is secures
eval okay you strict Mak sure that the variables and functions that you're going to write inside
eval like this it does not leak outside because right now if I try to access this without the UST mode I can access
the value right but if I write UST strict I did oh X is not defined because it's inside
eval and ustri prevents this variable from getting outside all right moving on the next one that we have duplicates
in function okay without using ustri IF inside a function I call let's just call
it sum if I write like this I have I was supposed to write B here but I accidentally wrote a twice and then I'm
going to just simply return A+ A+ C if I try to call this 10 20 30 now keep in mind that
these two are same and I'm not using the UST strict it'll give me the answer 10 20 30 70 but
prevents duplicates inside functions and that summarizes the UST strict
now let's move on to our last question of this module that is explain the Observer battern and how it relates to
JavaScript now to understand what exactly obser a pattern is consider an example so we have an influencer who
creates content for a particular audience she has a huge fan base and everybody follows her now this
particular audience has subscribed to her maybe she has YouTube channel so they have subscribed to her YouTube
channel now because they subscribed to the YouTube channel every single time she brings out a new updates the people
who have subscribed to the channel they'll get the notifications on their mobile phones or whatever devices
they're using that is exactly how Observer pattern Works in JavaScript if you look at the definition the Observer
pattern is a design pattern in which an object called as a subject or an influencer maintains a list of its
dependents called The Observers or the audience and notifies them of any change typically through a broadcast mechanism
so in observer pattern we have an object or a subject and the subject observers now in if you come back to the example
your subject is the influencer and your Observer is the audience who has subscribed to your uh particular YouTube
channel and the notification mechanism is the Subscribe and the update now if you to look at the code code for
this question 30 uh say if you had a button it's not here I'm just U this is
just an hypothetical example this is how it will look in real code though but right now in this HTML I haven't
specified any buttons this is not an HTML this is a Javascript file if you want to you can link an HTML file to
this and add button so say this is an observer one that is your audience one
uh Observer one notification notified let's right
similarly this can be done for Observer Observer to as well and this can just
keep on going next we can add a EV listener so you have the first one and then the second one you can even create
it for Observer two and you can keep on adding as many Observer one 2 3 4 however one you can add however one you
want or you can even create a main function which will rapidly create observers based on the traffic that is
coming to your website so this ad event listener is acting as your notification system which is sending the notification
to every single audience who have subscribed so that is how the whole Observer pattern Works in JavaScript and
that brings us to the end of this particular session thank you so much for watching
[Music]
In JavaScript, var is function-scoped and can lead to unexpected behavior due to its hoisting and global accessibility. let is block-scoped and mutable, making it safer for variable declaration within blocks. const is also block-scoped but prevents reassignment, enforcing immutability for the variable reference, which helps write safer and more predictable code.
Closures occur when an inner function retains access to variables from its outer function's scope even after the outer function has finished executing. This allows for data encapsulation and creation of private variables, enabling more modular and secure code patterns such as function factories and callbacks.
The == operator compares values after performing type coercion, meaning it converts the operands to a common type before comparison. Conversely, === performs a strict comparison, checking both value and type without conversion, which helps avoid unexpected bugs related to type coercion.
The event loop manages the execution of asynchronous callbacks by monitoring the call stack and the callback queue. When the call stack is empty, it dequeues callbacks from the queue and executes them, allowing non-blocking operations and enabling JavaScript to handle asynchronous tasks efficiently despite being single-threaded.
Promises represent the eventual completion (fulfillment or rejection) of an asynchronous operation, providing cleaner alternatives to nested callbacks. async/await build on Promises by allowing developers to write asynchronous code that appears synchronous, improving readability and making complex asynchronous flow easier to manage and debug.
A shallow copy duplicates only the top-level properties of an object, meaning nested objects remain referenced and changes affect both copies. A deep copy replicates all levels of the object, including nested objects, ensuring completely independent copies and preventing side effects when modifying data structures.
Event delegation involves attaching a single event listener to a parent element to handle events triggered by its child elements, leveraging event bubbling. This approach reduces memory consumption by minimizing the number of event listeners, simplifies dynamic content handling, and improves performance in complex DOM trees.
Heads up!
This summary and transcript were automatically generated using AI with the Free YouTube Transcript Summary Tool by LunaNotes.
Generate a summary for freeRelated Summaries
Top 10 Angular Interview Questions for Beginners and Juniors
Master the top 10 Angular interview questions designed for candidates with 0-2 years experience. Learn key concepts like Angular vs AngularJS, TypeScript advantages, components, modules, data binding, directives, lifecycle hooks, observables, and authentication to confidently crack your interview.
25 Essential Angular Interview Questions with Code Demonstrations
Explore 25 crucial Angular interview questions with detailed answers and code examples. This guide covers Angular basics, architecture, data binding, routing, lazy loading, services, dependency injection, and more to help you excel in your interview.
Complete JavaScript Beginner Course: Projects, Fundamentals, and API Integration
Learn JavaScript from scratch with practical projects including a digital clock, calculator, game, image slider, and a weather app fetching live data from APIs. This comprehensive course covers essential concepts like variables, functions, loops, objects, DOM manipulation, asynchronous programming, and more to build interactive web applications.
Top 50 Spring Boot Interview Questions and Answers Explained
This comprehensive guide covers the top 50 Spring Boot interview questions, including key concepts, features, advantages, and practical examples. Learn about Spring Boot architecture, configuration, starters, deployment, and best practices to excel in your Java developer interviews.
Comprehensive C++ Basics and Interview Prep with Striver's Resources
This video offers an in-depth introduction to C++ fundamentals, covering essential programming concepts like data types, conditional statements, loops, arrays, strings, and functions. Leveraging Striver's well-structured interview preparation sheets and courses, beginners and intermediates can build strong coding skills tailored for technical interviews. Practical coding demonstrations and tips enhance understanding and application.
Most Viewed Summaries
A Comprehensive Guide to Using Stable Diffusion Forge UI
Explore the Stable Diffusion Forge UI, customizable settings, models, and more to enhance your image generation experience.
Kolonyalismo at Imperyalismo: Ang Kasaysayan ng Pagsakop sa Pilipinas
Tuklasin ang kasaysayan ng kolonyalismo at imperyalismo sa Pilipinas sa pamamagitan ni Ferdinand Magellan.
Mastering Inpainting with Stable Diffusion: Fix Mistakes and Enhance Your Images
Learn to fix mistakes and enhance images with Stable Diffusion's inpainting features effectively.
Pamamaraan at Patakarang Kolonyal ng mga Espanyol sa Pilipinas
Tuklasin ang mga pamamaraan at patakaran ng mga Espanyol sa Pilipinas, at ang epekto nito sa mga Pilipino.
How to Install and Configure Forge: A New Stable Diffusion Web UI
Learn to install and configure the new Forge web UI for Stable Diffusion, with tips on models and settings.

