Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - use apostrophes or quotation marks? [duplicate]

For string literals, are any differences between using apostrophes or using quotes? I'm thinking in regard to performance, functionality, conventions, etc.

To clarify:

'Hello!'

vs.

"Hello!"

(for want of a more imaginative string)

like image 581
Jay Avatar asked Mar 16 '13 04:03

Jay


2 Answers

For me i use it depending on the contents of the string - will the string itself have double quotes or single quotes? if the string has one type of quote, i'll use the other so i don't have to escape it: e.g.:

my string is: <div class="someclass" >hello</div>

for the above i'd use single quote so i don't have to escape the single ones:

var str = '<div class="someclass" >hello</div>';

otherwise id need

var str = "<div class=\"someclass\" >hello</div>";

both are perfectly valid, but ones more easy on the coder...

like image 142
Tucker Avatar answered Sep 17 '22 23:09

Tucker


I wouldn't say there is a preferred method, you can use either. However If you are using one form of quote in the string, you might want to use the other as the literal.

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

The most likely reason is programmer preference / API consistency.

The difference is that you don't need to escape single quotes in double quotes, or double quotes in single quotes. That is the only difference, if you do not count the fact that you must hold the Shift key to type "

like image 20
Vitthal Avatar answered Sep 17 '22 23:09

Vitthal