Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional statements with no arguments

Tags:

javascript

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")

like image 445
Affy Avatar asked Nov 27 '22 19:11

Affy


2 Answers

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);
like image 59
Nidhin Joseph Avatar answered Nov 30 '22 23:11

Nidhin Joseph


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')
}
like image 36
Satyam Pathak Avatar answered Nov 30 '22 23:11

Satyam Pathak