To understand Function Expression lets explore functions in Javascript first.
Functions
In general, Functions are subprograms which may, or may not take parameters(input) and return a value.
Functions in Javascript
A javascript function does the same thing. It takes parameters as input and returns a value.
function addTwoNumbers(a, b) {
return a+b;
}
Javascript function definition starts with the function keyword, followed by:
- name of the function
- parameters if any, wrapped with parenthesis and separated by a comma
- the function body - series of statements inside curly brackets { }.
function greetings(name) {
alert('Hi' + name);
}
If you have experience in other programming languages, the above function definitions will look very familiar to you.
Function Expression
Functions are first-class objects in Javascript. For that reason, they can be assigned to a variable as an expression, passed as a parameter, and much more.
A function expression is defined by assigning a function definition to a javascript variable.
var addTwoNumbers = function (a,b) {
return a + b;
}
addTwoNumbers(2, 3);
Anonymous Function Expression
In the previous example, the function assigned to variable "addTwoNumbers" has no name. Therefore, it is called an anonymous function.
var multiplyTwoNumbers = function (a,b) {
return a * b;
}
multiplyTwoNumbers(2, 3);
Anonymous Function Expressions are used to create callback functions. We will save callback for another time.
Named Function Expression
To create a named function expression, assign a function with a name to a variable. In this case, the scope of the function name is the function itself.
var newSeries = function fibonacci(num) {
if (num <= 1) return 1;
return fibonacci(num - 1) + fibonacci(num - 2);
}
Named Function Expressions are useful for creating recursive functions.
Function Expression is quite useful in the real world. It is also used to create a coding pattern called IIFE(Immediately Invoked Function Expression). We will discuss the IIFE in the next article.
Originally Published on hackinbits.com.
If you like this article, please upvote and share it.
Top comments (0)