2018-May-15: The Great Variable Hoist

<– Back to all “Work Diary” entries

Not sure how I’ve never run into this before, but apparently in JS if you have a function foo() and a variable named foo, the variable can overwrite the function and cause it to be undefined, like so:

function foo() {
  console.log('hi');
}

var foo = foo();

Console will complain that, “foo is not a function”. Apparently this is a well-documented feature of JS called “variable hoisting” [1].

In Other Languages…

Tried similar code snippets in PHP and Ruby and they both have no issues when a function and a variable share names.

PHP

function foo() {
    echo 'hi';
}

$foo = foo();

Ruby

def foo
  puts 'hi'
end

foo = foo()

Key Takeaway

JavaScript…¯\_(ツ)_/¯


References

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var


<– Back to all “Work Diary” entries