Javascript Interview Questions ( Var, Let and Const ) - Hoisting, Scoping, Shadowing and more
Summary
TLDRThis video script discusses the intricacies of variable declaration in JavaScript, focusing on 'var', 'let', and 'const'. It explains scope, shadowing, and hoisting, highlighting how 'var' is function-scoped and can be redeclared, while 'let' and 'const' are block-scoped and cannot. The script delves into the temporal dead zone and the importance of understanding execution context. Aimed at interview preparation, it provides insights into common interview questions and the impact of variable declaration on JavaScript's behavior.
Takeaways
- 📚 JavaScript has three ways to declare variables: `var`, `let`, and `const`, with `var` being the oldest and `let` and `const` introduced in ES6 to overcome some limitations of `var`.
- 🔍 Scope is a critical concept in JavaScript, defining regions where variables can be recognized; it can be global, functional, or block scope.
- 🚫 The `var` keyword declares variables with function scope or global scope, allowing for redeclaration without error, unlike `let` and `const` which are block-scoped and do not allow redeclaration in the same scope.
- 🔑 Variable shadowing occurs when a variable declared with the same name in a inner scope takes precedence over an outer scope variable, which is allowed with `var` but not with `let` or `const` in the opposite scenario.
- 🚫 `let` and `const` must be initialized at the time of declaration, unlike `var` which can be declared without initialization.
- 🔄 Variables declared with `var` and `let` can be updated or reassigned, but `const` variables cannot be updated once initialized, attempting to do so results in an error.
- 💡 Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the creation phase, but `let` and `const` are in the 'Temporal Dead Zone' until they are initialized.
- 🛑 The 'Temporal Dead Zone' (TDZ) is a period between declaration and initialization where `let` and `const` variables are in scope but cannot be accessed, leading to ReferenceError if attempted to be used before initialization.
- 🤔 Interviewers often use questions about variable declaration, scope, hoisting, and TDZ to evaluate a candidate's understanding of JavaScript fundamentals.
- 📈 The order of execution in JavaScript involves a creation phase where the context is set up, including hoisting, followed by an execution phase where the code is executed line by line.
- 🔍 Understanding the nuances between `var`, `let`, and `const` is essential for effective JavaScript coding and is a common topic in technical interviews.
Q & A
What are the three ways to declare variables in JavaScript?
-The three ways to declare variables in JavaScript are using 'var', 'let', and 'const'. 'var' has been in JavaScript since its inception, while 'let' and 'const' were introduced in ES6 to overcome some limitations of 'var'.
What is the concept of scope in JavaScript?
-Scope in JavaScript refers to the region of a program where a variable exists and can be accessed. Beyond this region, the variable cannot be recognized. There are different types of scopes such as global scope, block scope, and function scope.
How does 'var' differ from 'let' and 'const' in terms of scoping?
-'var' is function-scoped or globally-scoped if not declared within a function, whereas 'let' and 'const' are block-scoped, meaning they are only accessible within the block in which they are declared.
What is variable shadowing in JavaScript?
-Variable shadowing occurs when a local variable with the same name as a variable in an outer scope is declared, effectively 'shadowing' the outer variable within the inner scope.
Why is it called 'illegal shadowing' when trying to shadow a 'let' variable with a 'var'?
-It is called 'illegal shadowing' because you cannot redeclare a 'let' variable with a 'var' in the same scope, as 'let' is block-scoped and 'var' is function-scoped or globally-scoped, leading to a 'variable already declared' error.
Can 'var', 'let', and 'const' be redeclared in the same scope?
-Yes, 'var' can be redeclared multiple times in the same scope without error. However, 'let' and 'const' cannot be redeclared in the same scope due to their block-scoping rules.
Why must a 'const' variable be initialized at the time of declaration?
-A 'const' variable must be initialized at the time of declaration because it represents a constant value that cannot be reassigned. If not initialized, it would lead to an error stating 'missing initializer in const declaration'.
What is the difference between updating 'var' and 'let' variables compared to 'const' variables?
-Both 'var' and 'let' variables can be updated after their initial assignment, meaning their values can be changed. In contrast, 'const' variables cannot be updated or reassigned once declared, as they are constants.
What is hoisting in JavaScript and how does it relate to 'var', 'let', and 'const'?
-Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase. 'var' variables are hoisted to the top of their function or global scope, while 'let' and 'const' are placed in a 'temporal dead zone' until they are initialized.
What is the 'temporal dead zone' and how does it differ from hoisting?
-The 'temporal dead zone' is the period between the declaration and initialization of 'let' and 'const' variables. During this time, the variables are in scope but have not yet been initialized, leading to a reference error if accessed before the initialization. This differs from hoisting, where 'var' variables are hoisted with an initial value of 'undefined'.
What is the significance of understanding hoisting and the 'temporal dead zone' in JavaScript interviews?
-Understanding hoisting and the 'temporal dead zone' is significant because it demonstrates a deeper knowledge of JavaScript's execution context and variable scoping, which are common topics in technical interviews.
Outlines
📘 JavaScript Variable Declaration and Scope
This paragraph discusses the different ways to declare variables in JavaScript: 'var', 'let', and 'const'. It emphasizes the importance of understanding these concepts, especially in interviews, as they can set the tone for the rest of the interview. The paragraph explains the concept of scope, including global, functional, and block scopes, and how 'var' has function scope while 'let' and 'const' have block scope. It also introduces the concept of variable shadowing, where a variable declared with 'let' or 'const' can shadow a 'var' variable within the same scope, but not vice versa, leading to 'illegal shadowing' if attempted.
🛠 Variable Declaration Rules and Initialization
The second paragraph delves into the rules for declaring variables without initialization using 'var', 'let', and 'const'. It highlights that 'var' allows redeclaration and updating of variables, whereas 'let' and 'const' do not permit redeclaration within the same scope. 'Const' requires an initializer upon declaration and cannot be updated, unlike 'var' and 'let'. The paragraph also touches on the importance of understanding hoisting in JavaScript, explaining how variables and function declarations are moved to the top of their scope during the creation phase of the execution context.
🕵️♂️ Hoisting and the Temporal Dead Zone in JavaScript
This paragraph explores the concept of hoisting in JavaScript, explaining how variables and functions are treated during the execution context's creation phase. It contrasts 'var', which is hoisted and initialized with 'undefined', with 'let' and 'const', which are also hoisted but exist in a 'Temporal Dead Zone' until explicitly initialized. The explanation includes practical examples and potential interview questions that demonstrate the differences in behavior between 'var', 'let', and 'const'. The paragraph concludes with a real-world interview scenario that tests understanding of hoisting and the temporal dead zone.
Mindmap
Keywords
💡Variable Declaration
💡Scope
💡ES6
💡Block Scope
💡Global Scope
💡Variable Shadowing
💡Redeclaration
💡Initialization
💡Temporal Dead Zone
💡Hoisting
💡Execution Context
Highlights
Three ways to declare variables in JavaScript: 'var', 'let', and 'const'.
'var' has been in JavaScript since its inception, while 'let' and 'const' were introduced in ES6.
Interviewers often use scope-related questions to gauge a candidate's JavaScript knowledge.
Scope is the region of a program where a variable exists and can be recognized.
Types of scopes include global scope, block scope, and function scope.
'var' is function-scoped, while 'let' and 'const' are block-scoped.
Variable shadowing allows a variable to be re-declared within a block scope, but not vice versa.
Re-declaring a variable with 'var' is allowed, but not with 'let' or 'const'.
'const' requires an initializer and cannot be updated, unlike 'var' and 'let'.
Understanding JavaScript execution context is crucial for grasping hoisting.
Hoisting is the behavior of JavaScript where variable and function declarations are moved to the top of their containing scope during the compilation phase.
Temporal Dead Zone (TDZ) is a period between the declaration and initialization of 'let' and 'const' variables.
Accessing a 'let' or 'const' variable before its initialization results in a ReferenceError.
Interviewers may ask about the console output of functions involving 'var', 'let', and 'const' to test understanding of hoisting and TDZ.
The importance of hoisting in JavaScript interviews and how it affects variable and function declarations.
Call stack is a mechanism that tracks function calls in JavaScript.
The video discusses how to handle questions on hoisting and TDZ in JavaScript interviews.
Encouragement for viewers to follow the presenter on Twitter and subscribe to the channel for more content.
Invitation for viewers to comment on topics they would like to see covered in future videos.
Transcripts
where let and const three ways we can
declare variables in javascript and
there can be a ton of questions that can
be made on this topic when it comes to
interview so where existed in javascript
pretty much ever since it was created
and lit and const were introduced in es6
version of javascript to overcome some
of the limitations of wear so when i was
preparing for this video i had a
conversation with few interviewers and
they all told me that these type of
questions are generally asked at the
beginning of the interview and they
decide how the interview will go forward
so let's say if the candidate failed to
answer this question this can change the
flow of interview drastically the
interviewer can evaluate your javascript
knowledge based on these questions so in
this video i'll try to cover most types
of questions that can be made on this
topic so the first type of question that
can be asked is on scope so i've opened
html css and javascript files over here
and when i run this
yep
so let's get back to our javascript file
so first of all what is this thing
called scope so a scope is a certain
region of a program where a defined
variable exists and can be recognized
and beyond that it cannot be recognized
so there can be multiple types of scopes
for example global scope block scope
functional scope so for example we are
over here without any blocks or
functions so this is our global scope if
i create a function over here
this is our function scope
and if we create any other block over
here this will be our block scope so
when we talk about where so if i write
where
a
equals five
so this is in its global scope so it can
be accessed anywhere over here so if i
say console log a
if we go to browser yup you see five
output over here so where is functional
scope but let and const are block scoped
so let's see what that means so if we
create a block over here
and write where inside of it
you're going to see that this is still
accessible outside of this block
but when we change it to let
we're going to see reference error a is
not defined so this is only accessible
inside of this block so if i move this
inside of it
yup you're gonna see we are able to
access it and same is with const
it's accessible inside of it but when we
take it outside
nope a is not defined now there is
another concept that can be taken out of
this scoping which is called shadowing
so in javascript the introduction of lit
and const in es6 along with block
scoping allows variable shadowing so
what is variable shadowing if i write
this code you're going to see we have a
variable over here called hello and if
we print this over here it's going to
print hello yeah that's fine but if we
have a block scope over here inside of
this we say let a equals high let's say
what do you think is going to happen
this
a is going to shadow this a this will
overlap the value of this a but still
it's just going to be only accessible
inside of this block outside of this
block the a will still be hello so if i
run this
you're gonna see first we get high from
over here
and then hello from over here so this is
called variable shadowing now while
shadowing a variable it should not cross
the boundary of scope that is we can
shadow where variable by using let but
cannot do the opposite so if we try to
shadow let variable by where variable it
is known as illegal shadowing and it
gives us the error that variable is
already defined so let's check this out
now you're gonna see we if we try to
shadow where variable by using let it's
gonna work absolutely fine but when we
try to shadow let variable by using
where it's going to give us the error so
let's check this out if i run this
you're gonna see
b has been already declared so this is
called illegal shadowing and sometimes
all of these questions can be asked
together by the interviewer as an
extension to the scoping question now
the next type of question can be on
declaration how these three can be
declared so if we try to say where a
and then again say where a
then this is absolutely fine it's not
going to give us error we can redeclare
it as many times as we want
but when we say
let a
and
let a again
you're going to see that gives us the
error a has already been declared so we
cannot redeclare a variable by using let
and when we use const
it's again going to give us the same
error but it's giving us another error
missing initializer in const declaration
which we are going to discuss in our
next question so let in cons cannot be
redeclared in the same scope but where
can be redeclared in the same scope but
if we have something like this
and we say let over here
and we save this then this is completely
fine which we already discussed that
this comes under shadowing now the next
type of question can be declaration
without initialization so if i write
where a and we declare it just like this
then this is absolutely fine no problem
we can declare it without providing it
any value
okay so but if we try to do it with lit
then also this is completely fine but if
we do it with const
then this will give us error that
missing initializer in const declaration
we need to provide cons some value while
declaring it so it cannot be declared
without initializing it with any value
all right pause if you're not yet
following me on twitter go to
twitter.com push underscore eon or click
the link in the description down below
and hit that follow button right now
i'm waiting for you
i'm still waiting
okay fine let's continue with the video
now just like declaration there can be
questions on initializations as well so
can we re-initialize these variables
let's see so if we say where a equals
five
and we again try to say a equals six
yep that's fine we can do that
but what about lit
yup we can do that with let as well
but can we do that with const
no we cannot do that with cons
assignment to a constant variable we get
this error over here so where and lit
can be updated but const can never be
updated if done this will give us this
assignment to constant variable error
now the next type of question that can
be asked is on hosting and this is a
really really important topic 95 of
javascript interviews definitely have a
question on hosting but before
understanding hosting let's understand
how javascript execution context works
so what happens is when we try to
execute a js code there are two phases
one is a creation phase and the other is
execution phase so in creation phase
three things happen first it creates a
global or a window object so
i'm going to create a
window object representation over here
oh man i'm so bad at drawing the second
step is it setups a memory heap for
storing variables and function
references that means it takes all of
the variables and functions and stores
it inside of this window object and the
third step is that it initializes those
functions and variable declarations with
undefined so let's say we have first
variable as a so we're going to store a
second is our function which is multiply
so we stored multiply over here and the
third thing is our variable b
now the third step is that it
initializes them with undefined and for
the function declarations it takes the
whole complete function from here and
stores it inside of our window object
and this is the exact reason why hosting
occurs i'm going to talk about hosting
in just a minute but let's understand
what happens in the execution phase so
during the execution phase the
javascript engine executes the code line
by line assigning the values to
variables and executes the function
calls also for every new function
created javascript engine creates a new
execution context altogether we're gonna
talk about how function work with
execution context in another video of
this series for this video i'm gonna
focus on where let enconst so during the
execution phase javascript first assigns
the value of a which is 10 then it moves
on to variable b because the function
multiplier has not been executed yet so
it's not going to touch this function
then it takes b and assigns it with this
function execution so it's going to
execute the function with multiply x so
it's going to pass 10 to this and it's
going to multiply to provide it value
100 and then it's going to run this
console log b which is going to be the
output of 100. now javascript also uses
something called call stack which is a
mechanism to keep track of all of the
function calls which we will discuss in
our upcoming videos so now you know how
javascript execution context works let's
move forward to hosting so during the
creation phase javascript engine moves
your variables and function declarations
to the top of your code and this is
known as hosting if i declare a variable
called count and if i try to console log
it before it was declared
you're gonna see that we get undefined
we didn't get any error it should have
given us error right that the variable
is not declared yet but since we know
how the javascript execution context
works it declares all of these variables
and functions at the top of the code
during the creation phase and then when
the execution happens it checks if this
variable already exists during the
creation phase or not so obviously it
existed so it gives us undefined so how
javascript looks at this code is it
looks at like this
that yep where was already declared and
then we are console logging this and
then later we are initializing it okay
so this was the case of where right but
what happens in let
let's change this to let
are let variables hosted as well
well if you console log this you're
gonna see this error and you're gonna
say no they are not hosted but you're
wrong they are hosted they are hosted in
temporal dead zone we're going to talk
about that temporal dead zone in just a
minute but let's see what do we get over
here so we get cannot access count
before initialization so this basically
helps us overcome the limitations of
where so where didn't warn us about the
declaration but since we are using let
it says that we cannot access the count
before the initialization
now if we go
over here in the
sources
and put a breakpoint over here and when
then we try to run this
you're going to see
that inside of the script we have this
count as undefined whereas if we let's
try to declare another variable with var
count
two
two value
and if you go back and refresh this
you're gonna see in the global we have
this count two over here so this is
inside of our scope and this is
undefined so that's fine but you're
going to see we have a separate script
over here which has this count variable
which is inside of the temporal dead
zone so temporal dead zone is the time
between the declaration and the
initialization of let and const
variables so let's understand hosting by
understanding this question which was
asked to me in one of my previous
interviews so i've already made a video
on this so i'm going to play that clip
right over here so interviewer gave me
this function right here function abc
and he asked what is going to be the
console log of a so i want you to think
about this first before moving forward
because we are using where over here to
declare this variable so what's going to
happen is when this function is
initialized in our execution context
it's going to host this variable a and
the console log will be undefined so let
me show you real quick
if i say abc
and run this
you're gonna see that we get undefined
in the console so
yep you see we get this undefined now
why is that so if you go to sources
and right over here in the script.js i'm
going to put a breakpoint over here in
the console log a so now if i refresh
the page
you're going to see when the code
reaches over here a is undefined because
it has initialized this function but it
has not initialized this variable yet so
this variable a is undefined at this
moment but if the console log was after
this variable a then obviously it would
have printed the value of a which which
is going to be 10.
so now if i
put another breakpoint over here and say
move forward
now you're gonna see a is 10 right over
here when this function ends the value
of a will be 10 but since at this time
the value of a was undefined it's going
to print undefined
now then interviewer added few more
variables inside of this function
now then he asked me what is going to be
the console log for all of these three
values so obviously we know for a it's
going to be undefined but for b and c
what is it going to be because const and
led behave a little differently than
where are these two variables going to
be hosted as well
yes they are going to be hosted but they
are going to be hosted in temporal dead
zone so if i go back
and you're going to see we get this
error cannot access b before the
initialization so our constant let
variables are not hosted like where but
they are hosted in the temporal dead
zone so if i go
to sources so now if i put a debugger
over here and let's see here as well and
refresh this
you're gonna see that we still get b and
c undefined in our local scope but these
doesn't work like exactly like where
does these both will be initialized in
the temporal dead zone so what is
temporal dead zone you ask so temporal
dead zone is the term to describe the
state where variables are in the scope
but they are not yet declared
just like over here they are in the
scope but they have not been declared
yet so that's why b and c are going to
be in the temporal dead
zone so these were some of the major
types of questions that can be asked to
us during these javascript interviews
now obviously there can be more types of
questions that can be framed by using
lit wear and const do mention them in
the comments down below so that others
can know and i can make a video on them
in future so if you like this first
video of our javascript interview series
give this video a huge fat thumbs up and
subscribe to the channel for more such
awesome videos and let me know in the
comments down below which topic would
you like for me to cover next
浏览更多相关视频
Declaring Variables without Var, Let, Const - What Would Happen?
Hoisting in JavaScript 🔥(variables & functions) | Namaste JavaScript Ep. 3
Curso Javascript - #03 const vs let vs var
Immediately Invoked Function Expressions (IIFE) | JavaScript 🔥 | Lecture 127
local and global Scope in JavaScript | JavaScript Tutorial in Hindi #88
BLOCK SCOPE & Shadowing in JS 🔥| Namaste JavaScript 🙏 Ep. 9
5.0 / 5 (0 votes)