Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
if else print at the same time in JavaScript

when I trigger the if condition, why the else will print out as well? someone could indicate what's the problem of the code below? written in JS.

original picture of code

const rainbow = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'violet'];
let colour = prompt("What is your favourite colour?").toLowerCase();

for (let i = 0; i < rainbow.length; i+=1) {
  if (rainbow[i] === colour) {
    console.log("yes")
  }
  else {
    console.log(rainbow.join(" *** "));
  }
}

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

It's because your loop is running through the array. So for example if I say red it will go to the first if and then after the second iteration it will go to the else. If this code is un a function you need to return in your if, if you want the loop to stop at this moment.

const findColor = () => {
    const rainbow = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'violet'];
    let colour = prompt("What is your favourite colour?").toLowerCase();

    for (let i = 0; i < rainbow.length; i+=1) {
      if (rainbow[i] === colour) {
        console.log("yes")
        return rainbow[i]// It will leave the loop when it passes on the right color
      }
      else {
        console.log(rainbow.join(" *** "));
        return
      }
    }
}

You can also use the includes function if you don't want to use a loop:

console.log(rainbow.includes(colour) ? 'yes' : rainbow.join(" *** "));
about 4 years ago · Juan Pablo Isaza Report

0

You don't even need a loop for this You can use the include function for arrays to achieve this.

const rainbow = ['red','orange','yellow','green','cyan','blue','violet']; 
let colour = prompt("What is your favourite colour?").toLowerCase();

console.log(rainbow.includes(colour) ? 'yes' : rainbow.join(" *** "));

about 4 years ago · Juan Pablo Isaza Report

0

You could use the includes method for checking the input.

const rainbow = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'violet'];
let colour = prompt("What is your favourite colour?").toLowerCase();

if (rainbow.includes(colour)) {
  console.log("yes")
}
else {
  console.log(rainbow.join(" *** "));
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!