Common pattern without else
Many developers prefer an early return instead of else:
function login(user) {
if (!user) {
console.log("No user found");
return;
}
console.log("Welcome");
}
Here no else is needed because return exits the function.
Rule: If there is no else, JavaScript simply ignores the if block when the condition is false and continues executing the next line.
why return
return is used to immediately stop a function and optionally send a value back.
Example without return:
function greet() {
console.log("Hello");
console.log("Welcome");
}
greet();
Output:
Hello
Welcome
Both lines run.
Example with return:
function greet() {
console.log("Hello");
return;
console.log("Welcome");
}
greet();
Output:
Hello
After return, the function ends immediately. Anything below it is not executed.
That's why developers often avoid else:
function login(user) {
if (!user) {
console.log("No user found");
return;
}
console.log("Welcome");
}
If user is missing:
No user found
The function stops at return.
If user exists:
Welcome
return can also send a value back:
function add(a, b) {
return a + b;
}
let result = add(2, 3);
console.log(result);
Output:
5
Here return a + b means:
"End the function and give back the value
5."
So return has two jobs:
- Stop the function.
- Optionally return a value to the caller.
- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
Comments
Post a Comment