JavaScript Roadmap — Day 29: Return Values and Scope — Getting Results Back

 

 

JavaScript · Day 29 of 180 · Beginner Phase

Return Values and Scope — Getting Results Back

Functions can send data back to the code that called them using the return statement. And scope determines where variables are visible. Master these and you'll write functions that are truly useful and bug-free.

Day 29 / 180
Beginner Phase
🕐 13 min read
💻 6 code examples
🎯 3 practice tasks
📝 5 quiz questions

1. The Return Statement — Sending Data Back

The return statement is how a function sends a value back to the code that called it. Without return, a function returns undefined by default — which means you can't use its result in calculations or store it in variables.

Think of a function like a vending machine. You put money in (arguments), press a button (call the function), and the machine returns a snack. Without the return, the machine would just make noise but give you nothing! The return statement also immediately exits the function — no code after it will run.

Return Statement Examples
// Function WITH return — sends value back
function add(a, b) {
  return a + b;  // Returns the sum
}
let result = add(5, 3);
console.log(result);  // 8

// Function WITHOUT return — returns undefined
function sayHello(name) {
  console.log(`Hello ${name}`);
}
let output = sayHello("Waheed");
console.log(output);  // undefined

// Return immediately exits the function
function earlyExit() {
  return "Done!";
  console.log("This never runs");  // ❌ Unreachable
}

💡 The key insight: return does two things: (1) it sends a value back to the caller, and (2) it immediately stops the function. Any code after return will never execute. This makes return perfect for early exits when validation fails.

📝 QUIZ Test Your Understanding

Question 1: What does a function return if there is no return statement?

2. Understanding Scope — Where Variables Live

Scope determines where variables are accessible in your code. Think of scope like different rooms in a house. Variables declared in a room (function) can't be seen from outside that room. But variables declared in the living room (global scope) can be seen from everywhere.

JavaScript has three main types of scope: global scope (accessible everywhere), function scope (accessible only inside the function), and block scope (accessible only inside {} blocks). Understanding scope prevents naming conflicts and unexpected bugs.

Scope Examples
// Global scope — accessible anywhere
let globalVar = "I'm global";

function myFunction() {
  // Function scope — only inside this function
  let functionVar = "I'm local to the function";
  console.log(globalVar);     // ✅ Works — can access global
  console.log(functionVar);   // ✅ Works
}

myFunction();
console.log(globalVar);       // ✅ Works
console.log(functionVar);     // ❌ Error! Not accessible outside

3. Global vs Local Scope — The Difference

Global variables are declared outside any function and can be accessed from anywhere. Local variables are declared inside a function and only exist while that function runs. This is crucial for avoiding naming conflicts — you can use the same variable name in different functions without them interfering.

A key principle: functions can read global variables, but when you assign to a variable inside a function, JavaScript creates a local variable unless you explicitly tell it otherwise. This prevents accidental modification of global variables.

Global vs Local
let message = "Global";  // Global variable

function showMessage() {
  let message = "Local";  // Local variable (different!)
  console.log(message);        // "Local"
}

showMessage();
console.log(message);          // "Global" (unchanged)

// ⚠️ Accidentally creating a global variable (avoid this!)
function badFunction() {
  accident = "I forgot 'let'!";  // ❌ Becomes global!
}
badFunction();
console.log(accident);  // "I forgot 'let'!" — now global!
📝 QUIZ Test Your Understanding

Question 2: What happens when you declare a variable inside a function without let, const, or var?

4. Block Scope — {} Creates Boundaries

With let and const, any pair of curly braces {} creates a new scope. This includes if statements, for loops, while loops, and standalone blocks. This is different from var, which ignores block scope and only respects function scope.

Block scope is why modern JavaScript prefers let and const over var. Variables declared with let inside a block cannot be accessed outside that block, preventing accidental leaks and making code more predictable.

Block Scope Examples
// Block scope with let (stays inside the block)
if (true) {
  let blockVar = "Inside block";
  console.log(blockVar);  // ✅ Works
}
console.log(blockVar);  // ❌ Error! blockVar not defined

// var ignores block scope (problematic!)
if (true) {
  var leaked = "This leaks out";
}
console.log(leaked);  // "This leaks out" (should not be accessible!)

// for loop block scope
for (let i = 0; i < 3; i++) {
  console.log(i);  // 0, 1, 2
}
console.log(i);  // ❌ Error! i is not defined outside the loop
📝 QUIZ 3 & 4 Test Your Understanding

Question 3: Which keyword creates block scope?

Question 4: What will be the output?

let x = 10;
function test() {
  let x = 20;
  console.log(x);
}
test();
console.log(x);

5. Common Mistakes to Avoid

Mistakes & Fixes
// ❌ MISTAKE 1: Code after return (unreachable)
function getValue() {
  return 42;
  console.log("Never runs");  // ❌ Unreachable
}

// ✅ FIX: Put code before return
function getValue() {
  console.log("Getting value");
  return 42;
}

// ❌ MISTAKE 2: Forgetting to store return value
function add(a, b) { return a + b; }
add(5, 3);  // Calculates 8 but does nothing with it

// ✅ FIX: Store or use the returned value
let result = add(5, 3);
console.log(result);

6. Best Practices — Professional Patterns

🎯 Always Use Return for Calculations
If a function produces a value, use return. Don't just log it. This makes your functions reusable and testable.
📦 Minimize Global Variables
Global variables can be changed anywhere, leading to bugs. Keep variables as local as possible — inside functions or blocks.
🔒 Use let/const, Never var
var ignores block scope and can cause bugs. Always use let (for changing values) or const (for constants).
📝 Return Early for Validation
Check for invalid inputs at the start of your function and return early. This reduces nesting and makes code clearer.

7. Try It Yourself — Scope Playground

See how scope works in real time. Click the buttons to test global vs local variables.

✏️ Scope Playground
HTML
JAVASCRIPT
LIVE PREVIEW
💡 Click buttons to see global vs local scope!

8. Practice Tasks

Task 1 — Easy: Return the Square

Write a function square(num) that returns the square of a number. Test with 5 (returns 25) and 10 (returns 100).

Task 2 — Medium: Local vs Global

Create a global variable counter = 0. Write a function increment() that creates a LOCAL variable also called counter and increments it. Show that the global counter remains unchanged.

Task 3 — Hard: Validation with Early Return

Write a function divide(a, b) that returns the division result. If b is 0, return the string "Error: Cannot divide by zero" immediately (early return). Test with (10, 2) and (10, 0).

📝 FINAL QUIZ Test Your Mastery

Question 5: What is the output of the following code?

let x = 5;
function example() {
  let x = 10;
  return x;
}
console.log(example());
console.log(x);
Next Lesson
Day 30 — Hoisting — Declaration Magic
View Full Roadmap →
Enjoying this roadmap?
Follow Muhammad Waheed Asghar for daily JavaScript tips and updates!

Popular Posts