0
0
Javascriptprogramming~3 mins

Why Return values in Javascript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your code could hand you answers like a helpful friend instead of just doing chores silently?

The Scenario

Imagine you ask a friend to do a quick math problem for you, but instead of telling you the answer, they just say "Done!" and walk away. You have to guess the result yourself or do the math again.

The Problem

Without return values, functions can only do things but not give back results. This means you must repeat work or keep extra notes, which is slow and confusing. It's like baking a cake but never getting to eat it.

The Solution

Return values let functions send back answers after doing their job. This means you get the exact result you want, ready to use right away, making your code clear and efficient.

Before vs After
Before
function add(a, b) { console.log(a + b); } add(2, 3); // prints 5 but no value returned
After
function add(a, b) { return a + b; } let sum = add(2, 3); console.log(sum); // prints 5 and stores value
What It Enables

Return values let your code pass results around easily, making programs smarter and more flexible.

Real Life Example

Think of a vending machine: you put money in, press a button, and it returns your snack. Without the snack coming back, the machine wouldn't be very useful!

Key Takeaways

Return values let functions give back results.

This avoids repeating work and keeps code clean.

They help programs communicate and work together smoothly.