📝 Understanding the return
Statement in JavaScript (with examples)
In JavaScript, functions are one of the most fundamental building blocks. Sometimes, you simply want a function to do something (like print a message). Other times, you want it to compute something and give the result back.
This is where the return
statement comes into play.
Let’s explore this with two simple functions:
Example 1: Function without return
function greet(name) { console.log("Hello, " + name + "!"); } greet("Sreeraj");
Here, the function greet
doesn’t return anything. Instead, it directly performs an action: it prints "Hello, Sreeraj!"
to the console.
This is perfect when you want a function to execute some code, but you don’t need to reuse the result.
Example 2: Function with return
function greeting(name) { return "Hello, " + name + "!"; }
In this case, the function greeting
creates the message and returns it to the place where the function was called.
This allows us to do more flexible things with the returned value:
Usage #1: Print directly
console.log(greeting("Sreeraj"));
Here, we call greeting("Sreeraj")
. The function returns "Hello, Sreeraj!"
, and then console.log
prints it.
Usage #2: Store in a variable and reuse
let msg = greeting("Sreeraj"); console.log(msg);
We store the returned message in the variable msg
. Later, we can log it, modify it, or use it anywhere else in our program.
âś… Summary
- The
return
statement sends a value back from the function to the caller. - Without
return
, a function just runs and finishes; withreturn
, it provides output you can use elsewhere. - Using
return
makes functions more reusable and flexible.
By understanding when to use return
, you’ll write cleaner, modular, and more maintainable JavaScript code