23
What are First Class Functions in JS?
Let's go over common jargons used in JS.
//function statement
function statement() {
console.log('statement')
}
//function expression
var expression = function () {
console.log('expression');
}
The main difference between declaring functions this way is hoisting.
statement(); // prints 'statement'
expression(); // TypeError: expression is not a function
function statement() {
console.log('statement')
}
var expression = function () {
console.log('expression');
}
When JS allocates memory it copies the whole function when it is declared as a statement. But, JS assigns a value of undefined for variables which is why JS does not recognize function expressions as functions.
Anonymous functions are functions without names. If you declare a function without a name it returns a syntax error. Anonymous functions are used when functions are used as values. In the example above, a function expression uses an anonymous function where the function is a value and has no name.
function () {} // this in itself returns SyntaxError;
First-class is the ability to use functions as values, arguments, and returned values.
23