JavaScript Interview Questions 6-10 (Scope, this, Functions, Closures)
Welcome to the second part of our JavaScript interview preparation series. In this lesson, we move slightly beyond the basics to explore how JavaScript handles structure and context. We will cover the difference between local and global scope, demystify the often confusing this keyword, compare function declarations with expressions, explore modern arrow functions, and finally, tackle the powerful concept of closures.
These topics often separate junior developers from intermediate ones. Don't worry if they feel abstract at first—we will use calm explanations and relatable analogies to make them stick.
6. What is the difference between local scope and global scope?
Scope determines where variables are accessible in your code. The two main categories are Global Scope and Local Scope.
- Global Scope: Variables declared outside of any function or block are global. They can be accessed from anywhere in your code.
- Local Scope: Variables declared inside a function or a block (like an if-statement or loop) are local. They are only accessible within that specific function or block.
Analogy: Think of Global Scope as the sky. Everyone, no matter where they are standing (inside a house or outside), can see the sky. Think of Local Scope as your living room. Only people inside your house can see what is in the living room; people outside cannot.
// Global variable (The Sky)
let globalVar = "I am visible everywhere";
function myHouse() {
// Local variable (The Living Room)
let localVar = "I am hidden inside the function";
console.log("Inside function:");
console.log(globalVar); // Works: Can see the sky from inside
console.log(localVar); // Works: We are in the room
}
myHouse();
console.log("Outside function:");
console.log(globalVar); // Works
// console.log(localVar); // Error! Cannot see inside the room from outside
Sample Output:
Inside function:
I am visible everywhere
I am hidden inside the function
Outside function:
I am visible everywhere
7. What is the "this" keyword in JavaScript?
The this keyword refers to the object that is currently executing the code. It gives functions access to their context. Its value depends entirely on how the function is called, not necessarily where it was defined.
- In an object method:
thisrefers to the object itself. - Alone or in a global function:
thisrefers to the global object (window in browsers), orundefinedin strict mode. - In an event listener:
thisrefers to the element that received the event.
Analogy: Think of this as the word "my". If I say "my computer," I mean mine. If you say "my computer," you mean yours. The word "my" is the same, but who it refers to changes depending on the speaker (the context).
const person = {
name: "Alice",
greet: function() {
// Here, 'this' refers to the 'person' object
console.log("Hello, " + this.name);
}
};
person.greet(); // "Hello, Alice"
const greetFunction = person.greet;
// When assigned to a variable and called alone, context is lost
// In strict mode (common in modern JS), this would be undefined
try {
greetFunction();
} catch (e) {
console.log("Context lost! 'this' is undefined or global.");
}
Sample Output:
Hello, Alice
Context lost! 'this' is undefined or global.
8. What is the difference between function declarations and function expressions?
While both define functions, they behave differently regarding hoisting (when they are loaded).
| Feature | Function Declaration | Function Expression |
|---|---|---|
| Syntax | function name() {} | const name = function() {} |
| Hoisting | Hoisted (Can be called before definition) | Not hoisted (Must be defined before calling) |
// 1. Function Declaration
// Works because the entire function is hoisted to the top
sayHello();
function sayHello() {
console.log("Hello from Declaration!");
}
// 2. Function Expression
// This would cause an error: ReferenceError or TypeError
// sayBye();
const sayBye = function() {
console.log("Bye from Expression!");
};
sayBye(); // Works only after the line above runs
Sample Output:
Hello from Declaration!
Bye from Expression!
9. What are arrow functions and how are they different from regular functions?
Arrow functions were introduced in ES6 as a more concise way to write function expressions. However, they aren't just syntactic sugar; they handle the this keyword differently.
- Syntax: Uses the fat arrow
=>syntax. If there is one expression, explicitreturnand braces{}are optional. - "this" Binding: Regular functions define their own
thisbased on how they are called. Arrow functions do not have their ownthis; they inherit it from the parent scope (lexical scoping). - Usage: Great for callbacks and array methods (like map/filter) but cannot be used as constructors or object methods where you need dynamic context.
// Regular Function
const add = function(a, b) {
return a + b;
};
// Arrow Function (Implicit return)
const addArrow = (a, b) => a + b;
console.log(add(5, 3)); // 8
console.log(addArrow(5, 3)); // 8
// The 'this' difference
const obj = {
value: 10,
regular: function() {
// 'this' refers to obj
console.log("Regular:", this.value);
},
arrow: () => {
// 'this' refers to global/window scope, NOT obj
console.log("Arrow:", this.value);
}
};
obj.regular();
obj.arrow();
Note: In the output below, "Arrow: undefined" happens because arrow functions don't grab the object as their context.
Sample Output:
8
8
Regular: 10
Arrow: undefined
10. What are closures in JavaScript?
A closure is created when a function is defined inside another function, and the inner function continues to access variables from the outer function even after the outer function has finished executing.
Analogy: Imagine a backpack. You pack your lunch (variables) inside your house (outer function). Even when you leave the house (outer function finishes), the backpack still holds the lunch. The function "closes over" the data it needs and carries it along.
Closures are widely used for data privacy and creating function factories.
function createCounter() {
let count = 0; // This variable is 'private' to the returned function
return function() {
count++;
return "Count is " + count;
};
}
// createCounter finishes running here...
const counterA = createCounter();
const counterB = createCounter();
// ...but counterA still remembers 'count' from its specific creation
console.log(counterA()); // Count is 1
console.log(counterA()); // Count is 2
console.log(counterA()); // Count is 3
// counterB has its own separate closure (backpack)
console.log(counterB()); // Count is 1
Sample Output:
Count is 1
Count is 2
Count is 3
Count is 1
You have now covered five more critical JavaScript concepts! From understanding where your variables live (scope) to mastering the behavior of functions and the power of closures. These are frequent topics in interviews because they demonstrate that you understand how JavaScript works under the hood, not just how to write syntax.