When should I use double or single quotes in JavaScript?

前端 未结 30 3343
攒了一身酷
攒了一身酷 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:34

    The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.

    Using the other type of quote as a literal:

    alert('Say "Hello"');
    alert("Say 'Hello'");
    

    This can get complicated:

    alert("It's \"game\" time.");
    alert('It\'s "game" time.');
    

    Another option, new in ECMAScript 6, is template literals which use the backtick character:

    alert(`Use "double" and 'single' quotes in the same string`);
    alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);
    

    Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.

    Note that JSON is formally specified to use double quotes, which may be worth considering depending on system requirements.

    0 讨论(0)
  • 2020-11-21 05:35

    Strictly speaking, there is no difference in meaning; so the choice comes down to convenience.

    Here are several factors that could influence your choice:

    • House style: Some groups of developers already use one convention or the other.
    • Client-side requirements: Will you be using quotes within the strings? (See Ady's answer.)
    • Server-side language: VB.NET people might choose to use single quotes for JavaScript so that the scripts can be built server-side (VB.NET uses double-quotes for strings, so the JavaScript strings are easy to distinguished if they use single quotes).
    • Library code: If you're using a library that uses a particular style, you might consider using the same style yourself.
    • Personal preference: You might think one or other style looks better.
    0 讨论(0)
  • 2020-11-21 05:35

    One more thing that you might want to consider as a reason for the shift from double quotes to single quotes is the increase in popularity of server side scripts. When using PHP you can pass variables and parse JavaScript functions using strings and variables in PHP.

    If you write a string and use double quotes for your PHP you won't have to escape any of the single quotes and PHP will automatically retrieve the value of the variables for you.

    Example:I need to run a JavaScript function using a variable from my server.

    public static function redirectPage( $pageLocation )
    {
        echo "<script type='text/javascript'>window.location = '$pageLocation';</script>";
    }
    

    This saves me a lot of hassle in having to deal with joining strings, and I can effectively call a JavaScript from PHP. This is only one example, but this may be one of several reasons why programmers are defaulting to single quotes in JavaScript.

    Quote from PHP documents:

    The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

    0 讨论(0)
  • 2020-11-21 05:36

    I am not sure if this is relevant in today's world, but double quotes used to be used for content that needed to have control characters processed and single quotes for strings that didn't.

    The compiler will run string manipulation on a double quoted string while leaving a single quoted string literally untouched. This used to lead to 'good' developers choosing to use single quotes for strings that didn't contain control characters like \n or \0 (not processed within single quotes) and double quotes when they needed the string parsed (at a slight cost in CPU cycles for processing the string).

    0 讨论(0)
  • 2020-11-21 05:37

    I'd like to say the difference is purely stylistic, but I'm really having my doubts. Consider the following example:

    /*
        Add trim() functionality to JavaScript...
          1. By extending the String prototype
          2. By creating a 'stand-alone' function
        This is just to demonstrate results are the same in both cases.
    */
    
    // Extend the String prototype with a trim() method
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    };
    
    // 'Stand-alone' trim() function
    function trim(str) {
        return str.replace(/^\s+|\s+$/g, '');
    };
    
    document.writeln(String.prototype.trim);
    document.writeln(trim);
    

    In Safari, Chrome, Opera, and Internet Explorer (tested in Internet Explorer 7 and Internet Explorer 8), this will return the following:

    function () {
        return this.replace(/^\s+|\s+$/g, '');
    }
    function trim(str) {
        return str.replace(/^\s+|\s+$/g, '');
    }
    

    However, Firefox will yield a slightly different result:

    function () {
        return this.replace(/^\s+|\s+$/g, "");
    }
    function trim(str) {
        return str.replace(/^\s+|\s+$/g, "");
    }
    

    The single quotes have been replaced by double quotes. (Also note how the indenting space was replaced by four spaces.) This gives the impression that at least one browser parses JavaScript internally as if everything was written using double quotes. One might think, it takes Firefox less time to parse JavaScript if everything is already written according to this 'standard'.

    Which, by the way, makes me a very sad panda, since I think single quotes look much nicer in code. Plus, in other programming languages, they're usually faster to use than double quotes, so it would only make sense if the same applied to JavaScript.

    Conclusion: I think we need to do more research on this.

    This might explain Peter-Paul Koch's test results from back in 2003.

    It seems that single quotes are sometimes faster in Explorer Windows (roughly 1/3 of my tests did show a faster response time), but if Mozilla shows a difference at all, it handles double quotes slightly faster. I found no difference at all in Opera.

    2014: Modern versions of Firefox/Spidermonkey don’t do this anymore.

    0 讨论(0)
  • 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 = '<a href="' + url + '">Hello</a>';
    However, single quotes are just as legal in HTML.

    elem.innerHTML = "<a href='" + url + "'>Hello</a>";

    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.

    0 讨论(0)
提交回复
热议问题