When should I use double or single quotes in JavaScript?

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

    If you're doing inline JavaScript (arguably a "bad" thing, but avoiding that discussion) single quotes are your only option for string literals, I believe.

    E.g., this works fine:

    hi
    

    But you can't wrap the "hi" in double quotes, via any escaping method I'm aware of. Even " which would have been my best guess (since you're escaping quotes in an attribute value of HTML) doesn't work for me in Firefox. " won't work either because at this point you're escaping for HTML, not JavaScript.

    So, if the name of the game is consistency, and you're going to do some inline JavaScript in parts of your application, I think single quotes are the winner. Someone please correct me if I'm wrong though.

提交回复
热议问题