Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
Compare an array with 0 in JavaScript

I was going through my company's code base and found a statement that compares an array with 0 like this:

array > 0;

if we let array = ["1"], which has a single element, the above statement would be true; but if let array = ["1", "2"] or [], the statement would become false;

Can someone explain the meaning of this statement, why it yields such results, and if it would be useful in any situation?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Since you are comparing the array to a number, JavaScript will cast it to a number. You can manually do this by doing Number(value). From my testing it seems like it just tries to cast the first value to a number. However, if there are multiple indexes, it returns NaN. And if there are no values it returns 0.

There's really not much use for the condition as far as I can imagine. It's hard to tell exactly what it's meant to do without context, but my guess is that it's a weird attempt to handle some edge case.

about 4 years ago · Juan Pablo Isaza Report

0

When you use >, the engine will first convert both sides to a primitive, which will call the valueOf, and, if that didn't return a primitive, then the toString method if it exists. For arrays, only the toString method returns a primitive, so that's what's used - and what it does is equivalent to doing .join(',').

console.log(['1', '2'].toString());

Looking at the spec again, after the array has been turned into a primitive, we now have one side that's a string (which came from the array), and another side that's a number. So, both sides are then converted to numbers:

d. Let nx be ? ToNumeric(px).
e. Let ny be ? ToNumeric(py).

And then the numbers are compared.

In the case of ['1'], you get 1 > 0, which is true.

In the case of ['1', '2'], the resulting string is '1,2', which cannot be converted into a number, so the following runs:

h. If nx or ny is NaN, return undefined.

and when undefined is returned by this algorithm, the whole > evaluates to false.

and if it would be useful in any situation?

For clean, understandable code, it generally wouldn't. Better to explicitly cast to types whose comparison makes intuitive sense first.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!