When should I use double or single quotes in JavaScript?

前端 未结 30 3355
攒了一身酷
攒了一身酷 2020-11-21 05:02

console.log("double"); vs. console.log(\'single\');

I see more and more JavaScript libraries out there using single quotes when ha

30条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 05:37

    Examining the pros and cons

    In favor of single quotes

    • Less visual clutter.
    • Generating HTML: HTML attributes are usually delimited by double quotes.

    elem.innerHTML = 'Hello';
    However, single quotes are just as legal in HTML.

    elem.innerHTML = "Hello";

    Furthermore, inline HTML is normally an anti-pattern. Prefer templates.

    • Generating JSON: Only double quotes are allowed in JSON.

    myJson = '{ "hello world": true }';

    Again, you shouldn’t have to construct JSON this way. JSON.stringify() is often enough. If not, use templates.

    In favor of double quotes

    • Doubles are easier to spot if you don't have color coding. Like in a console log or some kind of view-source setup.
    • Similarity to other languages: In shell programming (Bash etc.), single-quoted string literals exist, but escapes are not interpreted inside them. C and Java use double quotes for strings and single quotes for characters.
    • If you want code to be valid JSON, you need to use double quotes.

    In favor of both

    There is no difference between the two in JavaScript. Therefore, you can use whatever is convenient at the moment. For example, the following string literals all produce the same string:

        "He said: \"Let's go!\""
        'He said: "Let\'s go!"'
        "He said: \"Let\'s go!\""
        'He said: \"Let\'s go!\"'

    Single quotes for internal strings and double for external. That allows you to distinguish internal constants from strings that are to be displayed to the user (or written to disk etc.). Obviously, you should avoid putting the latter in your code, but that can’t always be done.

提交回复
热议问题