When should I use double or single quotes in JavaScript?

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

    I hope I am not adding something obvious, but I have been struggling with Django, Ajax, and JSON on this.

    Assuming that in your HTML code you do use double quotes, as normally should be, I highly suggest to use single quotes for the rest in JavaScript.

    So I agree with ady, but with some care.

    My bottom line is:

    In JavaScript it probably doesn't matter, but as soon as you embed it inside HTML or the like you start to get troubles. You should know what is actually escaping, reading, passing your string.

    My simple case was:

    tbox.innerHTML = tbox.innerHTML + '

    ' + myThis[i].fields.title +' ' + myThis[i].fields.description +'

    '

    You can spot the ' in the third field of showThis.

    The double quote didn't work!

    It is clear why, but it is also clear why we should stick to single quotes... I guess...

    This case is a very simple HTML embedding, and the error was generated by a simple copy/paste from a 'double quoted' JavaScript code.

    So to answer the question:

    Try to use single quotes while within HTML. It might save a couple of debug issues...

提交回复
热议问题