3 ms·
The semantics are that primitives (string, number, boolean, undefined, symbol) can be compared by value and everything else (object, except null) is a reference
by eyelidlessness 4y ago
The semantics are that primitives (string, number, boolean, undefined, symbol) can be compared by value and everything else (object, except null) is a reference type with pointer identity regardless of the value. This might change in a meaningful way for collections if the records/tuples proposal succeeds. But even then those types will be considered primitives and won’t be allowed to contain reference types either.
Strings are primitives in JS, not just these days. They’re always value-equal unless they’re boxed (eg new String, which nobody ever does unless they’re doing something really weird). === would work the same way.
Edit: I guess more to the point about how strings differ from arrays of string bytes… the semantics are that they’re only superficially similar. They’re both a sequential collection of things that might be a string character (or part of one), and they might have some getter names in common with similar behaviors, but that’s where their similarities end.
- TeMPOraL 4y ago> Strings are primitives in JS, not just these days. Right. What I meant is whether they're interned - i.e. stuffed in a global table, in which strings (or at least string constants) are automatically looked up on parsing. If they were interned, both instances of "hello" in the expression "hello" == "hello" would parse into the same object, i.e. two pointers referencing the same character array, and thus could be compared in O(1) by comparing pointer addresses, instead of checking individual characters. This is how symbols (a distinct type from strings) are implemented in Lisp languages. I've heard some languages do that automatically as optimization for small strings. I vaguely recall JavaScript was supposed to get symbols too, a while ago. Anyway, per yours and sibling comments, I see the difference between strings and arrays is effectively determined by how operator == treats them.
- tuukkah 4y agoJavaScript has a symbol type but I think it's different. I don't see the JS spec saying anything about interning or time complexity. Here's some talk about how JS implementations intern compile-time constants and nothing else: https://stackoverflow.com/questions/5276915/do-common-javascript-implementations-use-string-interning https://stackoverflow.com/questions/5276915/do-common-javasc...
- jholman 4y agoI agree with the sibling comment that there is nothing in the spec saying whether or not strings are interned, and commend the reference there. Also, you probably meant the === operator, because discussing the == operator is a whole extra bag of worms.