0
0
Javascriptprogramming~5 mins

Function scope in Javascript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is function scope in JavaScript?
Function scope means variables declared inside a function can only be used within that function. They are hidden from the outside world.
Click to reveal answer
beginner
What happens if you try to access a variable declared inside a function from outside that function?
You get a ReferenceError because the variable only exists inside the function's scope.
Click to reveal answer
beginner
Consider this code:<br><pre>function greet() {<br>  let message = 'Hi!';<br>  console.log(message);<br>}<br>greet();<br>console.log(message);</pre><br>What will happen when running it?
The function prints 'Hi!'. But the last line causes an error because message is not visible outside the function.
Click to reveal answer
beginner
Can variables declared with var inside a function be accessed outside the function?
No. Variables declared with var inside a function are also limited to that function's scope.
Click to reveal answer
intermediate
What is the difference between function scope and block scope?
Function scope limits variables to the whole function. Block scope limits variables to the block (like inside {}) where they are declared, usually with let or const.
Click to reveal answer
Where can a variable declared inside a function be accessed?
AOnly inside that function
BAnywhere in the program
COnly inside loops
DOnly inside if statements
What will happen if you try to access a function-scoped variable outside its function?
AIt will return the variable's value
BIt will create a new variable
CIt will print null
DIt will cause a <code>ReferenceError</code>
Which keyword creates a variable with function scope?
Avar
Bconst
Clet
Dfunction
What is the scope of a variable declared with let inside a function?
AGlobal scope
BFunction scope
CBlock scope inside the function
DNo scope
Which of these is true about function scope?
AVariables declared inside a function are accessible outside it
BVariables declared inside a function are hidden from outside
CFunction scope only applies to global variables
DFunction scope is the same as block scope
Explain function scope in JavaScript and how it controls variable visibility.
Think about where you can use variables declared inside a function.
You got /4 concepts.
    Describe the difference between function scope and block scope with examples.
    Consider how variables behave inside functions and inside blocks like if or loops.
    You got /4 concepts.