Explain the differences on the usage of foo between function foo() and var foo = function() in JavaScript

Answer

In JavaScript, there are key differences in how foo behaves and is used between these two declarations:

1. function foo() {}

This is a function declaration.

Key Characteristics:

  1. Hoisting:

Example:

foo(); // Works because the function is hoisted
function foo() {
  console.log('Function declaration');
}
  1. Scope:
function test() {
  function foo() {
    console.log('Local scope');
  }
  foo(); // Works within the local scope
}
test();
  1. Name Binding:

Example:

function foo(n) {
  if (n > 0) {
    return foo(n - 1); // Recursion
  }
  return 'Done';
}
console.log(foo(3)); // "Done"

2. var foo = function() {}

This is a function expression assigned to a variable.

Key Characteristics:

  1. Hoisting:

Example:

console.log(foo); // undefined (variable hoisted, but function not assigned yet)
foo(); // Error: foo is not a function
var foo = function () {
  console.log('Function expression');
};
  1. Scope:

Example:

function test() {
  console.log(foo); // undefined
  var foo = function () {
    console.log('Local function expression');
  };
  foo(); // Works now
}
test();
  1. Name Binding:

Anonymous Function:

var foo = function () {
  console.log('Anonymous function');
};
foo(); // Works

Named Function Expression:

var foo = function bar() {
  console.log('Named function expression');
  // bar() can reference itself here
};
foo(); // Works
bar(); // Error: bar is not defined outside the function

When to Use Which?

Conclusion