Javascript - What is the output: reference type parameter passing?

Question

What is the output of the following code?

function setName(obj) {
    obj.name = "First";
    obj = new Object();
    obj.name = "newValue";
}

var person = new Object();
setName(person);
console.log(person.name);    


Click to view the answer

First

Note

The code redefined obj as a new object with a different name.

When person is passed into setName(), its name property is set to "First".

Then the variable obj is set to be a new object and its name property is set to "newValue".

When obj is overwritten inside the function, it becomes a pointer to a local object.

That local object is destroyed as soon as the function finishes executing.

Related Quiz