Question discussion

What is the output of the following JavaScript code?var x = 1; function f() { console.log(x); var x = 2; } f(); console.log(typeof f, [10,…

1135Medium DSSSB TGT Computer Science 0 replies 1 views
0

What is the output of the following JavaScript code?

var x = 1;
function f() { console.log(x); var x = 2; }
f();
console.log(typeof f, [10, 1, 3].sort());
  • Aundefined function [ 1, 10, 3 ]
  • B1 function [ 1, 3, 10 ]
  • Cundefined object [ 1, 3, 10 ]
  • D2 function [ 10, 1, 3 ]
Correct answer: A

Explanation

The local var x is hoisted, so the first log prints undefined; sort() without a comparator orders elements as strings, giving [1, 10, 3].

Discussion 0

Nobody has replied yet. Start the discussion!