Search code examples
javascriptfunction-pointers

Javascript Function-Pointer Assignment


Consider this javascript code:

var bar = function () { alert("A"); }
var foo = bar;
bar = function () { alert("B"); };
foo();

When running this code I get "A". Is this behavior a part of javascript specification and can I rely on it?


Solution

  • Yes that is expected and by design.

    Your question is basically: does foo reference bar as a pointer or reference would in another language?

    The answer is no: the value of bar at the time of assignment is assigned to foo.