skip to Main Content

Here is my code :

function jeu(x, y) {
  let v1 = x,
    v2 = x;
  x > y ? v1 = y : v2 = y;
  alert(v2 - v1);
}

jeu(2, 10);

There is 2 parameters : x and y.

The two first line are putting to v1 the smallest value and to v2 the biggest as you can understand. But when I use some numbers like jeu(2,10), the code returns a negative number whereas I am doing "Biggest – Smallest".

Does anybody know why it does that ? (sorry for my bad english)(I can’t put this like code, idk why.

2

Answers


  1. In your case, "10" and "2" are treated as strings, not as numbers.

    If you want to perform numeric subtraction, you should convert the strings to numbers using parseInt() or parseFloat() like this:

    function jeu(x, y) {
      let v1 = parseInt(x, 10); // Convert x to an integer
      let v2 = parseInt(x, 10); // Convert x to an integer
      x > y ? v1 = parseInt(y, 10) : v2 = parseInt(y, 10);
      alert(v2 - v1);
    }
    
    jeu(2, 10);
    Login or Signup to reply.
  2. Instead of creating two variables v1 and v2 which are hard to understand, name them min and max. Assign both of them with conditional logic.

    function jeu(x, y) {
      const
        max = x > y ? x : y,
        min = x < y ? x : y;
      console.log(JSON.stringify({ min, max }));
      return max - min;
    }
    
    console.log(jeu(2, 10) === jeu(10, 2));

    May be overkill, but you could use Math.min and Math.max as well:

    function jeu(x, y) {
      const
        max = Math.max(x, y)
        min = Math.min(x, y);
      console.log(JSON.stringify({ min, max }));
      return max - min;
    }
    
    console.log(jeu(2, 10) === jeu(10, 2));

    The simpler version is calling Math.abs:

    function jeu(x, y) {
      return Math.abs(x - y);
    }
    
    console.log(jeu(2, 10) === jeu(10, 2));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search