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

前端 未结 12 1522
孤街浪徒
孤街浪徒 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:36

    If you use new, you're explicitly stating that you want to create an instance of an Object. Therefore, new String is producing an Object wrapping the String primitive, which means any action on it involves an extra layer of work.

    typeof new String(); // "object"
    typeof '';           // "string"
    

    As they are of different types, your JavaScript interpreter may also optimise them differently, as mentioned in comments.

提交回复
热议问题