David Ayeke
David Ayeke

Reputation: 26

Why does this code return the results that it does

When I run this in node I get the following result. Why?

//Why does this code return the results that it does?
function isBig(thing) {
  if (thing == 0 || thing == 1 || thing == 2) {
    return false
  }
  return true
}
isBig(1)    // false
isBig([2])  // false
isBig([3])  // true

Upvotes: 0

Views: 82

Answers (3)

kemotoe
kemotoe

Reputation: 1777

To piggy back on what Mark_M said when you pass the [2] and [3] to the function it's treating them as object literals instead of numbers. Then in your function call its typecasting them for the comparison.

console.log(typeof(1));
console.log(typeof[2]);
console.log(typeof[3]);

Upvotes: 0

obecker
obecker

Reputation: 2377

The == operator in JavaScript converts its operands into a common type before checking for equality (that's why it is recommended always to use the === operator, which respects the types). In your case the common type is number, so the each given array is converted into a number. For a single element array the conversion into a number results in the single element (converted to a number).

The parameter [2] equals the number 2, so return false. [3] on the other hand does neither equal 0, 1, or 2, so return true.

See also https://www.w3schools.com/js/js_type_conversion.asp for more examples.

Upvotes: 1

Mark
Mark

Reputation: 92440

== compares equity loosely.

To quote developer.mozilla.org

Loose equality compares two values for equality, after converting both values to a common type.

This means that [2] == 2 is true it also means "2" == 2 is true

and it's why it is so often recommended to use strict equality so that [2] === 2 is false unless you are really looking for the conversion.

Upvotes: 0

Related Questions