Skip to content Skip to sidebar Skip to footer

What Does ' ', And " ", And No Quotes Mean In Javascript?

I realized I've been switching between them with no understanding as to why, and am finding it hard to search for.

Solution 1:

' ' and " " are the same thing; they are used to define string literals.

Things without quotes can be an identifier, keyword, non-string literal, property name or a number (may have missed one).

Examples:

"hello world"        literal (string)
'hello world'        literal (string) with same contents
document             identifier (object)
{ a: 1 }             property name
if                   keyword (start conditional statement)
3.4                  literal (number)
/abc/                literal (regex object)

String literals that are enclosed in single quotes don't need escaped double quotes and visa versa, e.g.:

'<a href="">click me</a>'    HTML containing double quotes"It's going to rain"String containing single quote

Solution 2:

' ' and " " used to quote string literal and represents string(s) whereas literal without quote are variables (name of variable, constant) know as identifier, example

variable = 'Hello'; (Here `variable` is identifier and 'Hello' is string literal)var = "Ho There"

You might question, what is the difference between ' (single quote) and " (Double quote)

Difference is ,strings within " if have special character then they need to escape. Example:

Variable = "hi " there"; ---> here you need to escape the " inside string like

Variable = "hi \" there"; 

But if using, ' then no need of escaping (unless there is a extra ' in string). You can hve like

var = 'Hello " World"';

Solution 3:

" and ' are interchangeable (but need to be used together).

myObject["property"] and myObject.property are also interchangeable. $var foo = "property"; myObject[foo] as well (per comment below).

Solution 4:

A quick jsfiddle around and both single and double quotes escape control codes etc.

In latter days I have had errors from HTML where double quotes have not been used, and if you look at the spec for JSON you'll note it is a double quote that is asked for when quoting string literals. So it is double quotes that is the convention I think, for historical reasons.

However! In these days of writing server side JS I must admit I tend to be pulled back to my C roots and double quote where I want escaped chars and single quote strings that are effectively literal chars and never likely to contain escaped chars (even though this is essentially non-productive behaviour). Besides which most of my JS is coffeescript nowadays anyway, nobody ever wrote javascript for elegance, CS is a different kettle of fish though.

Post a Comment for "What Does ' ', And " ", And No Quotes Mean In Javascript?"