</> Code Corner

JavaScript · JS Functions & Objects · Lesson 40

JS Arrow Functions

Shorter function syntax with =>.

Arrow functions allow a shorter syntax for writing function expressions.

Example

<p id="demo"></p>
<script>
// Regular function expression
let hello1 = function () { return "Hello World!"; };
// Arrow function
let hello2 = () => "Hello World!";
// With parameters
let sum = (a, b) => a + b;
let square = x => x * x;
let makeUser = name => ({ name: name, active: true });
document.getElementById("demo").innerHTML =
  hello2() + "<br>sum: " + sum(2, 3) + "<br>square: " + square(5) + "<br>user: " + makeUser("Ada").name;
</script>
  • If the body is a single expression, you can omit { } and return
  • One parameter does not need parentheses
  • Wrap an object literal in parentheses to return it
  • Arrow functions do not have their own this

Keep reading “JS Arrow Functions”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