1

Consider these two snippets:

Snippet #1

function countDownFn(num) {
  if (num === 0) return;

  console.log(num);
  countDownFn(--num);
}

countDownFn(5); // prints 5, 4, 3, 2, 1 once per line

Snippet #2

var myCounter = function countDownExp(num) {
  if (num === 0) return;

  console.log(num);
  countDownExp(--num);
};

myCounter(5); // prints 5,4,3,2,1 once per line
  1. Why can I find window.countDownFn but cannot find window.countDownExp ?
  2. Why would you use one over other?
  3. Is one of them better than other ? Why?
Vikram
  • 4,162
  • 8
  • 43
  • 65

2 Answers2

1
var myCounter = function countDownExp(num) {
  if (num === 0) return;

  console.log(num);
  countDownExp(--num);
}

countDownExp is a named expression. That name is only available inside of the function and it used in case the function needs to be recursive. Named expressions only happen on function expressions and not function declarations.

Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
0

Try changing var myCounter = function countDownExp to function countDownExp this will make it available to the window object.

Function Declaration function example(){} Hoists the entire function. This means the function will be available for use even above where the function was written.

Function Expression var example = function(){} Hoists the variable but example will be undefined until the line of code that assigns the anonymous function to the variable.

I prefer function declarations because I don't have to worry about hoisting issues.

Nathan
  • 1,455
  • 1
  • 10
  • 7