Deal of The Day! Hurry Up, Grab the Special Discount - Save 25% - Ends In 00:00:00 Coupon code: SAVE25
Welcome to Pass4Success

- Free Preparation Discussions

Salesforce JS-Dev-101 Exam - Topic 2 Question 13 Discussion

Why does second have access to variable a?
B) Outer function's scope
A) Inner function's scope
C) Prototype Chain
D) Hoisting

Salesforce JS-Dev-101 Exam - Topic 2 Question 13 Discussion

Actual exam question for Salesforce's JS-Dev-101 exam
Question #: 13
Topic #: 2
[All JS-Dev-101 Questions]

Why does second have access to variable a?

Show Suggested Answer Hide Answer
Suggested Answer: B

The answer is B because JavaScript uses lexical scope.

When a function is created inside another function, the inner function can access variables from the outer function where it was defined.

For example:

function first() {

let a = 10;

function second() {

console.log(a);

}

second();

}

Here, a belongs to the outer function first(). The inner function second() can access it because JavaScript looks for variables through the scope chain.

The lookup works like this:

1. Look inside second()

2. If not found, look inside first()

3. If not found, look in the global scope

Since a is found in the outer function's scope, second() can use it.

This is also the basis of a closure. A closure allows an inner function to remember and access variables from its outer lexical environment.

Why the other options are incorrect:

A is not the best answer because a is not declared inside second() itself.

C is incorrect because the prototype chain is used for object property lookup, not local variable scope lookup.

D is incorrect because hoisting explains how declarations are moved during compilation, but it does not explain why an inner function can access an outer function's variable.

Therefore, the verified answer is B.


Contribute your Thoughts:

0/2000 characters

Currently there are no comments in this discussion, be the first to comment!


Save Cancel