📘 Lesson  ·  Lesson 22

Return Values

Return Values

The return Statement — sending a value back

function add(a, b) {
    return a + b;          // sends the result BACK to whoever called it
}

let sum = add(5, 3);       // sum now holds 8
console.log(sum);          // 8
console.log(add(10, 20));  // 30 — you can use the result directly
return sends a value out of a function, back to the code that called it. This transforms a function from something that just DOES things into something that PRODUCES a result you can store, print, or feed into another calculation. Parameters are how data goes IN; return is how the answer comes OUT. Most useful functions follow this shape: take some inputs, compute something, return the answer. Without return, a function's work is trapped inside it.

return vs console.log — a crucial distinction

// This PRINTS but returns nothing useful:
function addAndPrint(a, b) {
    console.log(a + b);          // shows 8 in the console
}
let x = addAndPrint(5, 3);       // x is undefined! Nothing was returned.

// This RETURNS a usable value:
function add(a, b) {
    return a + b;
}
let y = add(5, 3);               // y is 8 — a real value you can use
let z = add(5, 3) * 2;           // 16 — you can do maths with it
Beginners frequently confuse these two, but they do completely different jobs. console.log() DISPLAYS something for a human to read — it's for debugging, and it gives your program nothing to work with. return HANDS A VALUE back to your code, so you can store it, calculate with it, or pass it along. A function with no return statement automatically returns undefined. Rule of thumb: use return to produce results; use console.log only to peek at what's happening.

return Stops the Function Immediately

function test() {
    console.log("This runs");
    return "Done";
    console.log("This NEVER runs");   // unreachable code!
}

console.log(test());   // "This runs" then "Done"
The instant return executes, the function ENDS. Any code written after it inside that function is unreachable and will never run — some editors will grey it out or warn you. This isn't a limitation; it's a feature you can use deliberately. It means return serves two purposes at once: sending a value back, AND exiting the function right there. That second purpose leads to a very useful pattern, the "early return."

Early Return — exit as soon as you know the answer

function checkAge(age) {
    if (age < 0) {
        return "Invalid age";      // exit immediately — no need to check more
    }
    if (age >= 18) {
        return "Adult";
    }
    return "Minor";                // the leftover case
}

// A "guard clause" keeps code flat and readable:
function divide(a, b) {
    if (b === 0) return "Cannot divide by zero";   // guard
    return a / b;                                   // main logic, un-nested
}
Because return exits immediately, you can handle special cases first and get them out of the way. This is called an "early return" or "guard clause," and it's a hallmark of clean, professional code. Compare it with the alternative — wrapping your main logic in a big if/else, nesting deeper and deeper. Early returns keep the happy path (the normal case) at the bottom, un-indented and easy to read, with the exceptional cases dispatched up top. Once you start using guard clauses, deeply nested if statements start to look unnecessary.

Returning Several Values — use an array or object

// A function can only return ONE thing... but that thing can be a collection:

function getStats(marks) {
    let max = Math.max(...marks);
    let min = Math.min(...marks);
    return { max, min };          // return an OBJECT with both
}

let stats = getStats([85, 92, 78]);
console.log(stats.max);    // 92
console.log(stats.min);    // 78

// Or return an array:
function getPair() {
    return ["Aman", 20];
}
A function returns exactly one value — but that value can be an array or an object holding many things. Need to return both a maximum and a minimum? Bundle them in an object: return { max, min }. The caller then reads stats.max and stats.min. This is the standard way to "return multiple values" in JavaScript, and it also makes your result self-documenting (named properties beat guessing what position 0 means). You'll see this pattern everywhere once you learn objects properly in the next group.

Exam Corner

Q: What does return do? Sends a value back to the code that called the function, and exits the function.

Q: Difference between return and console.log? return gives a usable value to your code; console.log only displays text for humans.

Q: What does a function return if it has no return statement? undefined.

Q: Does code after a return statement run? No — return ends the function immediately.

Q: How do you return more than one value? Return an object or an array containing them.

return Statement — value वापस भेजना

function add(a, b) {
    return a + b;          // nateeja call karne wale ko WAPAS bhejta hai
}

let sum = add(5, 3);       // sum ab 8 rakhta hai
console.log(sum);          // 8
console.log(add(10, 20));  // 30 — nateeja seedhe use kar sakte hain
return function से value बाहर भेजता है, उस code को वापस जिसने उसे call किया. यह function को सिर्फ चीज़ें KARNE वाले से ऐसा बनाता है जो नतीजा PAIDA करता है जिसे आप store, print, या दूसरी calculation में डाल सकते हैं. Parameters से data ANDAR जाता है; return से जवाब BAHAR आता है. ज़्यादातर उपयोगी functions यही आकार follow करते हैं: कुछ inputs लो, कुछ compute करो, जवाब लौटाओ. return के बिना, function का काम उसी के अंदर फंसा रहता है.

