What will the following JavaScript code output?(function() { var a = b = 5;})();console.log(b);5ReferenceError: b is not definednullundefined
Question
What will the following JavaScript code output?
(function() {
var a = b = 5;
})();
console.log(b);
- 5
- ReferenceError: b is not defined
- null
- undefined
Solution
The output of the JavaScript code will be 5
.
Here's the step-by-step explanation:
-
The code defines an immediately invoked function expression (IIFE) that sets
a
andb
to5
. -
The
var
keyword only applies toa
, makinga
a local variable within the function. -
b
is not declared withvar
, so it is set as a global variable. -
After the function is executed,
a
is discarded because it's local to the function, butb
remains because it's global. -
When
console.log(b)
is called outside of the function, it logs the global variableb
, which is5
.
Similar Questions
What is the output of following code?var a = 10;function test() { a = 20;}test();console.log(a);Options: Pick one correct answer from below1020
What is the output of this code?const a = 12;function myFunction(a) { console.log(a);}myFunction(89);112289
What is the output of this code?function myFunction(a) { console.log(a + b);}const b = 79;myFunction(10);
What will be the output of the following code snippet?var a = 1; var b = 0; while (a <= 3) { a++; b += a * 2; print(b); }*4 10 181 2 3None of Above1 4 7
What will the below statements print on the console?"use strict"function abc() {console.log(this);}abc();
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.