KEMBAR78
JS SA Solution | PDF | Computer Programming | Software Engineering
0% found this document useful (0 votes)
203 views31 pages

JS SA Solution

The document contains a series of JavaScript questions and answers, focusing on concepts such as variable scope, regular expressions, and function behavior. Each question is followed by a detailed explanation of the correct answer, including code breakdowns and key points to remember. The document serves as a study guide for understanding JavaScript programming and testing with Jasmine.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
203 views31 pages

JS SA Solution

The document contains a series of JavaScript questions and answers, focusing on concepts such as variable scope, regular expressions, and function behavior. Each question is followed by a detailed explanation of the correct answer, including code breakdowns and key points to remember. The document serves as a study guide for understanding JavaScript programming and testing with Jasmine.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Question 1:

What will be the output on console when the below JavaScript code is run?

var myNumber = 111;

function updateMyNumber() {
var myNumber = 222;
myNumber = myNumber + 111;
}

updateMyNumber();
console.log(myNumber);

a) 222
b) 111
c) 333
d) Compilation Error

Correct Answer:
Option (b) 111

Concept Recap: JavaScript Function Scope (Local vs Global)

In JavaScript, variables declared using var inside a function are function-scoped, meaning they
are local to that function. They do not affect the variable with the same name outside the
function.

Step-by-Step Analysis:

1. var myNumber = 111;


→ Declares a global variable myNumber and assigns it 111.
2. The function updateMyNumber():
o Declares a local variable myNumber = 222;
o Then updates it to 222 + 111 = 333
o But this is all inside the function scope, so it does not affect the global
myNumber
3. updateMyNumber();
→ Calls the function, but it only works with the local copy of myNumber.
4. console.log(myNumber);
→ Refers to the global myNumber, which still holds the value 111.

Key Points to Remember:


• Variables declared with var inside a function are local to that function.
• The global variable remains unchanged unless explicitly modified (e.g., without var
or via return).
• JavaScript does not throw a compilation error in this case — it's perfectly valid
syntax.

Final Answer: Option (b)


The output is 111 because the global variable is unaffected by the local changes inside
the function.

Question 2:
What will be the output in the console for the following code?

var i = 999;

function myFunc() {
for (var i = 1; i <= 10; i++) {}
console.log(i);
}

myFunc();

a) Error
b) 10
c) 11
d) 999

Correct Answer:
Option (c) 11

Concept Recap: Variable Shadowing and Scope with var

• var is function-scoped, not block-scoped.


• Declaring var i inside the function creates a local variable that shadows the global
i.
• The for loop runs from i = 1 to i <= 10. After the loop ends, i becomes 11.

Step-by-Step Breakdown:
1. var i = 999;
→ Declares a global variable i and assigns it 999.
2. function myFunc() { ... }
o Inside this function, var i = 1; in the for loop shadows the global i.
o The loop executes as:
▪ i = 1 to i = 10
▪ Then i becomes 11, loop condition i <= 10 fails, and loop exits
o console.log(i); prints the local i, which is now 11.
3. Global i = 999 remains unchanged.

Key Points to Remember:

• var is function-scoped, so the i inside the function is not the same as the global i.
• After a for loop with var, the loop variable retains its final value.
• let would behave differently (block-scoped), but this uses var.

Final Answer: Option (c)


The console prints 11 because the local i declared in the loop increments beyond 10 and
retains its value.

Question 3:
Which of the following regular expressions will correctly match Indian PAN and fail if
provided input is not valid?
(Hint: Valid PAN formats include ABCDE1234F, VWXYZ6789Q)

a) /^[A-Z]{5}[\d]{4}[A-Z]$/
b) /^[A-Z]{5}[\d]{4}[A-Z]?$/
c) /^[\w]{5}[\d]{4}[A-Z]{1}$/
d) /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/

Correct Answer:
Option (a) /^[A-Z]{5}[\d]{4}[A-Z]$/
Also valid: Option (d) /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/

Concept Recap: PAN (Permanent Account Number) Format

An Indian PAN card number is a 10-character alphanumeric string with this format:
• First 5 characters: uppercase alphabets (A-Z)
• Next 4 characters: digits (0-9)
• Last character: an uppercase alphabet (A-Z)

