How is "first-name" a reserved word in JavaScript? - javascript

Note: This question pertains to the book 'JavaScript: The Good Parts' written by Doug Crockford.
As I was reading a chapter on Objects, I came across a statement as follows:
The quotes around a property's name in an object literal are optional if the name would be a legal JavaScript name and not a reserved word. So quotes are required around "first-name", but are optional around "first_name".
And the following is the example of an object literal provided in the book:
var stooge = {
"first-name": "Jerome",
"last-name": "Howard"
};
Now, I might have misinterpreted the text here but to me it seems like Mr. Crockford is saying first-name (with the hyphen) IS a reserved word whereas first_name (with the underscore) is not. If that is the case, I don't understand how the former can be a reserved word. I found no other explanation in the book why this is. Can someone please explain?

It is not a reserved word. Without the quotes, javascript will interpret the - character as a subtraction operator, attempt to perform the operation, and fail.
One reason for this is that javascript prefers to ignore whitespace whenever it can. Thus 2 - 3 is the same as 2-3.
Putting the whole thing in quotes causes the js to interpret as just another character, not an operator.

Related

single quotations vs double quotations [duplicate]

Consider the following two alternatives:
console.log("double");
console.log('single');
The former uses double quotes around the string, whereas the latter uses single quotes around the string.
I see more and more JavaScript libraries out there using single quotes when handling strings.
Are these two usages interchangeable? If not, is there an advantage in using one over the other?
The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.
Using the other type of quote as a literal:
alert('Say "Hello"');
alert("Say 'Hello'");
This can get complicated:
alert("It's \"game\" time.");
alert('It\'s "game" time.');
Another option, new in ECMAScript 6, is template literals which use the backtick character:
alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);
Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.
Note that JSON is formally specified to use double quotes, which may be worth considering depending on system requirements.
If you're dealing with JSON, it should be noted that strictly speaking, JSON strings must be double quoted. Sure, many libraries support single quotes as well, but I had great problems in one of my projects before realizing that single quoting a string is in fact not according to JSON standards.
There is no one better solution; however, I would like to argue that double quotes may be more desirable at times:
Newcomers will already be familiar with double quotes from their language. In English, we must use double quotes " to identify a passage of quoted text. If we were to use a single quote ', the reader may misinterpret it as a contraction. The other meaning of a passage of text surrounded by the ' indicates the 'colloquial' meaning. It makes sense to stay consistent with pre-existing languages, and this may likely ease the learning and interpretation of code.
Double quotes eliminate the need to escape apostrophes (as in contractions). Consider the string: "I'm going to the mall", vs. the otherwise escaped version: 'I\'m going to the mall'.
Double quotes mean a string in many other languages. When you learn a new language like Java or C, double quotes are always used. In Ruby, PHP and Perl, single-quoted strings imply no backslash escapes while double quotes support them.
JSON notation is written with double quotes.
Nonetheless, as others have stated, it is most important to remain consistent.
Section 7.8.4 of the specification describes literal string notation. The only difference is that DoubleStringCharacter is "SourceCharacter but not double-quote" and SingleStringCharacter is "SourceCharacter but not single-quote". So the only difference can be demonstrated thusly:
'A string that\'s single quoted'
"A string that's double quoted"
So it depends on how much quote escaping you want to do. Obviously the same applies to double quotes in double quoted strings.
I'd like to say the difference is purely stylistic, but I'm really having my doubts. Consider the following example:
/*
Add trim() functionality to JavaScript...
1. By extending the String prototype
2. By creating a 'stand-alone' function
This is just to demonstrate results are the same in both cases.
*/
// Extend the String prototype with a trim() method
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
// 'Stand-alone' trim() function
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
};
document.writeln(String.prototype.trim);
document.writeln(trim);
In Safari, Chrome, Opera, and Internet Explorer (tested in Internet Explorer 7 and Internet Explorer 8), this will return the following:
function () {
return this.replace(/^\s+|\s+$/g, '');
}
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
However, Firefox will yield a slightly different result:
function () {
return this.replace(/^\s+|\s+$/g, "");
}
function trim(str) {
return str.replace(/^\s+|\s+$/g, "");
}
The single quotes have been replaced by double quotes. (Also note how the indenting space was replaced by four spaces.) This gives the impression that at least one browser parses JavaScript internally as if everything was written using double quotes. One might think, it takes Firefox less time to parse JavaScript if everything is already written according to this 'standard'.
Which, by the way, makes me a very sad panda, since I think single quotes look much nicer in code. Plus, in other programming languages, they're usually faster to use than double quotes, so it would only make sense if the same applied to JavaScript.
Conclusion: I think we need to do more research on this.
This might explain Peter-Paul Koch's test results from back in 2003.
It seems that single quotes are sometimes faster in Explorer Windows (roughly 1/3 of my tests did show a faster response time), but if Mozilla shows a difference at all, it handles double quotes slightly faster. I found no difference at all in Opera.
2014: Modern versions of Firefox/Spidermonkey don’t do this anymore.
If you're doing inline JavaScript (arguably a "bad" thing, but avoiding that discussion) single quotes are your only option for string literals, I believe.
E.g., this works fine:
<a onclick="alert('hi');">hi</a>
But you can't wrap the "hi" in double quotes, via any escaping method I'm aware of. Even " which would have been my best guess (since you're escaping quotes in an attribute value of HTML) doesn't work for me in Firefox. " won't work either because at this point you're escaping for HTML, not JavaScript.
So, if the name of the game is consistency, and you're going to do some inline JavaScript in parts of your application, I think single quotes are the winner. Someone please correct me if I'm wrong though.
Technically there's no difference. It's only matter of style and convention.
Douglas Crockford1 recommends using double quotes.
I personally follow that.
Strictly speaking, there is no difference in meaning; so the choice comes down to convenience.
Here are several factors that could influence your choice:
House style: Some groups of developers already use one convention or the other.
Client-side requirements: Will you be using quotes within the strings? (See Ady's answer.)
Server-side language: VB.NET people might choose to use single quotes for JavaScript so that the scripts can be built server-side (VB.NET uses double-quotes for strings, so the JavaScript strings are easy to distinguished if they use single quotes).
Library code: If you're using a library that uses a particular style, you might consider using the same style yourself.
Personal preference: You might think one or other style looks better.
Just keep consistency in what you use. But don't let down your comfort level.
"This is my string."; // :-|
"I'm invincible."; // Comfortable :)
'You can\'t beat me.'; // Uncomfortable :(
'Oh! Yes. I can "beat" you.'; // Comfortable :)
"Do you really think, you can \"beat\" me?"; // Uncomfortable :(
"You're my guest. I can \"beat\" you."; // Sometimes, you've to :P
'You\'re my guest too. I can "beat" you too.'; // Sometimes, you've to :P
ECMAScript 6 update
Using template literal syntax.
`Be "my" guest. You're in complete freedom.`; // Most comfort :D
I hope I am not adding something obvious, but I have been struggling with Django, Ajax, and JSON on this.
Assuming that in your HTML code you do use double quotes, as normally should be, I highly suggest to use single quotes for the rest in JavaScript.
So I agree with ady, but with some care.
My bottom line is:
In JavaScript it probably doesn't matter, but as soon as you embed it inside HTML or the like you start to get troubles. You should know what is actually escaping, reading, passing your string.
My simple case was:
tbox.innerHTML = tbox.innerHTML + '<div class="thisbox_des" style="width:210px;" onmouseout="clear()"><a href="/this/thislist/'
+ myThis[i].pk +'"><img src="/site_media/'
+ myThis[i].fields.thumbnail +'" height="80" width="80" style="float:left;" onmouseover="showThis('
+ myThis[i].fields.left +','
+ myThis[i].fields.right +',\''
+ myThis[i].fields.title +'\')"></a><p style="float:left;width:130px;height:80px;"><b>'
+ myThis[i].fields.title +'</b> '
+ myThis[i].fields.description +'</p></div>'
You can spot the ' in the third field of showThis.
The double quote didn't work!
It is clear why, but it is also clear why we should stick to single quotes... I guess...
This case is a very simple HTML embedding, and the error was generated by a simple copy/paste from a 'double quoted' JavaScript code.
So to answer the question:
Try to use single quotes while within HTML. It might save a couple of debug issues...
It's mostly a matter of style and preference. There are some rather interesting and useful technical explorations in the other answers, so perhaps the only thing I might add is to offer a little worldly advice.
If you're coding in a company or team, then it's probably a good idea to follow the "house style".
If you're alone hacking a few side projects, then look at a few prominent leaders in the community. For example, let's say you getting into Node.js. Take a look at core modules, for example, Underscore.js or express and see what convention they use, and consider following that.
If both conventions are equally used, then defer to your personal preference.
If you don't have any personal preference, then flip a coin.
If you don't have a coin, then beer is on me ;)
I am not sure if this is relevant in today's world, but double quotes used to be used for content that needed to have control characters processed and single quotes for strings that didn't.
The compiler will run string manipulation on a double quoted string while leaving a single quoted string literally untouched. This used to lead to 'good' developers choosing to use single quotes for strings that didn't contain control characters like \n or \0 (not processed within single quotes) and double quotes when they needed the string parsed (at a slight cost in CPU cycles for processing the string).
If you are using JSHint, it will raise an error if you use a double quoted string.
I used it through the Yeoman scafflholding of AngularJS, but maybe there is somehow a manner to configure this.
By the way, when you handle HTML into JavaScript, it's easier to use single quote:
var foo = '<div class="cool-stuff">Cool content</div>';
And at least JSON is using double quotes to represent strings.
There isn't any trivial way to answer to your question.
There isn't any difference between single and double quotes in JavaScript.
The specification is important:
Maybe there are performance differences, but they are absolutely minimum and can change any day according to browsers' implementation. Further discussion is futile unless your JavaScript application is hundreds of thousands lines long.
It's like a benchmark if
a=b;
is faster than
a = b;
(extra spaces)
today, in a particular browser and platform, etc.
Examining the pros and cons
In favor of single quotes
Less visual clutter.
Generating HTML: HTML attributes are usually delimited by double quotes.
elem.innerHTML = 'Hello';
However, single quotes are just as legal in HTML.
elem.innerHTML = "<a href='" + url + "'>Hello</a>";
Furthermore, inline HTML is normally an anti-pattern. Prefer templates.
Generating JSON: Only double quotes are allowed in JSON.
myJson = '{ "hello world": true }';
Again, you shouldn’t have to construct JSON this way. JSON.stringify() is often enough. If not, use templates.
In favor of double quotes
Doubles are easier to spot if you don't have color coding. Like in a console log or some kind of view-source setup.
Similarity to other languages: In shell programming (Bash etc.), single-quoted string literals exist, but escapes are not interpreted inside them. C and Java use double quotes for strings and single quotes for characters.
If you want code to be valid JSON, you need to use double quotes.
In favor of both
There is no difference between the two in JavaScript. Therefore, you can use whatever is convenient at the moment. For example, the following string literals all produce the same string:
"He said: \"Let's go!\""
'He said: "Let\'s go!"'
"He said: \"Let\'s go!\""
'He said: \"Let\'s go!\"'
Single quotes for internal strings and double for external. That allows you to distinguish internal constants from strings that are to be displayed to the user (or written to disk etc.). Obviously, you should avoid putting the latter in your code, but that can’t always be done.
Talking about performance, quotes will never be your bottleneck. However, the performance is the same in both cases.
Talking about coding speed, if you use ' for delimiting a string, you will need to escape " quotes. You are more likely to need to use " inside the string. Example:
// JSON Objects:
var jsonObject = '{"foo":"bar"}';
// HTML attributes:
document.getElementById("foobar").innerHTML = '<input type="text">';
Then, I prefer to use ' for delimiting the string, so I have to escape fewer characters.
There are people that claim to see performance differences: old mailing list thread. But I couldn't find any of them to be confirmed.
The main thing is to look at what kind of quotes (double or single) you are using inside your string. It helps to keep the number of escapes low. For instance, when you are working with HTML content inside your strings, it is easier to use single quotes so that you don't have to escape all double quotes around the attributes.
When using CoffeeScript I use double quotes. I agree that you should pick either one and stick to it. CoffeeScript gives you interpolation when using the double quotes.
"This is my #{name}"
ECMAScript 6 is using back ticks (`) for template strings. Which probably has a good reason, but when coding, it can be cumbersome to change the string literals character from quotes or double quotes to backticks in order to get the interpolation feature. CoffeeScript might not be perfect, but using the same string literals character everywhere (double quotes) and always be able to interpolate is a nice feature.
`This is my ${name}`
I would use double quotes when single quotes cannot be used and vice versa:
"'" + singleQuotedValue + "'"
'"' + doubleQuotedValue + '"'
Instead of:
'\'' + singleQuotedValue + '\''
"\"" + doubleQuotedValue + "\""
There is strictly no difference, so it is mostly a matter of taste and of what is in the string (or if the JavaScript code itself is in a string), to keep number of escapes low.
The speed difference legend might come from PHP world, where the two quotes have different behavior.
The difference is purely stylistic. I used to be a double-quote Nazi. Now I use single quotes in nearly all cases. There's no practical difference beyond how your editor highlights the syntax.
You can use single quotes or double quotes.
This enables you for example to easily nest JavaScript content inside HTML attributes, without the need to escape the quotes.
The same is when you create JavaScript with PHP.
The general idea is: if it is possible use such quotes that you won't need to escape.
Less escaping = better code.
In addition, it seems the specification (currently mentioned at MDN) doesn't state any difference between single and double quotes except closing and some unescaped few characters. However, template literal (` - the backtick character) assumes additional parsing/processing.
A string literal is 0 or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for the closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), and U+000A (LINE FEED). Any code points may appear in the form of an escape sequence. String literals evaluate to ECMAScript String values...
Source: https://tc39.es/ecma262/#sec-literals-string-literals

