1

I understand that the answer to this is it's in the specs but what, if any, is the logic behind it?

Welcome to Node.js v19.0.0.
Type ".help" for more information.
> !!''
false
> !![]
true

A String, to my understanding, is really an array with some extra functionality added to make text easier to work with, it still does all the array-like things though so why is an empty string falsey but an empty array is truthy?

Reporter
  • 3,897
  • 5
  • 33
  • 47
BanksySan
  • 27,362
  • 33
  • 117
  • 216
  • 4
    A string is a primitive type and an array is an object. Objects are *always* truthy. That is a simple rule. – trincot Jul 07 '23 at 09:29
  • `null` is an object, too. but not *[truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)*. – Nina Scholz Jul 07 '23 at 09:30
  • 1
    `null` is not an object, but a primitive. It has `typeof` equal to `"object"`, but that is a different story. – trincot Jul 07 '23 at 09:30
  • Strings act in a similar way to arrays, but, in javascript at least, they are *not* arrays. eg you can reference a character with `mystring[0]` but you can't add characters with `mystring.push("end")`. Note that strings *are* immutable. See [this question](https://stackoverflow.com/questions/51185/are-javascript-strings-immutable-do-i-need-a-string-builder-in-javascript) for more info on strings. – freedomn-m Jul 07 '23 at 09:32

1 Answers1

-1

Let's make it simple:

!!''

An empty string in JavaScript is considered a "falsy" value. It is treated as a boolean false when evaluated in a boolean context.

!![]

Arrays, whether it contains items or not, are considered "truthy" values in Javascript. They are treated as a boolean true when evaluated in a boolean context.

Raptor
  • 53,206
  • 45
  • 230
  • 366
  • 2
    This appears to just repeat the question - statement of fact rather than reasons. – freedomn-m Jul 07 '23 at 09:34
  • shall I say, *it's by definition* that, objects are truthy, empty strings are falsey? I thought I already mentioned the logic, which is the OP is asking. – Raptor Jul 07 '23 at 09:36
  • 1
    OP isn't asking about the "logic" of true/false, OP is asking about the philosophical *logic* - ie the *reasoning* of *why* it works like this. OP already stated they know it does work like this. They key is the phrase "*the logic behind it*" – freedomn-m Jul 07 '23 at 09:44