Examples:

• ABCDE1234F
• VWXYZ6789Q

Option-by-Option Analysis:

Option Regex Explanation Valid?


a) /^[A-Z]{5}[\d]{4}[A- Matches 5 uppercase letters, 4
Z]$/
digits, 1 uppercase letter exactly Yes
b) /^[A-Z]{5}[\d]{4}[A- Last character is optional ([A-Z]?) No
Z]?$/
— may match only 9 characters
c) /^[\w]{5}[\d]{4}[A- \w includes lowercase, digits, No
Z]{1}$/
underscores — not strict enough
d) /^[A-Z]{5}[0-9]{4}[A- Same as (a), uses [0-9] instead of
Z]{1}$/
\d, which is equally valid Yes

Key Points to Remember:

• \d and [0-9] are equivalent for matching digits.


• ? makes the preceding character optional → not suitable when exact length is
required.
• \w matches [A-Za-z0-9_] → not strict enough for PAN.

Final Answer:
Both Option (a) /^[A-Z]{5}[\d]{4}[A-Z]$/ and Option (d) /^[A-Z]{5}[0-9]{4}[A-
Z]{1}$/ are correct.

If only one answer is allowed, go with:


Option (a) – commonly used and clean.

Question 4:
Which of the following REGEX will properly validate an Indian Mobile Number (10
digits, should start with 6/7/8/9)?
a) /^[6789]\d{9}$/
b) /^\d{10}$/
c) /^[^6-9]\d{9}$/
d) /^[6-9][0-9]{9}$/

Correct Answer:
Both Option (a) /^[6789]\d{9}$/ and Option (d) /^[6-9][0-9]{9}$/ are correct
If only one must be selected, prefer:
Option (d) – cleaner and more semantically accurate.

Concept Recap: Valid Indian Mobile Number Format

A valid Indian mobile number:

• Must be exactly 10 digits


• Must start with 6, 7, 8, or 9
• Must contain only digits

Option Analysis:

Option Regex Explanation


a) /^[6789]\d{9}$/ Starts with 6,7,8,9 + 9 digits → total 10 digits Valid
b) /^\d{10}$/ Accepts any 10-digit number, even starting Invalid
with 1–5
c) /^[^6-9]\d{9}$/ Starts with not 6–9 → the opposite of what's Invalid
needed
d) /^[6-9][0- Starts with 6–9, followed by 9 digits (0–9) Valid
9]{9}$/

Both (a) and (d) are correct, though (d) is more readable and explicitly matches the
requirement.

Key Notes:

• ^[6-9] → first digit must be 6, 7, 8, or 9


• [0-9]{9} or \d{9} → matches the next 9 digits
• Anchors ^ (start of string) and $ (end of string) ensure exact match
Final Answer:
Option (d) /^[6-9][0-9]{9}$/
It properly validates Indian mobile numbers — exactly 10 digits starting with 6, 7, 8, or
9.

Question 5:
What will be the output of the following JavaScript snippet?

var str = "The best things3 are free in life";


var pattern = new RegExp("[a-z]+[0-9]");
var result = pattern.exec(str);
console.log(result);

Options:

a) true
b) s3
c) The best things3 are free in life
d) things3

Correct Answer:
Option (d) things3

Concept Recap: RegExp.exec() in JavaScript

• The RegExp.exec(str) method searches a string for a match against a regular


expression pattern.
• It returns:
o An array with the matched string if found
o null if no match is found

Breakdown of the Regex:

/[a-z]+[0-9]/

• [a-z]+ → one or more lowercase letters


• [0-9] → exactly one digit
• Combined: Matches substrings like abc3, hello9, etc.
Input String:

"The best things3 are free in life"

• The substring things3 matches the pattern:


o things → [a-z]+
o 3 → [0-9]

Code Execution:

var result = pattern.exec(str);


console.log(result);

• exec() returns an array:


["things3"]
• When logged with console.log(result), it prints:
["things3"]

Key Points:

• The regex is case-sensitive (matches only lowercase letters).


• exec() gives the first match found in the string.
• The match is returned as an array; accessing result[0] would return the string directly.

Final Answer: Option (d)


things3 is the first substring that matches the pattern and is returned by exec().

