What quotes can I use while coding? [duplicate] - javascript

Working on node.js (server side), I wonder if I should use all back-ticks (`) instead of the regular quotes (" or ') all the time since it will make the code consistent. Is there any specific reason for keeping different type of quotes for different things. Will it affect performance if all non-substitution quotes are converted to back-ticks?

the back-tick allows you to use string templating for example:
var value = 4;
var str = `text with a ${value}`
// str will be : 'text with a 4'
for " vs ' I say look at this post: https://stackoverflow.com/a/9959952/6739517
As for performance, it seems like it would be the same if you are just using back-ticks for plain strings. However when building strings it looks like concatenation is still the way to go. Take a look here:
2018 update: It seems that ES6 string templating can be faster than concatenation in some cases. Take a look at the following post for some hard numbers:
Are ES6 template literals faster than string concatenation?
2020 update: Generally speaking you should not be worried about performance when considering which type of quotation to use. There might be tiny differences but as many have pointed out these are such tiny improvements you are likely better off optimizing your code rather than considering which character to use. That said, this doesn't really answer the question of consistency. For me, I generally follow Airbnb's style guide. That is strings are always declared with single quotes (') unless you need to build a string then you should avoid concatenation and only use string templating with backticks (`). Finally, double quotes are reserved for JSON and HTML.

The performance difference between creating strings using backticks or single quotes would be so absurdly small that I don't think you should consider it as a reason to use one or the other. Here is some basic evidence of that.
However - I would argue against using template string for strings that are not templates simply because it's clear when you use single quotes that no templating is going to occur. If I saw a string with backticks - I would immediately start hunting to see what was going to be substituted, or why they were used. By contrast, single quotes are very clear.
I don't think it will affect performance - but I don't think you should do it "just to be consistent" either. It's not consistent because it's a completely different construct - the same as a while or for loop. They are different tools for different jobs.

Back ticks(``) are called template literals. They are part of ES6.
Difference is:
var name = "world";
var greetES5 = 'Hello '+name;//using single quote
var greetES6 = `Hello ${name}`;//using ticks
You can refer MDN here for more info.

Related

Back-tick vs single quote in js

Working on node.js (server side), I wonder if I should use all back-ticks (`) instead of the regular quotes (" or ') all the time since it will make the code consistent. Is there any specific reason for keeping different type of quotes for different things. Will it affect performance if all non-substitution quotes are converted to back-ticks?
the back-tick allows you to use string templating for example:
var value = 4;
var str = `text with a ${value}`
// str will be : 'text with a 4'
for " vs ' I say look at this post: https://stackoverflow.com/a/9959952/6739517
As for performance, it seems like it would be the same if you are just using back-ticks for plain strings. However when building strings it looks like concatenation is still the way to go. Take a look here:
2018 update: It seems that ES6 string templating can be faster than concatenation in some cases. Take a look at the following post for some hard numbers:
Are ES6 template literals faster than string concatenation?
2020 update: Generally speaking you should not be worried about performance when considering which type of quotation to use. There might be tiny differences but as many have pointed out these are such tiny improvements you are likely better off optimizing your code rather than considering which character to use. That said, this doesn't really answer the question of consistency. For me, I generally follow Airbnb's style guide. That is strings are always declared with single quotes (') unless you need to build a string then you should avoid concatenation and only use string templating with backticks (`). Finally, double quotes are reserved for JSON and HTML.
The performance difference between creating strings using backticks or single quotes would be so absurdly small that I don't think you should consider it as a reason to use one or the other. Here is some basic evidence of that.
However - I would argue against using template string for strings that are not templates simply because it's clear when you use single quotes that no templating is going to occur. If I saw a string with backticks - I would immediately start hunting to see what was going to be substituted, or why they were used. By contrast, single quotes are very clear.
I don't think it will affect performance - but I don't think you should do it "just to be consistent" either. It's not consistent because it's a completely different construct - the same as a while or for loop. They are different tools for different jobs.
Back ticks(``) are called template literals. They are part of ES6.
Difference is:
var name = "world";
var greetES5 = 'Hello '+name;//using single quote
var greetES6 = `Hello ${name}`;//using ticks
You can refer MDN here for more info.

Are there drawbacks to using backticks for all string operations in Typescript? [duplicate]

