Both variable and function declarations are hoisted to the top on code execution, meaning that their order is irrelevant i.e functions can be called before they are declared.
var a; // Regular.
let c; // Block scoped.
const b; // Immutable.
Functions are first class objects - a function is a regular object of type function
. The function object type has a constructor: Function
.
There are several ways to declare a function.
The difference is how the function interacts with the external components (the outer scope, the enclosing context, object that owns the method, etc) and the invocation type (regular function invocation, method invocation, constructor call, etc).
Hoisted. Available immediately after parsing, before any code is executed.
The function declaration creates a variable in the current scope with the identifier equal to function name. This variable holds the function object.
function foo() {}
foo();
Use them when a function expression is not appropriate or when it is important that that a function is hoisted.
Not hoisted. Available only after the variable assignment is executed.
// Named
let bar = function foo() {};
bar();
foo(); // undefined
Use them when you are doing recursion or want to see the function name in the debugger.
// Anonymous
let foo = function () {};
foo();
let bar = foo();
bar(); // Error: not a function.
Use them when you want to pass a function as an argument to another function or you want to form a closure.
(function () {
// ...
})();
Use them for the module pattern.
Binds this
automatically.
let foo = () => {};
Use them when you want to lexically bind the this
value.
let foo = new Function();
- Use function declaration generators
function* foo(){}
when you want to exit and then re-enter a function. - Use function expression generators
let foo = function* [name](){}
when you want to exit and then re-enter a nested function.
An argument is the value supplied to the parameter.
function foo(bar) {
// bar is a parameter
console.log(bar);
}
foo("baz"); // baz is an argument.
Strings with at least one letter and numbers larger than zero are truthy
.
console.log(true && "foo"); // foo
console.log(true && "foo" && 1); // 1