Question 6:
What will be the console output for the code given below?

function good(greet) {
console.log("Good");
return greet;
}
function call(greet) {
console.log("Hi");
good(greet)();
}
function greet() {
console.log("Morning");
}
call(greet);

Options:

a) Hi Good
b) Hi Good Morning
c) Hi Morning Good
d) Hi Morning

Correct Answer:
Option (b) Hi Good Morning

Step-by-Step Execution:

Let’s analyze the function calls:

1. call(greet); is executed.
o Enters the call function.
o Prints "Hi" → Console: Hi
o Calls good(greet).
2. Inside good(greet):
o Prints "Good" → Console: Hi Good
o Returns the greet function (i.e., returns a reference to the function greet)
o So: good(greet)() → now becomes greet() (a function call)
3. greet():
o Prints "Morning" → Console: Hi Good Morning

Final Order of Console Outputs:

Hi
Good
Morning

Final Answer: Option (b)


The console outputs "Hi Good Morning" in order as each function executes.

Question 7:
What will be printed on the console when the below JavaScript code is run?

const myFunction = () => console.log("Hello ") || "World!";


let returnValue = myFunction();
console.log(returnValue);

Options:

a) Compilation Error
b) Hello
c) World
d) Hello World!

Correct Answer:
Option (c) World

Concept Recap: Logical OR (||) in JavaScript

• The || operator returns the first truthy value it encounters.


• If the left operand is falsy, it returns the right operand.
• console.log(...) returns undefined → which is falsy

Code Breakdown:

const myFunction = () => console.log("Hello ") || "World!";

• console.log("Hello ") → Prints "Hello " to the console


• But console.log(...) returns undefined (a falsy value)
• So the expression evaluates to:
→ undefined || "World!" → returns "World!"

Then:

let returnValue = myFunction(); // Logs "Hello ", returns "World!"


console.log(returnValue); // Prints "World!"

Console Output:

Hello
World!

• "Hello " is printed first (from inside console.log)


• "World!" is printed next (as the return value of the function)
Final Answer: Option (c)
Console prints "Hello " and then "World!" — final output is World (from the return
value).

Question 8:
What will be the output of the following JavaScript code snippet?

function emailFormat(email){
try {
if(email.match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/)) {
console.log("Matching the email format!!");
return true;
} else {
throw new Error("Email invalid!!");
}
} catch(error) {
console.log(error.message);
} finally {
console.log("Into the finally block!!");
}
}
console.log(emailFormat("hello.123@example.com"));

Options:

a) Matching the email format!! Into the finally block!!


b) Email invalid!! Into the finally block!!
c) Matching the email format!! Into the finally block!! true
d) true Matching the email format!! Into the finally block!!

Correct Answer:
Option (c) Matching the email format!! Into the finally block!! true

Concept Recap: Try-Catch-Finally and Return Behavior in JavaScript

• try block runs first.


• If a match occurs, the code prints:
"Matching the email format!!" and return true
• Even when a return occurs in try, the finally block is still executed.
• The return value is preserved after finally.
Step-by-Step Execution:

1. email.match(...)
hello.123@example.com matches the regex → Valid email
2. Inside try block:
o Logs: "Matching the email format!!"
o Executes return true
3. Before returning, finally block executes:
o Logs: "Into the finally block!!"
4. The function returns true, which is passed to:

console.log(emailFormat("hello.123@example.com"));

Logs: true

Final Console Output:

Matching the email format!!


Into the finally block!!
true

Final Answer: Option (c)


The correct output includes the success message, finally block log, and the returned
value true.

Question 9:
Which of the following test case will fail?

main.js file:

function modulus(value1, value2){


var result;
result = value1 % value2;
return result;
}

mainSpecs.js file (Jasmine Test Cases):

describe('Test Case Suite:', function() {


// Test Case 1
it("Test Case 1", function(){
expect(modulus(15, 7)).toEqual(1);
});

// Test Case 2
it("Test Case 2", function(){
expect(modulus(15, 8)).toBeGreaterThan(4);
});

// Test Case 3
it("Test Case 3", function(){
expect(modulus(15, 15)).toBeTruthy();
});

// Test Case 4
it("Test Case 4", function(){
expect(modulus(15, 15)).toBeDefined();
});

});