Is there a reason (performance or other) not to use backtick template literal syntax for all strings in a javascript source file? If so, what?
Should I prefer this:
var str1 = 'this is a string';
over this?
var str2 = `this is another string`;
Code-wise, there is no specific disadvantage. JS engines are smart enough to not have performance differences between a string literal and a template literal without variables.
In fact, I might even argue that it is good to always use template literals:
You can already use single quotes or double quotes to make strings. Choosing which one is largely arbitrary, and you just stick with one. However, it is encouraged to use the other quote if your string contains your chosen string marker, i.e. if you chose ', you would still do "don't argue" instead of 'don\'t argue'. However, backticks are very rare in normal language and strings, so you would actually more rarely have to either use another string literal syntax or use escape codes, which is good.
For example, you'd be forced to use escape sequences to have the string she said: "Don't do this!" with either double or single quotes, but you wouldn't have to when using backticks.
You don't have to convert if you want to use a variable in the string in the future.
However, those are very weak advantages. But still more than none, so I would mainly use template literals.
A real but in my opinion ignorable objection is the one of having to support environments where string literals are not supported. If you have those, you would know and wouldn't be asking this question.
The most significant reason not to use them is that ES6 is not supported in all environments.
Of course that might not affect you at all, but still: YAGNI. Don't use template literals unless you need interpolation, multiline literals, or unescaped quotes and apostrophes. Much of the arguments from When to use double or single quotes in JavaScript? carry over as well. As always, keep your code base consistent and use only one string literal style where you don't need a special one.
Always use template literals. In this case YAGNI is not correct. You absolutely will need it. At some point, you will have add a variable or new line to your string, at which point you will either need to change single quotes to backticks, or use the dreaded '+'.
Be careful when the values are for external use. We work with Tealium for marketing analysis, and it currently does not support ES6 template literals. Event data containing template literals aka string templates will cause the Tealium script to error.
I'm fairly convinced by other answers that there's no serious downside to using them exclusively, but one additional counterpoint is that template strings are also used in advanced "tagged template" syntax, and as illustrated in this Reddit comment, if you try to rely exclusively on JavaScript's automatic semicolon insertion or just forget to include a semicolon, you can run into parsing issues with statements that begin with a template string.
// OK (single (or double) quotes)
logger = console.log
'123'.split('').forEach(logger)
// OK (semicolon)
logger = console.log;
`123`.split('').forEach(logger)
// Not OK
logger = console.log
`123`.split('').forEach(logger) // Error

Comma Operator to Semicolons

I have a chunk of javascript that has many comma operators, for example
"i".toString(), "e".toString(), "a".toString();
Is there a way with JavaScript to convert these to semicolons?
"i".toString(); "e".toString(); "a".toString();
This might seem like a cop-out answer... but I'd suggest against trying it. Doing any kind of string manipulation to change it would be virtually impossible. In addition to function definition argument lists, you'd also need to skip text in string literals or regex literals or function calls or array literals or object literals or variable declarations.... maybe even more. Regex can't handle it, turning on and off as you see keywords can't handle it.
If you want to actually convert these, you really have to actually parse the code and figure out which ones are the comma operator. Moreover, there might be some cases where the comma's presence is relevant:
var a = 10, 20;
is not the same as
var a = 10; 20;
for example.
So I really don't think you should try it. But if you do want to, I'd start by searching for a javascript parser (or writing one, it isn't super hard, but it'd probably take the better part of a day and might still be buggy). I'm pretty sure the more advanced minifiers like Google's include a parser, maybe their source will help.
Then, you parse it to find the actual comma expressions. If the return value is used, leave it alone. If not, go ahead and replace them with expression statements, then regenerate the source code string. You could go ahead and format it based on scope indentation at this time too. It might end up looking pretty good. It'll just be a fair chunk of work.
Here's a parser library written in JS: http://esprima.org/ (thanks to #torazaburo for this comment)

Is there any practical reason to use quoted strings for JSON keys?

