Arrow Function
Lesson 10 of 14 in Coddy's Function Declarations in JavaScript course.
Arrow functions, also known as lambda functions, are a concise way to write JavaScript functions introduced in ES6. They provide a shorter syntax compared to traditional function declarations, making your code more readable in certain situations, which is why modern JavaScript programmers often prefer them.
Imagine you have small, well-defined tasks within your code. Arrow functions allow you to express those tasks in a more compact and streamlined way. They are particularly useful for callback functions and situations where a short, anonymous function is needed.
// Arrow function with implicit return (single line)
const greet = (name) => `Hello, ${name}!`;
const message = greet("Bob");
console.log(message); // Output: Hello, Bob!
// Arrow function with explicit return (multiple lines)
const multiply = (num1, num2) => {
const product = num1 * num2;
return product;
};
const result = multiply(5, 3);
console.log(result); // Output: 15We define an arrow function named
greetthat takes one argument,name.The
=>symbol separates the parameters from the function body.Since the function body is a single line expression, the return statement is implicit.
We define an arrow function named
multiplythat takes two arguments,num1andnum2.The function body uses curly braces
{}for multiple lines of code.Inside the function, the product is calculated and stored in the
productvariable.An explicit
returnstatement is used to return the calculatedproduct.
Challenge
MediumYour task is to write a JavaScript program that finds the largest number in a given numbers array using an findLargest arrow function.
Try it yourself
// Write code here
All lessons in Function Declarations in JavaScript
1Course Introduction
What you will learn?3Ways of Function Declaration
Basic FunctionNested FunctionReturning a FunctionFunction ExpressionsArrow FunctionFunction Constructor