3

Possible Duplicate:
When to Use Double or Single Quotes in JavaScript

I think $('#id') and $("#id") both is valid so " and ' character is samething and it is just preference to use ' instead of " ?

Community
  • 1
  • 1
Freshblood
  • 6,285
  • 10
  • 59
  • 96

3 Answers3

6

Single- and double-quotes do the same thing in JavaScript: they delimit string constants. It's convenient (though a little weird) to have both types of quotes available for the same purpose, because it makes quoting strings with embedded quotes a little easier sometimes. One example: jQuery selectors:

$('input[name="my input"]').val('');
Pointy
  • 405,095
  • 59
  • 585
  • 614
1

jQuery is just a JavaScript library.

A string quoted with ' characters have have " characters inside it without them being escaped — and vice versa — that is all.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Right, JQuery is just framework of javascript but it always looks like have different syntax with $ character. – Freshblood Dec 26 '10 at 22:10
  • Sadly, stupid variable names do not stop JavaScript being JavaScript. – Quentin Dec 26 '10 at 22:13
  • 1
    @Freshblood: `$` is just an identifier like `x` or `hasNinjas`. – Mark Byers Dec 26 '10 at 22:14
  • @David - why stupid? they make your life easier? – ifaour Dec 26 '10 at 23:40
  • @ifaour: It's just a matter of opinion. The ECMA standard says that the $ character is valid but recommends it to be reserved for machine generated code - like code generated by GWT or a macro processor or, if they exist, self-aware robots. So some purists consider them stupid since they don't consider regular programmers to be robots. I for one know some people in HR, marketing and accounting who think programmers are closely related to robots. – slebetman Dec 27 '10 at 00:03
  • Stupid because it is a meaningless symbol. Variables should be meaningful. `$` says nothing about its purpose, and even if you know it is a magic function name, it doesn't tell you if it is jQuery's `$` or MooTool's `$` or Prototype.js's `$` or another `$` entirely. – Quentin Dec 27 '10 at 00:26
0

' and " may be used interchangeably in JavaScript/jQuery.

It's a little more robust to use '.

Why? Because it's easier to move JavaScript code between script tags and inline HTML elements - common XHTML syntax is to wrap event code in "" (eg onclick="alert('foo')"). Using single quotes prevents the need to escape (eg "alert(\"foo\")"), and allows you to easily move the code from the inline to an external script page.

vol7ron
  • 40,809
  • 21
  • 119
  • 172
  • `'` and `"` are equivalent in xml too, so you could write `onclick='alert("foo")'` and still be valid. Since languages which do make a distinction often opt for `"` to wrap strings, I tend to stick with that in JS. – Douglas Dec 26 '10 at 22:41
  • @Douglas: that is exactly correct. I said "proper" and meant "common". Fixed - great catch. – vol7ron Dec 26 '10 at 23:13