By the end of this lesson, you will be able to write function expressions and arrow functions in JavaScript. Both concepts are essential for coding effectively.
A function expression is a way to define a function in JavaScript. It allows you to create a function and assign it to a variable. For example, you might use a function expression to calculate the sum of two numbers. This can help you simplify your code.
Imagine you have a math tutor. You can ask this tutor to help you with addition. The tutor has a method to calculate sums. Similarly, function declarations in JavaScript serve as methods to perform tasks in your code.
File: sum.js
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3));
8
In this example, we first create a function expression named add. This function takes two parameters, a and b, and returns their sum. Consequently, we use console.log to display the result of calling the add function with the numbers 5 and 3.
Arrow functions offer a shorter way to write function expressions in JavaScript. They are often more readable. Here’s how you can write the same function as an arrow function:
const add = (a, b) => {
return a + b;
};
console.log(add(5, 3));
Create a function expression and an arrow function named multiply. This function should take two numbers and return their product. Afterwards, log the result of calling both functions with the numbers 4 and 6.
// Function Expression
const multiplyExpression = function(a, b) {
return a * b;
};
// Arrow Function
const multiplyArrow = (a, b) => {
return a * b;
};
console.log(multiplyExpression(4, 6));
console.log(multiplyArrow(4, 6));
24
24
function keyword. Arrow functions should use the => syntax. Therefore, check your code for extra symbols.() when you want to run the function. Without them, you just reference the function.