What is the difference between string primitives and String objects in JavaScript?

前端 未结 12 1700
孤街浪徒
孤街浪徒 2020-11-22 07:58

Taken from MDN

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., witho

12条回答
  •  庸人自扰
    2020-11-22 08:40

    The biggest difference between a string primitive and a string object is that objects must follow this rule for the == operator:

    An expression comparing Objects is only true if the operands reference the same Object.

    So, whereas string primitives have a convenient == that compares the value, you're out of luck when it comes to making any other immutable object type (including a string object) behave like a value type.

    "hello" == "hello"
    -> true
    new String("hello") == new String("hello") // beware!
    -> false
    

    (Others have noted that a string object is technically mutable because you can add properties to it. But it's not clear what that's useful for; the string value itself is not mutable.)

提交回复
热议问题