Function Logic Recap:

modulus(value1, value2) → returns value1 % value2

Now let's evaluate each test case one by one:

Test Case 1:

modulus(15, 7) → 15 % 7 = 1
expect(1).toEqual(1) → Pass

Test Case 2:

modulus(15, 8) → 15 % 8 = 7
expect(7).toBeGreaterThan(4) → Pass

Test Case 3:

modulus(15, 15) → 15 % 15 = 0
expect(0).toBeTruthy() → **Fails**

`0` is a **falsy** value in JavaScript


So `toBeTruthy()` will **fail** on 0
Test Case 4:

modulus(15, 15) → returns 0


expect(0).toBeDefined() → Pass

0 is defined — it's not `undefined`

Final Answer: Option (c)

Test Case 3 will fail because expect(0).toBeTruthy() is false — 0 is not truthy.

Question 10:
Which of the following regular expressions will be valid for all of the following list of
words?
Jack, John, James, Jasper, Judie

Options:

a) /[J|j][a-z]{3,5}/
b) /[a-z]+/
c) /[j|J][a-z]{4,6}/
d) /j[A-z]{4,6}/

Correct Answer:

Option (c) /[j|J][a-z]{4,6}/

Explanation of the Word List:

Words:

• Jack → 4 letters
• John → 4 letters
• James → 5 letters
• Jasper → 6 letters
• Judie → 5 letters

All start with uppercase J, followed by lowercase a–z letters


Total length ranges from 4 to 6 characters
So, a regex should:

• Match J or j
• Followed by 4 to 6 lowercase letters

Option-by-Option Analysis:

Option Meaning Valid? Why?


a) `/[J j][a-z]{3,5}/` Starts with J/j, then Incorrect
3–5 lowercase
letters
b) /[a- Matches any lowercase Incorrect Will match parts like "ack"
z]+/ letters from "Jack", but not full
names
c) `/[j J][a-z]{4,6}/` Starts with j or J, Correct
then 4–6 lowercase
letters
d) /j[A- Starts with lowercase j, Incorrect A-z includes symbols like
z]{4,6}/ followed by 4–6 [ \ ] ^ _ (non-letters)
characters in A-z due to ASCII range

⚠ A-z is not safe — use [A-Za-z] instead when matching only letters.

Final Answer:

Option (c) /[j|J][a-z]{4,6}/


Correctly matches all the names listed.

Question 11:
What will be the output in the console for the following JavaScript code?

let power = 666;

function man() {
power = 10;
console.log("Man's power is:", power);
}

function bat(spider) {
power = 30;
try {
spider();
} catch(e) {
power = 20;
}
console.log("Bat's power is:", power);
}

function spider() {
bat(man);
}

spider();

Options:

a) Man's power is: 10 Bat's power is: 10


b) Man's power is: 20 Bat's power is: 10
c) Man's power is: 10 Bat's power is: 20
d) Man's power is: 30 Bat's power is: 10

Correct Answer:

Option (a) Man's power is: 10 Bat's power is: 10

Step-by-Step Code Execution:

1. Global:
o power = 666 initially.
2. Call spider()
o Inside spider(), it calls bat(man).
3. Inside bat(man):
o First line: power = 30;
➔ Now power = 30
4. Inside bat(man), spider() is actually man (passed as argument):
o man() is called inside the try block.
5. Inside man():
o Sets power = 10;
o Logs: "Man's power is: 10"
6. Back to bat() after spider() (which is man()) executes:
o No exception was thrown → so catch block does NOT execute.
o Now, console.log("Bat's power is:", power);
o power is now 10 (set by man() earlier).
7. Final console output:

Man's power is: 10


Bat's power is: 10

Key Observations:
• bat(man) calls man() normally → no error → catch is skipped.
• power was modified globally at each step.
• No nested or hidden errors.

Final Answer: Option (a)


Man's power is: 10
Bat's power is: 10

Question 12:
Which of the following statements are true about arrow functions?

a) Curly Brackets {} are optional for multiple lines of code.


b) Curly Brackets {} are mandatory for multiple lines of code.
c) Parentheses () are optional for single parameter.
d) Parentheses () are mandatory for single parameter.

