Someone can explain me in the following code, why when I do o = {}, the object is not being reset?
var funky = function (o) {
o.z = null;
o.a = "aaa";
o = {};
};
var x = { z: "zzz"};
funky(x);
console.log(x);
Because JavaScript doesn't pass by reference. It passes references by value.
The difference is subtle, but important. The gist of it is, the value of an object variable isn't an object; it is a reference to an object. Passing a variable passes a copy of that reference. With it you can modify the content of the object virtually at will, but you couldn't replace it with a whole other object in a way the caller could see.
o is just an alias to whatever it's currently pointing, it's not the instance (pass by value).
If you want to emulate "pass by reference", you can do it:
var x = { ... };
var container = { x: x };
funky(container);
Now you can reset it in funky():
container.x = {};
var x = ... inside your function. o = {}; doesn't modify the existing object, it creates a new one. o now points to the new object but there is no way to change x. So what you need is to put x into another object.There is neither pass-by-value nor pass-by-reference in JavaScript.
Identifier is binding to value. When call funky(x), parameter o is binding to the value of x, which is {z:"zzz"}.
When JavaScript interprets o.z=null and o.a="aaa", it updates the value of x(because it is binding to it).
When JavaScript interprets o = {}, it rebind o to {}. So, the output must be {z:null, a:"aaa"}, which is the value of x.
nullinstead.