Back

Technologies:

javascriptjavascript
avatar
Tolerim
22 days ago

The conditional statement of if-else is not being performed.

The given question contains code that is not executing the if-else conditions and only displaying the variables in an alert. Can anyone please help me understand why this is happening? I have tried going over my code but I am still unable to figure out the issue. Here is the code snippet:


  
var dni= 12345678; 
var typeOfService = 1; 

if (typeOfService === 1){
    sum = 750 - (750*0.10); 
} else if (typeOfService === 2){
    sum = 930 - (930 - 0.05);
} else if (typeOfService ===3){
    sum = 1200; 
}

console.log("The customer " + dni + " has to pay the total of " + sum)
Thank you in advance for your help!
Answers(2)
avatar
Vogi
21 days ago
Verified Answer
The issue with the code is that the variable sum is not declared before it is used. You can fix this by adding var sum; before the if-else statements. Here is the corrected code:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
    <pre class="snippet-code-js lang-js prettyprint-override"><code>var dni= 12345678; 
var typeOfService = 1; 
var sum;

if (typeOfService === 1){
    sum = 750 - (750*0.10); 
} else if (typeOfService === 2){
    sum = 930 - (930 - 0.05);
} else if (typeOfService ===3){
    sum = 1200; 
}

console.log("The customer " + dni + " has to pay the total of " + sum)</code></pre>
  </div>
</div>
I hope this helps! Let me know if you have any other questions.

Sources

if statement - "IF ELSE" Javascript not working - Stack Overflowjavascript - `else if` is never executed; only the preceding `if` is ...javascript - Why is my if-else statement not executing correctly ...Avoid if-else hell in javascript - LinkedInjavascript if/else not working - Stack Overflowif...else - JavaScript | MDN - Mozilla Developer
avatar
Tolerim
22 days ago
The issue is with your console.log() statement. You are not printing the sum variable that you have computed based on the typeOfService conditionals. Instead, you are printing typeOfService. Here's the corrected code:
var dni= 12345678; 
var typeOfService = 1; 
var sum;

if (typeOfService === 1){
    sum = 750 - (750*0.10); 
} else if (typeOfService === 2){
    sum = 930 - (930 - 0.05);
} else if (typeOfService ===3){
    sum = 1200; 
}

console.log("The customer " + dni + " you have to pay the total of " + sum)
This should now correctly output:
;