[Nearley]: how to parse matching opening and closing tag

I'm trying to parse a very simple language with nearley: you can put a string between matching opening and closing tags, and you can chain some tags. It looks like a kind of XML, but with[ instead of < , with tag always 2 chars long, and without nesting.
[aa]My text[/aa][ab]Another Text[/ab]
But I don't seem to be able to parse correctly this, as I get the grammar should be unambiguous as soon as I have more than one tag.
The grammar that I have right now:
#builtin "string.ne"
#builtin "whitespace.ne"
openAndCloseTag[X] -> "[" $X "]" string "[/" $X "]"
languages -> openAndCloseTag[[a-zA-Z] [a-zA-Z]] (_ openAndCloseTag[[a-zA-Z] [a-zA-Z]]):*
string -> sstrchar:* {% (d) => d[0].join("") %}
And related, Ideally I would like the tags to be case insensitive (eg. [bc]TESt[/BC] would be valid)
Has anyone any idea how we can do that? I wasn't able to find a nearley XML parser example .
Your language is almost too simple to need a parser generator. And at the same time, it is not context free, which makes it difficult to use a parser generator. So it is quite possible that the Nearly parser is not the best tool for you, although it is probably possible to make it work with a bit of hackery.
First things first. You have not actually provided an unambiguous definition of your language, which is why your parser reports an ambiguity. To see the ambiguity, consider the input
[aa]My text[/ab][ab]Another Text[/aa]
That's very similar to your test input; all I did was swap a pair of letters. Now, here's the question: Is that a valid input consisting of a single aa tag? Or is it a syntax error? (That's a serious question. Some definitions of tagging systems like this consider a tag to only be closed by a matching close tag, so that things which look like different tags are considered to be plain text. Such systems would accept the input as a single tagged value.)
The problem is that you define string as sstrchar:*, and if we look at the definition of sstrchar in string.ne, we see (leaving out the postprocessing actions, which are irrelevant):
sstrchar -> [^\\'\n]
| "\\" strescape
| "\\'"
Now, the first possibility is "any character other than a backslash, a single quote or a newline", and it's easy to see that all of the characters in [/ab] are in sstrchar. (It's not clear to me why you chose sstrchar; single quotes don't appear to be special in your language. Or perhaps you just didn't mention their significance.) So a string could extend up to the end of the input. Of course, the syntax requires a closing tag, and the Nearley parser is determined to find a match if there is one. But, in fact, there are two of them. So the parser declares an ambiguity, since it doesn't have any criterion to choose between the two close tags.
And here's where we come up against the issue that your language is not context-free. (Actually, it is context-free in some technical sense, because there are "only" 676 two-letter case-insensitive tags, and it would theoretically be possible to list all 676 possibilities. But I'm guessing you don't want to do that.)
A context-free grammar cannot express a language that insists that two non-terminals expand to the same string. That's the very definition of context-free: if one non-terminal can only match the same input as a previous non-terminal, then
the second non-terminals match is dependent on the context, specifically on the match produced by the first non-terminal. In a context-free grammar, a non-terminal expands to the same thing, regardless of the rest of the text. The context in which the non-terminal appears is not allowed to influence the expansion.
Now, you quite possibly expected that your macro definition:
openAndCloseTag[X] -> "[" $X "]" string "[/" $X "]"
is expressing a context-sensitive match by repeating the $X macro parameter. But it is not by accident that the Nearley documentation describes this construct as a macro. X here refers exactly to the string used in the macro invocation. So when you say:
openAndCloseTag[[a-zA-Z] [a-zA-Z]]
Nearly macro expands that to
"[" [a-zA-Z] [a-zA-Z] "]" string "[/" [a-zA-Z] [a-zA-Z] "]"
and that's what it will use as the grammar production. Observe that the two $X macro parameters were expanded to the same argument, but that doesn't mean that will match the same input text. Each of those subpatterns will independently match any two alphabetic characters. Context-freely.
As I alluded to earlier, you could use this macro to write out the 676 possible tag patterns:
tag -> openAndCloseTag["aa"i]
| openAndCloseTag["ab"i]
| openAndCloseTag["ac"i]
| ...
| openAndCloseTag["zz"i]
If you did that (and you managed to correctly list all of the possibilities) then the parser would not complain about ambiguity as long as you never use the same tag twice in the same input. So it would be ok with both your original input and my altered input (as long as you accept the interpretation that my input is a single tagged object). But it would still report the following as ambiguous:
[aa]My text[/aa][aa]Another Text[/aa]
That's ambiguous because the grammar allows it to be either a single aa tagged string (whose text includes characters which look like close and open tags) or as two consecutive aa tagged strings.
To eliminate the ambiguity you would have to write the string pattern in a way which does not permit internal tags, in the same way that sstrchar doesn't allow internal single quotes. Except, of course, it is not nearly so simple to match a string which doesn't contain a pattern, than to match a string which doesn't contain a single character. It could be done using Nearley, but I really don't think that it's what you want.
Probably your best bet is to use native Javascript regular expressions to match tagged strings. This will prove simpler because Javascript regular expressions are much more powerful than mathematical regular expressions, even allowing the possibility of matching (certain) context-sensitive constructions. You could, for example, use Javascript regular expressions with the Moo lexer, which integrates well into Nearley. Or you could just use the regular expressions directly, since once you match the tagged text, there isn't much else you need to do.
To get you started, here's a simple Javascript regular expression which matches tagged strings with matching case-insensitive labels (the i flag at the end):
/\[([a-zA-Z]{2})\].*?\[\/\1\]/gmi
You can play with it online using Regex 101

What is the difference of operators " and ' in javascript [duplicate]

Consider the following two alternatives:
console.log("double");
console.log('single');
The former uses double quotes around the string, whereas the latter uses single quotes around the string.
I see more and more JavaScript libraries out there using single quotes when handling strings.
Are these two usages interchangeable? If not, is there an advantage in using one over the other?
The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.
Using the other type of quote as a literal:
alert('Say "Hello"');
alert("Say 'Hello'");
This can get complicated:
alert("It's \"game\" time.");
alert('It\'s "game" time.');
Another option, new in ECMAScript 6, is template literals which use the backtick character:
alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);
Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.
Note that JSON is formally specified to use double quotes, which may be worth considering depending on system requirements.
If you're dealing with JSON, it should be noted that strictly speaking, JSON strings must be double quoted. Sure, many libraries support single quotes as well, but I had great problems in one of my projects before realizing that single quoting a string is in fact not according to JSON standards.
There is no one better solution; however, I would like to argue that double quotes may be more desirable at times:
Newcomers will already be familiar with double quotes from their language. In English, we must use double quotes " to identify a passage of quoted text. If we were to use a single quote ', the reader may misinterpret it as a contraction. The other meaning of a passage of text surrounded by the ' indicates the 'colloquial' meaning. It makes sense to stay consistent with pre-existing languages, and this may likely ease the learning and interpretation of code.
Double quotes eliminate the need to escape apostrophes (as in contractions). Consider the string: "I'm going to the mall", vs. the otherwise escaped version: 'I\'m going to the mall'.
Double quotes mean a string in many other languages. When you learn a new language like Java or C, double quotes are always used. In Ruby, PHP and Perl, single-quoted strings imply no backslash escapes while double quotes support them.
JSON notation is written with double quotes.
Nonetheless, as others have stated, it is most important to remain consistent.
Section 7.8.4 of the specification describes literal string notation. The only difference is that DoubleStringCharacter is "SourceCharacter but not double-quote" and SingleStringCharacter is "SourceCharacter but not single-quote". So the only difference can be demonstrated thusly:
'A string that\'s single quoted'
"A string that's double quoted"
So it depends on how much quote escaping you want to do. Obviously the same applies to double quotes in double quoted strings.
I'd like to say the difference is purely stylistic, but I'm really having my doubts. Consider the following example:
/*
Add trim() functionality to JavaScript...
1. By extending the String prototype
2. By creating a 'stand-alone' function
This is just to demonstrate results are the same in both cases.
*/
// Extend the String prototype with a trim() method
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
// 'Stand-alone' trim() function
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
};
document.writeln(String.prototype.trim);
document.writeln(trim);
In Safari, Chrome, Opera, and Internet Explorer (tested in Internet Explorer 7 and Internet Explorer 8), this will return the following:
function () {
return this.replace(/^\s+|\s+$/g, '');
}
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
However, Firefox will yield a slightly different result:
function () {
return this.replace(/^\s+|\s+$/g, "");
}
function trim(str) {
return str.replace(/^\s+|\s+$/g, "");
}
The single quotes have been replaced by double quotes. (Also note how the indenting space was replaced by four spaces.) This gives the impression that at least one browser parses JavaScript internally as if everything was written using double quotes. One might think, it takes Firefox less time to parse JavaScript if everything is already written according to this 'standard'.
Which, by the way, makes me a very sad panda, since I think single quotes look much nicer in code. Plus, in other programming languages, they're usually faster to use than double quotes, so it would only make sense if the same applied to JavaScript.
Conclusion: I think we need to do more research on this.
This might explain Peter-Paul Koch's test results from back in 2003.
It seems that single quotes are sometimes faster in Explorer Windows (roughly 1/3 of my tests did show a faster response time), but if Mozilla shows a difference at all, it handles double quotes slightly faster. I found no difference at all in Opera.
2014: Modern versions of Firefox/Spidermonkey don’t do this anymore.
If you're doing inline JavaScript (arguably a "bad" thing, but avoiding that discussion) single quotes are your only option for string literals, I believe.
E.g., this works fine:
<a onclick="alert('hi');">hi</a>
But you can't wrap the "hi" in double quotes, via any escaping method I'm aware of. Even " which would have been my best guess (since you're escaping quotes in an attribute value of HTML) doesn't work for me in Firefox. " won't work either because at this point you're escaping for HTML, not JavaScript.
So, if the name of the game is consistency, and you're going to do some inline JavaScript in parts of your application, I think single quotes are the winner. Someone please correct me if I'm wrong though.
Technically there's no difference. It's only matter of style and convention.
Douglas Crockford1 recommends using double quotes.
I personally follow that.
Strictly speaking, there is no difference in meaning; so the choice comes down to convenience.
Here are several factors that could influence your choice:
House style: Some groups of developers already use one convention or the other.
Client-side requirements: Will you be using quotes within the strings? (See Ady's answer.)
Server-side language: VB.NET people might choose to use single quotes for JavaScript so that the scripts can be built server-side (VB.NET uses double-quotes for strings, so the JavaScript strings are easy to distinguished if they use single quotes).
Library code: If you're using a library that uses a particular style, you might consider using the same style yourself.
Personal preference: You might think one or other style looks better.
Just keep consistency in what you use. But don't let down your comfort level.
"This is my string."; // :-|
"I'm invincible."; // Comfortable :)
'You can\'t beat me.'; // Uncomfortable :(
'Oh! Yes. I can "beat" you.'; // Comfortable :)
"Do you really think, you can \"beat\" me?"; // Uncomfortable :(
"You're my guest. I can \"beat\" you."; // Sometimes, you've to :P
'You\'re my guest too. I can "beat" you too.'; // Sometimes, you've to :P
ECMAScript 6 update
Using template literal syntax.
`Be "my" guest. You're in complete freedom.`; // Most comfort :D
I hope I am not adding something obvious, but I have been struggling with Django, Ajax, and JSON on this.
Assuming that in your HTML code you do use double quotes, as normally should be, I highly suggest to use single quotes for the rest in JavaScript.
So I agree with ady, but with some care.
My bottom line is:
In JavaScript it probably doesn't matter, but as soon as you embed it inside HTML or the like you start to get troubles. You should know what is actually escaping, reading, passing your string.
My simple case was:
tbox.innerHTML = tbox.innerHTML + '<div class="thisbox_des" style="width:210px;" onmouseout="clear()"><a href="/this/thislist/'
+ myThis[i].pk +'"><img src="/site_media/'
+ myThis[i].fields.thumbnail +'" height="80" width="80" style="float:left;" onmouseover="showThis('
+ myThis[i].fields.left +','
+ myThis[i].fields.right +',\''
+ myThis[i].fields.title +'\')"></a><p style="float:left;width:130px;height:80px;"><b>'
+ myThis[i].fields.title +'</b> '
+ myThis[i].fields.description +'</p></div>'
You can spot the ' in the third field of showThis.
The double quote didn't work!
It is clear why, but it is also clear why we should stick to single quotes... I guess...
This case is a very simple HTML embedding, and the error was generated by a simple copy/paste from a 'double quoted' JavaScript code.
So to answer the question:
Try to use single quotes while within HTML. It might save a couple of debug issues...
It's mostly a matter of style and preference. There are some rather interesting and useful technical explorations in the other answers, so perhaps the only thing I might add is to offer a little worldly advice.
If you're coding in a company or team, then it's probably a good idea to follow the "house style".
If you're alone hacking a few side projects, then look at a few prominent leaders in the community. For example, let's say you getting into Node.js. Take a look at core modules, for example, Underscore.js or express and see what convention they use, and consider following that.
If both conventions are equally used, then defer to your personal preference.
If you don't have any personal preference, then flip a coin.
If you don't have a coin, then beer is on me ;)
I am not sure if this is relevant in today's world, but double quotes used to be used for content that needed to have control characters processed and single quotes for strings that didn't.
The compiler will run string manipulation on a double quoted string while leaving a single quoted string literally untouched. This used to lead to 'good' developers choosing to use single quotes for strings that didn't contain control characters like \n or \0 (not processed within single quotes) and double quotes when they needed the string parsed (at a slight cost in CPU cycles for processing the string).
If you are using JSHint, it will raise an error if you use a double quoted string.
I used it through the Yeoman scafflholding of AngularJS, but maybe there is somehow a manner to configure this.
By the way, when you handle HTML into JavaScript, it's easier to use single quote:
var foo = '<div class="cool-stuff">Cool content</div>';
And at least JSON is using double quotes to represent strings.
There isn't any trivial way to answer to your question.
There isn't any difference between single and double quotes in JavaScript.
The specification is important:
Maybe there are performance differences, but they are absolutely minimum and can change any day according to browsers' implementation. Further discussion is futile unless your JavaScript application is hundreds of thousands lines long.
It's like a benchmark if
a=b;
is faster than
a = b;
(extra spaces)
today, in a particular browser and platform, etc.
Examining the pros and cons
In favor of single quotes
Less visual clutter.
Generating HTML: HTML attributes are usually delimited by double quotes.
elem.innerHTML = 'Hello';
However, single quotes are just as legal in HTML.
elem.innerHTML = "<a href='" + url + "'>Hello</a>";
Furthermore, inline HTML is normally an anti-pattern. Prefer templates.
Generating JSON: Only double quotes are allowed in JSON.
myJson = '{ "hello world": true }';
Again, you shouldn’t have to construct JSON this way. JSON.stringify() is often enough. If not, use templates.
In favor of double quotes
Doubles are easier to spot if you don't have color coding. Like in a console log or some kind of view-source setup.
Similarity to other languages: In shell programming (Bash etc.), single-quoted string literals exist, but escapes are not interpreted inside them. C and Java use double quotes for strings and single quotes for characters.
If you want code to be valid JSON, you need to use double quotes.
In favor of both
There is no difference between the two in JavaScript. Therefore, you can use whatever is convenient at the moment. For example, the following string literals all produce the same string:
"He said: \"Let's go!\""
'He said: "Let\'s go!"'
"He said: \"Let\'s go!\""
'He said: \"Let\'s go!\"'
Single quotes for internal strings and double for external. That allows you to distinguish internal constants from strings that are to be displayed to the user (or written to disk etc.). Obviously, you should avoid putting the latter in your code, but that can’t always be done.
Talking about performance, quotes will never be your bottleneck. However, the performance is the same in both cases.
Talking about coding speed, if you use ' for delimiting a string, you will need to escape " quotes. You are more likely to need to use " inside the string. Example:
// JSON Objects:
var jsonObject = '{"foo":"bar"}';
// HTML attributes:
document.getElementById("foobar").innerHTML = '<input type="text">';
Then, I prefer to use ' for delimiting the string, so I have to escape fewer characters.
There are people that claim to see performance differences: old mailing list thread. But I couldn't find any of them to be confirmed.
The main thing is to look at what kind of quotes (double or single) you are using inside your string. It helps to keep the number of escapes low. For instance, when you are working with HTML content inside your strings, it is easier to use single quotes so that you don't have to escape all double quotes around the attributes.
When using CoffeeScript I use double quotes. I agree that you should pick either one and stick to it. CoffeeScript gives you interpolation when using the double quotes.
"This is my #{name}"
ECMAScript 6 is using back ticks (`) for template strings. Which probably has a good reason, but when coding, it can be cumbersome to change the string literals character from quotes or double quotes to backticks in order to get the interpolation feature. CoffeeScript might not be perfect, but using the same string literals character everywhere (double quotes) and always be able to interpolate is a nice feature.
`This is my ${name}`
I would use double quotes when single quotes cannot be used and vice versa:
"'" + singleQuotedValue + "'"
'"' + doubleQuotedValue + '"'
Instead of:
'\'' + singleQuotedValue + '\''
"\"" + doubleQuotedValue + "\""
There is strictly no difference, so it is mostly a matter of taste and of what is in the string (or if the JavaScript code itself is in a string), to keep number of escapes low.
The speed difference legend might come from PHP world, where the two quotes have different behavior.
The difference is purely stylistic. I used to be a double-quote Nazi. Now I use single quotes in nearly all cases. There's no practical difference beyond how your editor highlights the syntax.
You can use single quotes or double quotes.
This enables you for example to easily nest JavaScript content inside HTML attributes, without the need to escape the quotes.
The same is when you create JavaScript with PHP.
The general idea is: if it is possible use such quotes that you won't need to escape.
Less escaping = better code.
In addition, it seems the specification (currently mentioned at MDN) doesn't state any difference between single and double quotes except closing and some unescaped few characters. However, template literal (` - the backtick character) assumes additional parsing/processing.
A string literal is 0 or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for the closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), and U+000A (LINE FEED). Any code points may appear in the form of an escape sequence. String literals evaluate to ECMAScript String values...
Source: https://tc39.es/ecma262/#sec-literals-string-literals

