Single and Double Quote



Javascript Single Quote or Double Quote

JavaScript, allows you to use either double quote or single quote marks to create a string. The following two assignments are equivalent

var x ="Javascript at referencedesigner.com";
var x = 'Javascript at referencedesigner.com';


If you do not include both the opening as well as the closing quote marks, or you will get "Unterminated string literal" error in Firefox. Mixing up the single and double quote in same string is not allowed. So,

var x = 'Javascript at referencedesigner.com"; 


is incorrect but the following two in the same web page is ok.

var x ="Javascript at referencedesigner.com";
var y = 'Javascript at referencedesigner.com';



Quote mark within a quote

The use of quotations within a string generates error. As an example

var message='Javascript's beauty is simplicity';


There is no way for the browser to know which one is the closing quote. The interpreter sees the second quote in 'Javascript's as the ending quote - so rest of the line becomes invalid. In Firefox error console, you’ll get the message - "Missing ; before statement".

How to fix issue of quote within quote

You can exploit the fact that javascript allows single as well as double quote to mix and match and avoid repetition of either single quote or the double quote. Simple put, you can put double quotes around a string with single quotes, or single quotes around a string containing double quotes.

As an example the following two are javascript statements are error free

var x="John's father wanted him to learn javascript from referencedesigner.com site";
var y='His father said, "Learn javascript from referencedesigner.com site"';


A second approach take by programmers is to escape the quote marks. To escape a character you precede it with forward slask mark \.

The following two sentences are valid

var x='John\'s father wanted him to learn javascript from referencedesigner.com site\;
var y="His father said, \"Learn javascript from referencedesigner.com site\"";