Lesson 13 - Arrow Functions in JavaScript
We have already seen a bit of what a function is. Arrow functions still operate, to some extent, like the normal functions except that:
- They don't have a name, unless you use named function expression instead
- They are compact alternative to a traditional function expression
- A deliberate limitations in usage(bindings to
this
, cannot be used asconstructors
, and cannot useyield
)
We will dive into these details in this lesson. So let's see the basic usage of the arrow function in JavaScript.
const multiply = (a, b) => a * b;
console.log(multiply(4, 3)); // Output: 12
Explanation:
- Arrow functions (
=>
) provide a shorter way to write functions in JavaScript. const multiply = (a, b) => a * b;
is equivalent to:
function multiply(a, b) {
return a * b;
}
- If the function has a single expression,
{}
andreturn
can be omitted.
Try your hand:
1. Create a File:
Create a new file named lesson13-arrow-functions.html
2. Write the Code:
Copy and paste the following code into your file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Day 13 - Arrow Functions</title>
</head>
<body>
<script>
const multiply = (a, b) => a * b;
console.log(multiply(4, 3)); // Output: 12
</script>
</body>
</html>
Save the file in your folder.
3. Preview the File:
- Open the file in your browser and access the developer console.
- Observe the output:
12
Experiment:
-
Try an arrow function without parameters:
const sayHello = () => "Hello, world!"; console.log(sayHello()); // Output: Hello, world!
-
Try an arrow function with one parameter (parentheses can be omitted):
const square = x => x * x; console.log(square(5)); // Output: 25
-
Try a multi-line arrow function:
const greet = (name) => { let message = "Hello, " + name + "!"; return message; }; console.log(greet("Alice")); // Output: Hello, Alice!