I am trying to learn conditional statements in JavaScript, when I called the function with passing no argument still I am getting the x is equal to y. I don't understand where I m missing the code.
function tryMe(x, y) {
  if (x == y) {
    console.log("x and y are equal");
  } else if (x > y) {
    console.log("x is greater than y");
  } else if (x < y) {
    console.log("x is less than y")
  } else {
    console.log("no values")
  }
}
tryMe();
This is my console log:
x and y are equal // i am expecting it to console.log("no values")
This happens because when you call tryMe(), both x and y are undefined, meaning they are equal. So, you will need to check if there is value assigned to x and y first. 
function tryMe(x, y) {
  if (typeof(x) != 'undefined' && typeof(y) != 'undefined') {
    if (x == y) {
      console.log("x and y are equal");
    } else if (x > y) {
      console.log("x is greater than y");
    } else if (x < y) {
      console.log("x is less than y")
    } else {
      console.log("no values")
    }
  } else {
    console.log("no values")
  }
}
tryMe();
tryMe(1);
tryMe(1, 2);
Because undefined is equals to undefined
When you don't pass params, it get undefined both x and y
Why that happens - When you just declare a variable it's have default value undefined. Which is same happens in your case, your fn tryMe() declared x and y which has default value undefined and when you compare them then both are equal.
console.log(undefined == undefined)
var x, y
// Here you declared the variable which happens in your function
if(x === y) {
  console.log('You never defined what value I have so Javascript engine put undefined by default')
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With