Search code examples
javascriptecmascript-6ternary-operator

Code working with ternary operator but not with if else statements


This javascript program works with ternary operator as expected but not with if else statements. What I am doing wrong?

I am trying to solve some basic javascript exercises but I am stuck at this question. https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-74.php

//Working code with ternary operator
    function all_max(nums) {
      var max_val = nums[0] > nums[2] ? nums[0] : nums[2];

      nums[0] = max_val;
      nums[1] = max_val;
      nums[2] = max_val;

      return nums;
      }
    console.log(all_max([20, 30, 40]));
    console.log(all_max([-7, -9, 0]));
    console.log(all_max([12, 10, 3]));

// With if-else statement

  function all_max(nums) {
     if (var max_val = nums[0] > nums[2]) {
     return nums[0];
    } else {
     return nums[2];
  }

     nums[0] = max_value ;
     nums[1] = max_value ;
     nums[2] = max_value ;

return nums;
}
console.log(all_max([20, 30, 40]));
console.log(all_max([-7, -9, 0]));
console.log(all_max([12, 10, 3]));

Solution

  • You should be assigning the value in the body of the if/else statement, not within the comparison, so something like this should work for you:

    function all_max(nums) {
      let max_val = 0
      if (nums[0] > nums[2]) {
        max_val = nums[0];
      } else {
        max_val = nums[2];
      }
      nums[0] = max_val;
      nums[1] = max_val;
      nums[2] = max_val;
    
      return nums;
    }
    
    console.log(all_max([20, 30, 40]));
    console.log(all_max([-7, -9, 0]));
    console.log(all_max([12, 10, 3]));