Correct Answers:
Option (b) Curly Brackets {} are mandatory for multiple lines of code.
Option (c) Parentheses () are optional for single parameter.

Concept Recap: Arrow Functions in JavaScript

Arrow functions (=>) are a concise syntax for writing function expressions.

Case Rule Example


Single-line, single No {} needed const sum = (a, b)
=> a + b;
expression
Multiple lines {} are mandatory, and you must use
return if returning a value
const sum = (a, b) => {
const result = a + b;
return result;
};

| Single parameter | () around the parameter are optional |

const greet = name => "Hello " + name;

| Zero or multiple parameters | () are mandatory |

const greet = (name, age) => {...};


const sayHello = () => "Hi!";

Option-by-Option Analysis:

Option Validity Explanation


a) Curly Brackets {} are optional for Incorrect — mandatory for
multiple lines of code multiple lines
b) Curly Brackets {} are mandatory for Correct
multiple lines of code
c) Parentheses () are optional for single Correct
parameter
d) Parentheses () are mandatory for Incorrect — optional for
single parameter single parameter

Key Points:

• Multiple lines = use {} and return


• Single line = no {} or return needed
• Single parameter = parentheses optional
• Zero or multiple parameters = parentheses mandatory

Final Answer:
Options (b) and (c) are true.
Curly Brackets {} are mandatory for multiple lines, and Parentheses () are optional for
a single parameter.

Question 13:
Which of the following Jasmine matchers should be used so that the test case passes?

main.js

var helloworld = function() {


return 'Hello World';
};

mainSpec.js

describe("Hello World", function(){


it("should Return Hello world", function(){
expect(helloworld()).__________('Hello World');
});
});

Options:

a) toBeTruthy()
b) toBeFalsy()
c) toBeEqualTo()
d) toEqual()

Correct Answer:

Option (d) toEqual()

Explanation of Jasmine Matchers:

Matcher Description
toEqual() Checks deep equality for primitive values and objects (like ===)
toBe() Checks strict equality (===) — also works here, but not an option
toBeTruthy() Passes if the result is truthy — does not check exact value
toBeFalsy() Passes if the result is falsy — clearly wrong in this case
toBeEqualTo() Invalid — not a real Jasmine matcher

Why toEqual() Works:

expect(helloworld()).toEqual('Hello World');

• helloworld() returns "Hello World"


• The test passes when the actual (helloworld()) equals the expected string ("Hello
World")

Why Other Options Are Wrong:

• a) toBeTruthy() → Just checks if value is truthy, not exact match


• b) toBeFalsy() → "Hello World" is truthy →
• c) toBeEqualTo() → Not a valid Jasmine matcher
• d) toEqual() → Correctly checks value equality
Final Answer: Option (d)
Use toEqual() to validate that helloworld() returns "Hello World" correctly in the
Jasmine test.

Question 14:
What will be the output in the console for the following code?

let i = 666;

function myFunc() {
for (let i = 1; i < 10; i++) {
}
console.log(i);
}

myFunc();

Options:

a) Error
b) 666
c) 10
d) 11

Correct Answer:

Option (a) Error

Explanation: JavaScript let and Block Scope

• let is block-scoped, unlike var which is function-scoped.


• In the function myFunc(), a new block-scoped let i is declared inside the for loop.
• This i exists only within the for loop block.
• After the loop ends, that block-scoped i is not accessible.

Step-by-Step Execution:

1. let i = 666;
→ Global variable i = 666.
2. function myFunc() defines a function that:

for (let i = 1; i < 10; i++) {


// i is scoped only within this loop
}

3. After the loop ends, when we try console.log(i);


→ It refers to i inside myFunc, but no such i exists outside the for loop.

This results in a ReferenceError:

ReferenceError: i is not defined

Key Point:

• let inside a loop does not leak outside the loop block.
• Trying to use that variable outside will cause an error.

Final Answer: Option (a)

ReferenceError occurs because i is not defined outside the loop block.

Question 15:
What will be the output in the console for the following code?

function bat(man, maxPower) {


power = maxPower;
try {
man();
} finally {
power = 400;
}
console.log(power);
}

function man() {
try {
throw new Error();
power = 100;
} catch(e) {
power = 200;
} finally {
power = 300;
}
}

