• in
InterCourses
CoursesBlogs
0
← Introduction to JavaScript
○What is JavaScript?○Your First JavaScript Code○Data Types○Type Checking
○Declaring Variables○let and const in Practice○Operators○Type Conversion
○Conditionals○Switch Statement○For Loops○While Loop●Break and Continue
○Defining Functions○Arrow Functions○Scope○Closures○Project - Calculator○Function Expressions
○Arrays○Array Mutation Methods○Array Search and Slice○Array Iteration Methods○Multidimensional Arrays○Destructuring○Array Reverse and Sort○Array Fill○Array Find and Includes○Array Flat and FlatMap○Array Reduce, Some, and Every
○Objects○Object Methods and Destructuring○JSON○Math and Date○Date Basics
○02 Template Literals○String Methods○Regular Expressions
○Higher-Order Functions○Callbacks○map, filter, and reduce○Recursion○Project - Data Transform Pipeline
○OOP Introduction○Classes○Inheritance○Encapsulation
○Asynchronous JavaScript○Promises and Async Await○Async API Simulation

Break and Continue

Two special statements let you control loop execution mid-flight.

break — exit the loop early

javascript
for (let i = 0; i < 10; i++) {
    if (i === 5) break;
    console.log(i); // 0 1 2 3 4
}

Useful when you have found what you were looking for and don't need to continue.

continue — skip to the next iteration

javascript
for (let i = 0; i < 5; i++) {
    if (i === 2) continue;
    console.log(i); // 0 1 3 4
}

Your Task

  1. Write a function firstNegative(numbers) that returns the first negative number in the array, or null if there isn't one. Use break to stop as soon as you find it.
  2. Write a function positiveOnly(numbers) that returns a new array containing only positive numbers (> 0). Use continue to skip non-positive values.
  3. Call both with [-5, 3, -2, 8, -1] and display in #output: "First negative: -5 | Positives: 3,8".
Hint 1
1 / 3
HINT 1

Use break to exit the loop immediately when the condition is met.

Loading editor…
READY
intercourses
javascript