What is the output of the following JavaScript code?
function outer() { let x = 10; function inner() { let x = 20; return x; } return inner(); } console.log(outer());
Think about which x the inner function uses.
The inner function has its own x variable which shadows the outer one. So it returns 20.
What will be logged to the console when this code runs?
const obj = { value: 42, getValue: function() { return this.value; } }; const getValue = obj.getValue; console.log(getValue());
Consider what this refers to when the function is called alone.
When getValue is called without an object, this is undefined in strict mode, so this.value is undefined.
What is the output of this code snippet?
function test(a, b) { arguments[0] = 100; return a + b; } console.log(test(1, 2));
Remember how the arguments object relates to named parameters.
In non-strict mode, changing arguments[0] changes a. So a becomes 100, b is 2, sum is 102.
What will this code print?
const obj = { value: 10, arrowFunc: () => this.value, regularFunc() { return this.value; } }; console.log(obj.arrowFunc()); console.log(obj.regularFunc());
Think about how arrow functions handle this compared to regular functions.
Arrow functions do not have their own this, so this.value is undefined. Regular function uses object context, returns 10.
Consider this code. What will be the output and why?
function createCounter() { let count = 0; return function() { count += 1; return count; }; } const counter1 = createCounter(); const counter2 = createCounter(); console.log(counter1()); console.log(counter1()); console.log(counter2());
Each call to createCounter creates a new closure with its own count.
Each counter has its own count. counter1 increments twice (1 then 2), counter2 starts fresh at 1.