I see many articles and posts about javascript objects and primitives passed by refference vs passed by value. Though I don't see topic covering functions. Are they passed by value or refference. Therefore I made test myself to check it out.
Cosnider this example:
function sayHello() {
console.log("Hello")
}
function changeSayHello(func) {
func = function() {
console.log("Good Bye");
}
func();
}
sayHello(); // >> Hello
changeSayHello(sayHello); // >> Good Bye
sayHello(); // >> Hello
You can see the result by running the snippet. From this example I conclude that functions
in JavaScript are passed by value. What is your comment.
* EDIT * May be this better explains what I ment. And it shows that function is passed by refference?
var Obj = function() {
this.a = 5;
}
var change = function(func) {
func.prototype.b = 8;
}
var first = new Obj();
console.log(first.b); //undefined
change(Obj);
console.log(first.b);// 8
I don't see why this is marked as duplicate. I saw the proposed answer and there is no example about functions being passed as an argument.