-1

Source: https://developer.mozilla.org/el/docs/Web/JavaScript/Reference/Operators/function
"Function expressions in JavaScript are not hoisted, unlike function declarations. You can't use function expressions before you declare them."

Example:

var hey = function(){
    console.log("hi");
}

Chrome's console: window.hey returns

function (){
console.log("hi");
}
sterg
  • 37
  • 1
  • 5
  • 2
    Is there a question here? – RobG Mar 06 '17 at 00:20
  • 1
    I don't see any question here, pls make clear what you want to know. – cyr_x Mar 06 '17 at 00:20
  • What's the question? You're using `window.hey` **after** you declare the function, so the dociumentation you quoted doesn't apply. – Barmar Mar 06 '17 at 00:20
  • I guess the word "hoisting" is unclear to him. `function x()` can be called even prior to its declaration, while `var x = function()` is not available until it's defined. – Psi Mar 06 '17 at 00:21
  • Yea..I messed it up in my head.Got it now. – sterg Mar 06 '17 at 00:32

2 Answers2

1

What it's saying is that you can't write:

hey();
var hey = function() {
    console.log("hi");
}

because you're using the variable hey before you assign the function expression to it. But you can write:

hey();
function hey() {
    console.log("hi");
}

because function declarations are hoisted to the beginning of the containing function.

For more information, see var functionName = function() {} vs function functionName() {}

Community
  • 1
  • 1
Barmar
  • 596,455
  • 48
  • 393
  • 495
0

To build on @Barmar's answer, when you do:

hey();
var hey = function() {
    console.log("hi");
}

technically the variable declaration is still hoisted, but the assignment remains where it is written, so it is equivalent to:

var hey;
hey(); // hey is declared as a variable, but is still undefined.
hey = function() {
    console.log("hi");
}
CodingWithSpike
  • 40,215
  • 17
  • 97
  • 136