0

Is it possible to assign the outcome of an IF statement to a variable in JS?

  if (busNumber[currentBus][2] == route[0]){
     console.log("Correct!");
  }
  else {
     console.log("Incorrect!");
  } 

Is it possible to assign Correct or Incorrect to a variable so i can thereafter call it in other areas of the program?

3 Answers 3

1
var result;
if (busNumber[currentBus][2] == route[0]){
    result = "Correct!";
}
else {
    result = "Incorrect!";
}
Sign up to request clarification or add additional context in comments.

Comments

0

It's possible by defining the variable upfront and then assign the value to it:

var output;
if (busNumber[currentBus][2] == route[0]){
    console.log("Correct!");
    output = "Correct!";
} else {
    console.log("Incorrect!");
    output = "Incorrect!";
}
console.log('Output: ' + output);

You now can use the variable output in the rest of your script.

2 Comments

Tried this earlier - i keep receiving reverse or an undefined outcome when i call output elsewhere.
This works see the following fiddle: jsfiddle.net/oje21wup change the match variable to get a different output.
0

You can in a way

var result = function() {
    if (busNumber[currentBus][2] == route[0]) {
       return "Correct!";
    }
    else {
       return "Incorrect!";
    } 
}();

though, technically you're assigning the result of a function to a variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.