When should I use double or single quotes in JavaScript?

前端 未结 30 3430
攒了一身酷
攒了一身酷 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: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 "";
    }
    

    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.

提交回复
热议问题