Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 11, 2022 06:54 pm GMT

Equality of values in JavaScript

I'm currently doing the JustJavascript course, which I highly recommend, and I've learned how equality of values works in JavaScript.

There are 3 kinds of equality in JavaScript.

  • Same value equality: Object.is(a, b).
  • Strict equality: a === b (triple equals).
  • Loose equality: a == b (double equals).

Same value equality

Object.is(a, b) tells us if a and b are the same value:

Object.is(2, 2); //  trueObject.is(undefined, undefined); //  trueObject.is(null, null); //  trueObject.is(true, true); //  trueObject.is(1, 1); //  trueObject.is(-1, -1); //  trueObject.is("Hello", "Hello"); //  trueObject.is({}, {}); //  falseObject.is([], []); //  false

Strict equality

Strict equality works like Object.is but there are two exceptions.

1. NaN === NaN is false, although they are the same value in JavaScript.

There are some ways to safely check if two values are NaN:

  • Number.isNaN(variable)
  • Object.is(variable, NaN)
  • variable !== variable
NaN === NaN; //  falseObject.is(NaN, NaN); //  trueNumber.isNaN(NaN); //  trueNaN !== NaN; //  true

2. -0 === 0 and 0 === -0 are true, although they are different values in JavaScript.

In the common math that we all learn at school negative zero does not exist, but it exists in floating-point math forpractical reasons.

0 === -0; //  trueObject.is(0, -0); //  false

Loose equality

Loose equality is very confusing and that's why it's recommended not to use it. As an example, see these cases:

[[]] == ""; // truetrue == [1]; // truefalse == [0]; // true

If you still want to learn how it works, you can read more about it here.

Resources


Original Link: https://dev.to/jmalvarez/equality-of-values-in-javascript-hgd

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To