Intern
/* Given three sections of code. Write the output of each console.log. */ var n = 1; function f(n) { n = 3; } f(n); console.log(n); // ?? // ---------------- var obj = { a: 1 }; function f1(o) { o.a = 5; } f1(obj); console.log(obj); // ?? // ---------------- var obj = { a: 1 }; function f2(o) { o = { hello: 1 }; } f2(obj);
sobes.tech AI
Answer from AI
javascript var n = 1;
function f(n) { n = 3; // local variable n inside the function } f(n);
console.log(n); // 1
// ----------------
var obj = { a: 1 };
function f1(o) { o.a = 5; // changing the property of the object that o references } f1(obj);
console.log(obj); // { a: 5 }
// ----------------
var obj = { a: 1 };
function f2(o) { o = { hello: 1 }; // reassigning the local variable o, not changing the external object }
f2(obj);
console.log(obj); // { a: 1 }
Explanation:
- In the first case, the primitive `n` is passed by value, so changes inside the function do not affect the external variable.
- In the second case, the object is passed by reference, and changing its property inside the function affects the original object.
- In the third case, the variable `o` inside the function is reassigned to a new object, but this does not change the external object that the variable `obj` initially referenced.