JavaScript return Vs throw Error
The return
and throw
are used to handle errors and exceptions in JavaScript, but they are used in different ways.
The return
statement is used to exit a function and return a value to the caller. It can be used to return a value, or to exit a function without returning a value.
On the other hand, the throw
statement is used to signal an exception or error. It can be used to throw a user-defined exception. When the throw
statement is used, the normal flow of the program is interrupted and the program jumps to the nearest catch block.
The main difference between return
and throw
is that a return
statement is used to exit a function and return a value, while a throw
statement is used to signal an error or exception.
A return
statement should be used to end a function and return a value to the calling code, whereas a throw
statement should be used to indicate that an error has occurred and that the function cannot continue executing normally.
In addition, throw
statement can be caught with try...catch
block, while returned error cannot be caught this way.
It's generally recommended to use throw
statement to signal an exception, and return
statement to return the value or exit a function.
Using return
statement
The return
statement is used to exit a function and return a value to the caller. First, let’s show how we can use the return
statement to return a value, especially within a function. The value returned can be of any data type, including numbers, strings, objects, and even other functions. For example, a simple function that returns the square of a number might look like this
function square(x) {
return x * x;
}
console.log(square(256));
Output
65536
In addition, aside from returning a value, we can make use of the return
statement to exit the function execution early, even if there are more statements to be executed in the function. This is useful in situations where a certain condition is met and you don't want to execute the remaining statements.
function isAdult(age) {
if (age < 18) {
return "Not an adult.";
}
return "Adult.";
}
console.log(isAdult(15));
Output
Not an adult.
In the above code, we call the isAdult
function with the value of 15
, the function returns "Not and adult."
because the value is less than 18 and doesn’t even reach the other return statement.
In this example, the divide()
function checks if the divisor (b) is equal to zero, if so it returns an error object with a message "Cannot divide by zero". The returned value is then checked if it's an instance of error if true it logs the error message, otherwise it logs the result.
function divide(a, b) {
if (b === 0) {
return new Error('Cannot divide by zero');
}
return a / b;
}
let result = divide(4, 2);
if (result instanceof Error) {
console.log(result.message);
} else {
console.log(result);
}
Using throw
statement
The throw
statement is used to throw an exception, which is a special object that represents an error or exceptional condition. When an exception is thrown, the current function execution is stopped and control is passed to the nearest catch block, which can handle the exception. For example, a simple function that checks if a number is positive might look like this
function checkPositive(x) {
if (x < 0) {
throw "Error: Number is not positive";
}
return "Number is positive";
}
console.log(checkPositive(-34));
Output
throw "Error: Number is not positive";
^
Error: Number is not positive
In this example, the function throws an exception when the input number is not positive.
Furthermore, throw
statements are used in conjunction with try/catch
statement to deal with errors. So in a situation where your functions throw an exception, the catch section of the statement will handle the exception. Let’s illustrate this by creating a divide()
function that will throw an error when we try to divide a number by 0
.
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero.");
}
return a / b;
}
try {
let result = divide(5, 0);
console.log(result);
} catch (e) {
console.error(e);
}
Output
Error: Cannot divide by zero.
In this example, the divide
function checks if the divisor (b
) is zero. If it is, an error is thrown using the throw
statement with the message "Cannot divide by zero." The try/catch
block is used to handle the exception. The code inside the try
block is executed and if an exception is thrown, the code inside the catch
block is executed instead. In this case, the error message is logged into the console.
If we don’t want to log the error, we can simply log a statement in place of the error message.
try {
let result = divide(5, 0);
console.log(result);
} catch (e) {
console.log("Cannot divide by zero");
}
Output
Cannot divide by zero
JavaScript provides several built-in error objects that developers can use to create more informative error messages. These include Error
, TypeError
, RangeError
, SyntaxError
, and others.
Summary
In summary, JavaScript developers use return
statement to exit a function and return a value to the caller, and throw
statement to throw an exception, which represents an error or exceptional condition. return
statement is used to exit the function execution early, even if there are more statements to be executed in the function. throw
statement is used to throw an exception and stop the current function execution and pass the control to the nearest catch block which can handle the exception.
References
return - JavaScript | MDN (mozilla.org)
throw - JavaScript | MDN (mozilla.org)