Javascript: Question re functions

1 - I can reference a function by its name.

function funName () {
  //code
}
console.log (funName);         // -> function funName () {//code}
console.log (typeof funName);  // -> function

2 - I can assign a function to a variable and reference the function by the name of the variable.

var x = function funName () {
  //code
}
console.log (x);               // -> function funName () {//code}
console.log (typeof x);        // -> function

3 - If I assign a function to a variable, I can no longer reference the function by its name.

var x = function funName () {
  //code
}
console.log (funName);         // -> ReferenceError: funName is not defined

Can someone explain why the latter is the case?

Thanks in advance.

1 Like

The keyword function can be used either as a declaration statement:


Or as a way to instantiate a function inside an expression:

When used as the former, it automatically declares a variable as well.

However as the latter, b/c it’s an expression and not a statement, we still need to assign it to some variable/property, or pass it as an argument.

3 Likes