JavaScript RegExp: R naming conventions

We're all familiar with naming conventions in R (if not: Venables & Smith - Introduction to R, Chapter 1.8). Regular expressions, on the other hand, remain terra incognita and the most hated part in my programming life so far ... Recently, I've officially started JavaScript recapitulation, and I'm trying to create precise RegExp to check correct R object name.
Brief intro:
Object names must start with . or lower/uppercase letter, and if they start with . cannot continue with numeric... afterward, alphanumeric symbols are allowed with . and underscore _.
Long story short, here's my JS code:
var txt = "._.";
var inc = /^\.(?!\d)|^[a-z\.]/i;
document.write(inc.test(txt));
This approach manages the first part (. and/or lower/upper case and numeric after .), but I cannot pass something like & [\w\.]. I can write a function that will take care of this one, but is it at all possible to manage this with a single RegExp?
I'm not familiar with R or its naming conventions, but I'll give it a shot:
If you're only trying to verify that the name begins correctly, all you need to do is remove the \. from the character class, leaving you with: /^\.(?!\d)|^[a-z]/i. Otherwise, the . may still be the first character with no restrictions on the remaining ones.
If you want to verify the that entire name is correct, something like this should work:
/^(?:\.(?!\d)|[a-z])[a-z0-9_\.]+$/i

