Search code examples
javascriptfunctionpass-by-reference

Function callbacks/copies, concept of passing by value/reference


I was in midst of reviewing some basic CS understandings but the question arose ;/ in my head.

I am wondering if there's an idea of passing by value or reference on 'functions'

Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. -quoted from developer.mozilla

My current understanding is flustered in that when a function is saved: I do not understand how functions are passed.

Considering anything that is not primitive type is object type in javascript, the block of code is passed as reference to the function name. However, I am also told that

'Javascript always pass by value so changing the value of the variable never changes the underlying primitive (String or number).'

so does it pass by value? or by reference? so here was my attempt to test the case out:

function example(){
console.log('hello');
}

here block of code 'console.log('hello")' is saved to function variable named 'example'

then in the case of

var example2 = example;

I expected function 'example' to be passed as value to 'example2'

so I tried to test if my hypothesis is true by testing:

function original(){
    console.log('hello');
}
var Original = original;
original();
Original();

function original(){
    console.log('Hello');
}
original();
Original();

I honestly expected result to be

hello
hello
Hello
Hello

but instead the actual result was

Hello
Hello
Hello
Hello

I thought it was passed by reference but after reading the comment I realized that it was hoisting problem;

so I ran

var original = function(){
    console.log('hello');
}
var Original = original;
original();
Original();

original = function(){
    console.log('Hello');
}
original();
Original();

and the result came out to be

hello
hello
Hello
hello

Solution

  • This is due to hoisting which is what happens when you use function declarations. If you use use function expressions, then what you expected will occur:

    var original = function(){
      console.log('hello');
    };
    var Original = original;
    original.value = 5;
    original();
    Original();
    
    original = function(){ // changes original to point to a new function (does not affect Original)
      console.log('Hello');
    }
    original();
    Original();
    console.log( Original.value );