0
0
Javascriptprogramming~30 mins

Return inside loops in Javascript - Mini Project: Build & Apply

Choose your learning style9 modes available
Return inside loops
📖 Scenario: Imagine you have a list of numbers and you want to find the first number that is bigger than a certain limit. This is like looking for the first ripe apple in a basket.
🎯 Goal: You will write a function that looks through a list of numbers and returns the first number that is greater than a given limit. You will learn how return works inside a loop to stop the search as soon as the answer is found.
📋 What You'll Learn
Create an array called numbers with the exact values: [3, 7, 10, 2, 8]
Create a variable called limit and set it to 6
Write a function called findFirstGreater that takes numbers and limit as parameters and uses a for loop with variable num to check each number
Inside the loop, use return to immediately return the first number greater than limit
If no number is greater, return null
Call findFirstGreater(numbers, limit) and print the result
💡 Why This Matters
🌍 Real World
Finding the first item that meets a condition quickly is common in searching tasks, like finding the first available seat or the first product in stock.
💼 Career
Understanding how to use return inside loops helps in writing efficient code that stops processing as soon as the needed result is found, which is important in many programming jobs.
Progress0 / 4 steps
1
Create the array of numbers
Create an array called numbers with these exact values: [3, 7, 10, 2, 8]
Javascript
Need a hint?

Use const numbers = [3, 7, 10, 2, 8]; to create the array.

2
Set the limit value
Create a variable called limit and set it to 6
Javascript
Need a hint?

Use const limit = 6; to create the limit variable.

3
Write the function with a loop and return inside
Write a function called findFirstGreater that takes numbers and limit as parameters. Use a for loop with variable num to check each number. Inside the loop, use return to immediately return the first number greater than limit. If no number is greater, return null after the loop.
Javascript
Need a hint?

Use for (const num of numbers) to loop. Use if (num > limit) return num; inside the loop. Return null after the loop.

4
Call the function and print the result
Call findFirstGreater(numbers, limit) and print the result using console.log
Javascript
Need a hint?

Use console.log(findFirstGreater(numbers, limit)); to print the result.