return vs console.log — अहम भेद

// Yeh PRINT karta hai par kuch upyogi nahi lautata:
function addAndPrint(a, b) {
    console.log(a + b);          // console me 8 dikhata
}
let x = addAndPrint(5, 3);       // x undefined hai! Kuch return nahi hua.

// Yeh istemal layak value LAUTATA hai:
function add(a, b) {
    return a + b;
}
let y = add(5, 3);               // y 8 hai — asli value jo use kar sakte
let z = add(5, 3) * 2;           // 16 — isse ganit kar sakte hain
Beginners अक्सर इन दोनों को उलझाते हैं, पर वे बिल्कुल अलग काम करते हैं. console.log() इंसान के पढ़ने को कुछ DIKHATA है — यह debugging के लिए है, और आपके program को काम करने को कुछ नहीं देता. return आपके code को VALUE SAUPTA है, तो आप उसे store, उससे गणना, या आगे pass कर सकते हैं. बिना return statement वाला function अपने आप undefined लौटाता है. Thumb rule: नतीजे बनाने को return use कीजिए; क्या हो रहा है झांकने को ही console.log.

return Function तुरंत रोकता है

function test() {
    console.log("This runs");
    return "Done";
    console.log("This NEVER runs");   // unreachable code!
}

console.log(test());   // "This runs" phir "Done"
जिस पल return execute होता है, function KHATM हो जाता है. उस function के अंदर उसके बाद लिखा कोई भी code unreachable है और कभी नहीं चलेगा — कुछ editors उसे धुंधला कर देंगे या चेतावनी देंगे. यह सीमा नहीं; यह feature है जिसे आप जानबूझकर use कर सकते हैं. इसका मतलब return एक साथ दो काम करता है: value वापस भेजना, AUR वहीं function से बाहर निकलना. वह दूसरा मकसद बहुत उपयोगी pattern की ओर ले जाता है, "early return."

Early Return — जवाब पता चलते ही बाहर

function checkAge(age) {
    if (age < 0) {
        return "Invalid age";      // turant bahar — aur jaanchne ki zarurat nahi
    }
    if (age >= 18) {
        return "Adult";
    }
    return "Minor";                // bacha hua case
}

// "Guard clause" code ko samtal aur readable rakhta hai:
function divide(a, b) {
    if (b === 0) return "Cannot divide by zero";   // guard
    return a / b;                                   // mukhya logic, bina nesting
}
क्योंकि return तुरंत बाहर निकालता है, आप खास मामले पहले संभालकर उन्हें रास्ते से हटा सकते हैं. इसे "early return" या "guard clause" कहते हैं, और यह साफ, professional code की पहचान है. विकल्प से तुलना कीजिए — अपना मुख्य logic बड़े if/else में लपेटना, और गहरा nesting. Early returns happy path (सामान्य मामला) को नीचे रखते हैं, बिना indent और पढ़ने में आसान, अपवाद मामले ऊपर निपटाए हुए. Guard clauses use करना शुरू करते ही, गहरे nested if statements बेवजह लगने लगते हैं.

कई Values लौटाना — array या object use कीजिए

// Function sirf EK cheez lauta sakta hai... par vah cheez sangrah ho sakti hai:

function getStats(marks) {
    let max = Math.max(...marks);
    let min = Math.min(...marks);
    return { max, min };          // dono ke saath OBJECT lautao
}

let stats = getStats([85, 92, 78]);
console.log(stats.max);    // 92
console.log(stats.min);    // 78

// Ya array lautao:
function getPair() {
    return ["Aman", 20];
}
Function ठीक एक value लौटाता है — पर वह value कई चीज़ें रखने वाला array या object हो सकता है. अधिकतम और न्यूनतम दोनों लौटाने हैं? उन्हें object में बांधिए: return { max, min }. फिर caller stats.max और stats.min पढ़ता है. यह JavaScript में "कई values लौटाने" का standard तरीका है, और यह आपका नतीजा self-documenting भी बनाता है (named properties position 0 का मतलब अंदाज़ने से बेहतर हैं). अगले group में objects ठीक से सीखने पर आप यह pattern हर जगह देखेंगे.

Exam Corner

Q: return क्या करता है? Function को call करने वाले code को value वापस भेजता है, और function से बाहर निकलता है.

Q: return और console.log में अंतर? return आपके code को इस्तेमाल लायक value देता है; console.log सिर्फ इंसानों को text दिखाता है.

Q: बिना return statement वाला function क्या लौटाता है? undefined.

Q: क्या return के बाद का code चलता है? नहीं — return function को तुरंत खत्म करता है.

Q: एक से ज़्यादा values कैसे लौटाते हैं? उन्हें रखने वाला object या array लौटाइए.
← Back to JavaScript Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
👁 Live Preview
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का console.log देखने के लिए F12 दबाइए.