Home > JavaScript > JavaScript String: Single or Double Quote?

JavaScript String: Single or Double Quote?

If you come from a strongly typed language like C++ to JavaScript you’ll definitely confused the way strings are represented in it.

In JavaScript you can use both single and double quotes to represent a string. Also you can use both single and double quotes in a single line too but the nesting order should be maintained ie if you start a double or single quote then you must finish it before using a different quote. For example

var strStudentName = "Tom" + ' Thomas'; //Correct 
var strStudentAddress = "12/56, ' + 'Arizona "; //Incorrect; due to the quote nesting issues

So the best part is the user can represent the string in JavaScript any way they want. But a question at this point is which method is the proper one?

There is no definite answer as both single and double quotes are interchangeable and you can use whatever you find convenient.

Still I feel that we should use single quotes in JavaScript to represent strings. One of the reason I found is this style is useful especially if you are dealing with HTML markup strings in JavaScript. In HTML the double quotes used for storing attributes. An example would be

var strHtml = '<div id="p0_content">This is a test</div>";

In the above code snippet we’ve used single quote for the string value and double quotes for enclosing the attribute value in the markup. It looks simple and elegant.

About these ads
Categories: JavaScript
  1. July 20, 2014 at 9:00 pm

    I see a lot of interesting posts on your website. You have to spend
    a lot of time writing, i know how to save you a
    lot of work, there is a tool that creates unique, SEO friendly posts in couple of
    seconds, just type in google – k2 unlimited content

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: