Last updated: Mar 2, 2024
Reading time·3 min
The "SyntaxError: Illegal return statement" occurs when the return
statement
is used outside of a function.
To solve the error make sure to only use the return
statement inside of a
named or an arrow function. The statement ends a function's execution and
returns the value to the caller.
Here are examples of when the error occurs.
// ⛔️ don't return outside a function return 42; // ✅ Use return inside a function function getNum() { return 42; } if (true) { // ⛔️ don't return outside a function return 10; } for (let i = 0; i < 3; i++) { // ⛔️ don't return outside a function return 15; } function example() // 👈️ has a missing curly brace { return true }
return
statement outside a functionThe most common cause of the error is using the return
statement outside of a
function.
Make sure to only use the return
keyword inside functions.
// ✅ return inside named function function getNum() { return 42; } // ✅ return inside arrow function const example = () => { return 42; }; // ✅ implicit return using arrow function const another = () => 'bobbyhadz.com'; // ✅ implicitly return object from arrow function const another2 = () => ({ id: 1, site: 'bobbyhadz.com', });
The following if
statement and for
loop are not inside of a function, so we
aren't allowed to use the return
statement in them.
if (true) { // ⛔️ don't return outside a function return 10; } for (let i = 0; i < 3; i++) { // ⛔️ don't return outside a function return 15; }
Instead, you should wrap the if
statement in a function.
function test() { if (true) { return 100; } return 200; }
break
statement if you need to exit a loopIf you need to exit a for
loop, you should use a break
statement instead of
return
.
const arr = ['bobby', 'hadz', 'com']; for (let index = 0; index < arr.length; index++) { console.log(arr[index]); if (arr[index] === 'hadz') { // 👇️ exit the loop break; } }
The break
statement is used to exit a loop prematurely.
We can use the break
statement in the following scenarios:
for
loopsfor ... of
loopsfor ... in
loopswhile
loopsswitch
statementsHere is an example of using the break
statement to exit a for...of
loop.
let arr = ['a', 'b', 'c']; for (const element of arr) { if (element === 'b') { break; } console.log(element) // 👉️ a }
The if
statement in the for...of
loop checks if a condition is met on each
iteration.
Once the if
block runs, we use the break
statement to exit the for...of
loop.
Another common reason for the error being thrown is a syntax error in our code.
In the screenshot, we can see that the error was thrown in the index.js
file
on line 5
.
You can hover over the squiggly red line to get additional information on why the error was thrown.
To solve the "Illegal return statement" error:
return
statement inside of functions.