bat(man, 100);
Correct Answer:

✔️ Option (c) 400

Step-by-Step Execution:

1. Global Context:

• No var, let, or const declared → All power = ... statements affect a global variable
called power.

2. Call: bat(man, 100)


function bat(man, maxPower) {
power = maxPower; // power = 100
try {
man(); // calls man()
} finally {
power = 400; // overrides power after man() finishes
}
console.log(power); // prints power
}

At this point:

• power = 100

3. Inside man() function:


function man() {
try {
throw new Error(); // error is thrown immediately
power = 100; // skipped
} catch(e) {
power = 200; // error caught → power = 200
} finally {
power = 300; // finally → power = 300
}
}

Execution inside man():

• throw new Error() is hit → jumps to catch


• catch sets power = 200
• finally runs → sets power = 300

So after man() completes: power = 300


4. Back in bat(), after man():

• finally in bat() sets power = 400

So, final console.log(power); → 400

Final Variable Trace:

Step Value of power


Initially —
bat sets 100
man → catch 200
man → finally 300
bat → finally 400
console.log 400

Final Answer: Option (c)

The final output is 400, due to the finally block in the bat() function overriding all earlier
changes.

Question 16:
What will be the output in the console for the following code?

function bat(man, maxPower) {


power = maxPower;
try {
man();
} finally {
let power = 400;
}
console.log(power);
}

function man() {
try {
throw new Error();
power = 100;
} catch(e) {
power = 200;
} finally {
power = 300;
}
}
bat(man, 100);

Correct Answer:

✔️ Option (a) 300

Step-by-Step Explanation:

🔹 Step 1: Global Context

• No variable power is declared with let, const, or var in the global scope.
• So all power = ... assignments create/modify a global variable named power.

🔹 Step 2: Call bat(man, 100)


power = maxPower; // power = 100 (global)
try {
man(); // call man()
}
finally {
let power = 400; // This is a **new block-scoped local variable**
inside finally
}
console.log(power);

• power = 100 (global)


• Then it calls man().

🔹 Step 3: Inside man()


try {
throw new Error(); // Error thrown immediately
power = 100; // skipped
} catch(e) {
power = 200; // caught → global power = 200
} finally {
power = 300; // finally → global power = 300
}

• So after man():
o Global power = 300

🔹 Step 4: Back in bat()


finally {
let power = 400;
}

• This declares a new block-scoped power inside finally, which is local and doesn't affect
the global power.
• Hence, global power remains 300.

🔹 Final Step:
console.log(power); // prints global `power`, which is 300

Final Output: 300

Key Takeaways:

• let power = 400; inside finally shadows the global power only within that block.
• The global power remains unchanged by this let declaration.
• man() modifies global power to 300.

Final Answer: Option (a)

The final value logged to the console is 300.

Question 17:
What will be the output in the console for the following JavaScript code?

javascript
CopyEdit
let power = 999;

function elephant(spider) {
let power = 50;
try {
spider();
} catch (e) {
power = 70;
}
console.log("Elephant's power is:", power);
}

function spider() {
elephant(tiger);
}
function tiger() {
power = 30;
console.log("Tiger's power is:", power);
}

spider();

Correct Answer:

✔️ Option (c) Tiger's power is: 30 Elephant's power is: 50

Step-by-Step Execution:

1. Global power = 999

• power is a global variable initialized with 999.

2. Call spider()

• Inside spider(), it calls elephant(tiger).

3. Inside elephant(tiger)
javascript
CopyEdit
let power = 50;
try {
spider(); // here 'spider' is 'tiger'
} catch (e) {
power = 70;
}
console.log("Elephant's power is:", power);

• let power = 50; (local to elephant function)


• Now, inside the try, spider() (which is tiger()) is called.

4. Inside tiger()
javascript
CopyEdit
power = 30;
console.log("Tiger's power is:", power);

• Which power?
o No let, const, or var is declared inside tiger().
o So it modifies the global power (from 999 to 30).

Prints:

Tiger's power is: 30

• No error is thrown inside tiger(), so the catch block inside elephant() does not
execute.

5. After tiger() returns:

• catch block is skipped (because no error).