According to Crockford's json.org, a JSON object is made up of members, which is made up of pairs.
Every pair is made of a string and a value, with a string being defined as:
A string is a sequence of zero or more
Unicode characters, wrapped in double
quotes, using backslash escapes. A
character is represented as a single
character string. A string is very
much like a C or Java string.
But in practice most programmers don't even know that a JSON key should be surrounded by double quotes, because most browsers don't require the use of double quotes.
Does it make any sense to bother surrounding your JSON in double quotes?
Valid Example:
{
"keyName" : 34
}
As opposed to the invalid:
{
keyName : 34
}
The real reason about why JSON keys should be in quotes, relies in the semantics of Identifiers of ECMAScript 3.
Reserved words cannot be used as property names in Object Literals without quotes, for example:
({function: 0}) // SyntaxError
({if: 0}) // SyntaxError
({true: 0}) // SyntaxError
// etc...
While if you use quotes the property names are valid:
({"function": 0}) // Ok
({"if": 0}) // Ok
({"true": 0}) // Ok
The own Crockford explains it in this talk, they wanted to keep the JSON standard simple, and they wouldn't like to have all those semantic restrictions on it:
....
That was when we discovered the
unquoted name problem. It turns out
ECMA Script 3 has a whack reserved
word policy. Reserved words must be
quoted in the key position, which is
really a nuisance. When I got around
to formulizing this into a standard, I
didn't want to have to put all of the
reserved words in the standard,
because it would look really stupid.
At the time, I was trying to convince
people: yeah, you can write
applications in JavaScript, it's
actually going to work and it's a good
language. I didn't want to say, then,
at the same time: and look at this
really stupid thing they did! So I
decided, instead, let's just quote the
keys.
That way, we don't have to tell
anybody about how whack it is.
That's why, to this day, keys are quoted in
JSON.
...
The ECMAScript 5th Edition Standard fixes this, now in an ES5 implementation, even reserved words can be used without quotes, in both, Object literals and member access (obj.function Ok in ES5).
Just for the record, this standard is being implemented these days by software vendors, you can see what browsers include this feature on this compatibility table (see Reserved words as property names)
Yes, it's invalid JSON and will be rejected otherwise in many cases, for example jQuery 1.4+ has a check that makes unquoted JSON silently fail. Why not be compliant?
Let's take another example:
{ myKey: "value" }
{ my-Key: "value" }
{ my-Key[]: "value" }
...all of these would be valid with quotes, why not be consistent and use them in all cases, eliminating the possibility of a problem?
One more common example in the web developer world: There are thousands of examples of invalid HTML that renders in most browsers...does that make it any less painful to debug or maintain? Not at all, quite the opposite.
Also #Matthew makes the best point of all in comments below, this already fails, unquoted keys will throw a syntax error with JSON.parse() in all major browsers (and any others that implement it correctly), you can test it here.
If I understand the standard correctly, what JSON calls "objects" are actually much closer to maps ("dictionaries") than to actual objects in the usual sense. The current standard easily accommodates an extension allowing keys of any type, making
{
"1" : 31.0,
1 : 17,
1n : "valueForBigInt1"
}
a valid "object/map" of 3 different elements.
If not for this reason, I believe the designers would have made quotes around keys optional for all cases (maybe except keywords).
YAML, which is in fact a superset of JSON, supports what you want to do. ALthough its a superset, it lets you keep it as simple as you want.
YAML is a breath of fresh air and it may be worth your time to have a look at it. Best place to start is here: http://en.wikipedia.org/wiki/YAML
There are libs for every language under the sun, including JS, eg https://github.com/nodeca/js-yaml

Best way to generate javascript code in ruby (RoR)

I have seen some rails plugins which generate javascript code dynamically using ruby.
1.
%Q ( mixed block of javascript and ruby )
2.
<<-CODE
some mixed ruby and javascript code
CODE
Being a java developer I don't understand
what those strange looking syntax mean ?
Is one way better than the other ?
can anyone point me to proper documentation about such things ?
The first syntax is Ruby's string literal syntax. Specifically, the %Q (capital Q as opposed to lower-case) means that the string will be interpolated. eg:
%Q[Here's a string with #{a_variable} interpolated!]
Note that you can use any arbitrary characters as the open and close delimiters.
The second syntax is Ruby's heredoc syntax. The dash after the opening << indicates that Ruby will strip whitespace from the beginning of input lines contained in the heredoc block.
Ruby on Rails ships with the Prototype JavaScript framework built-in already. It also ships with JS generator helper methods which generate the Prototype code dynamically based on Ruby code.
You needn't use these if you don't want to. In fact, I rarely use them or Prototype at all, as jQuery is my JS framework of choice. So one way is not "better" than the other (except in the general sense that heredoc is better than the string literal syntax for certain cases).
In Ruby %Q provides a double quote delimited string, so:
%Q(mixed block of javascript and ruby) #=> "mixed block of javascript and ruby"
<<-CODE is what Ruby calls a Here Document, or simply heredoc. This is a mechanism for creating free format strings whilst preserving special characters such as new lines and tabs.
A heredoc is created by preceding the text with << followed by the delimiter string you wish to use to mark the end of the text.
text = <<-DOC
To be, or not to be: that is the question
William Shakespeare
DOC
When this string is printed it appears exactly as it was entered, together with all the new lines and tabs:
To be, or not to be: that is the question
William Shakespeare
%Q is the equivalent to a "" string in Ruby. But if you use such %Q-syntax, you don't need to escape double quotes.
It's a HEREDOC declaration. You also don't need to escape quotes there.
Strings in Ruby.
Here you can find the details.
Ruby with javascript

Categories

Resources