Why are some object-literal properties quoted and others not? [duplicate]

This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 9 years ago.
I see this all the time: object literals declared such that some keys are surrounded with quotes and others are not. An example from jQuery 1.4.2:
jQuery.props = {
"for": "htmlFor",
"class": "className",
readonly: "readOnly",
maxlength: "maxLength",
cellspacing: "cellSpacing",
rowspan: "rowSpan",
colspan: "colSpan",
tabindex: "tabIndex",
usemap: "useMap",
frameborder: "frameBorder"
};
What is the significance of wrapping the first two property keys (for and class) with quotes, while leaving the others quote-less? Are there any differences at all?
I've been poking around the ECMAScript 5 specification; all I've been able to find is [Note 6 of Section 15.12.3, emphasis mine]:
NOTE 6 An object is rendered as an
opening left brace followed by zero or
more properties, separated with
commas, closed with a right brace. A
property is a quoted String
representing the key or property name,
a colon, and then the stringified
property value. An array is rendered
as an opening left bracket followed by
zero or more values, separated with
commas, closed with a right bracket.
However, this refers only to the stringification of JSON.
Those are Javascript reserved words, and (though not really necessary) the syntax of the language requires that they be quoted.
Strictly speaking, pure "JSON" notation requires that all of the "key" strings be quoted. Javascript itself however is OK with keys that are valid identifiers (but not reserved words) being unquoted.
There is a reason at this point (two plus years later) to quote object literal properties. If one wants to minify their code using the Closure Compiler they may need to make the properties accessible to other source files. In that case, they will want to avoid having symbols renamed by the compiler. By quoting the property name, the Closure Compiler will not minify (rename) them.
See: Removal of code you want to keep
(This applies to at least the ADVANCED_OPTIMIZATIONS setting.)
Javascript language keywords or reserved keywords are always surrounded by quotes in there.
for and class are language keywords. Your interpreter would throw a SyntaxError when those are unquoted.
See section 7.6.1.1 in the Spec you linked to.
Javascript has a lot of reserved words that are not actually used by the language which I think were reserved for possible future use. class is one of these even though Javascript does not actually use classes. Another is goto and there's absolutely no chance of that ever being used. The result, however, is that if you want to use these as a json key then it has to be quoted. Strictly speaking you should probably always quote your keys just to avoid the possibility of falling foul of the javascript unused reserved word trap (mind you - I never do).

Categories

Resources