• Control goes to console.log("Elephant's power is:", power);
• Which power?
o The let power = 50; declared inside elephant().
o So it prints:

Elephant's power is: 50

Final Output:

Tiger's power is: 30


Elephant's power is: 50

Final Answer: Option (c)


Tiger's power is: 30 Elephant's power is: 50

Question 18:
What will be printed in the console on successful execution of the below code
snippet?

function test() {
console.log(a);
console.log(foo());
var a = 1;
}
function foo() {
return 2;
}
test();
Options:

a) This code will throw an error


b) 2
c) 1 2
d) undefined 2

Correct Answer:

✔️ Option (d) undefined 2

Step-by-Step Execution:

1. Concept: Hoisting in JavaScript

• var declarations are hoisted (moved to the top of their scope), but their initialization
remains in place.
• Function declarations like foo() are fully hoisted with their definitions.

So after hoisting, the test function looks like:

function test() {
var a; // hoisted and initialized as undefined
console.log(a); // prints undefined
console.log(foo()); // prints 2
a = 1; // assignment happens here
}

2. Step-by-Step:

• console.log(a);
o a is declared (var a) but not assigned yet → prints undefined
• console.log(foo());
o foo() is hoisted and fully available → returns 2, so it prints 2

Summary:

Line Output

console.log(a); undefined

console.log(foo()); 2
Final Console Output:

undefined
2

Final Answer: Option (d)


undefined 2 is printed in the console.

Question 19:
What will be the output in the console for the following JavaScript code?

function man() {
power = 10;
console.log("Man's power is:", power);
}

function bat(spider) {
var power = 30;
try {
spider();
} catch(e) {
power = 20;
}
console.log("Bat's power is:", power);
}

function spider() {
bat(man);
}

spider();

Correct Answer:

✔️ Option (a) Man's power is: 10 Bat's power is: 30

Step-by-Step Execution:

1. What happens first?

• spider() is called.
2. Inside spider(), it calls bat(man).

3. Inside bat(man):
var power = 30;
try {
spider(); // here 'spider' is 'man'
} catch(e) {
power = 20;
}
console.log("Bat's power is:", power);

• var power = 30; — A local variable power is declared inside bat.


• Inside try, man() is called.

4. Inside man():
power = 10;
console.log("Man's power is:", power);

• Important:
o power = 10; — No var, let, or const is declared inside man().
o So global power (not the local power inside bat) is created/modified to 10.
• Then prints:

Man's power is: 10

• No error occurs, so catch block is skipped.

5. Back to bat(man):

• After man() finishes, catch is skipped (no exception).


• The local power inside bat is still 30.
• Then console.log("Bat's power is:", power); prints:

Bat's power is: 30

Important Variable Scope Clarification:

Scope Variable Name Value


Global power 10
Local (bat) power 30
• man() changes the global power.
• bat() uses its own local power for printing.

Final Console Output:

Man's power is: 10


Bat's power is: 30

Final Answer: Option (a)


Man's power is: 10 Bat's power is: 30

Question 20:
What will be the output of the below JavaScript code?

counts = [1, 2, 3, 4];


counts.map(_ => Math.pow(_, 2));
console.log(counts);

Options:

a) [1, 4, 9, 16]
b) []
c) [1, 2, 3, 4]
d) Compilation Error

Correct Answer:

✔️ Option (c) [1, 2, 3, 4]

Step-by-Step Explanation:

1. Code Behavior

• counts.map(_ => Math.pow(_, 2));


o map() returns a new array with the squared values.
o But — unless you store the returned array, the original counts array
remains unchanged.
counts.map(_ => Math.pow(_, 2));
// Returns [1, 4, 9, 16], but it is not assigned anywhere!

• Then console.log(counts);
o Prints the original counts array: [1, 2, 3, 4]

Important Concept:

• map() is non-mutating — it creates a new array without changing the original.


• To actually update counts, you would need:

counts = counts.map(_ => Math.pow(_, 2));

But in the given code, no reassignment happens, so counts stays [1, 2, 3, 4].

Final Console Output:

[1, 2, 3, 4]

Final Answer: Option (c)


[1, 2, 3, 4] is printed because map() does not modify the original array unless assigned.

You might also like