Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Tell me please, what is the sacred power of the style below:
var javascript = new Language(
'Brendan Eich'
, new Date(1995, 0, 1)
, ['C', 'Java', 'Scheme']
);
Why do lots of programmers use that style? What benefits does it have? For example,
var javascript = new Language(
'Brendan Eich',
new Date(1995, 0, 1),
['C', 'Java', 'Scheme']
);
I like much more than previous. Thanks.
Lots of great answers already. Allow me to give you my own one, to make things as clear as possible.
I personally call this way of writing code 'Haskel style', since it's a common style to use in Haskell. Let me give you a Haskell example first:
data Settings = -- The user settings
{ has_sound :: Bool -- Determines if the user has sound
, has_power :: Bool -- Determines if the user has electricity
, has_graphics :: Bool -- Determines if the user has graphics
, user_name :: String -- The name of the user
, user_password :: String -- The hashed password of the user
, user_email :: Email -- The email address of the user
, stylesheet :: Style -- The stylesheet to use
}
And a Javascript snippet from one of my projects:
var events // Holds the events to generate a event handler for.
, var2 // Quick description for var2.
, var3 // Quick description for var3.
, ... // ...
;
events = // Event handlers will be generated for the following events:
[ "onmousedown" // Works outside of the window element
, "onmouseup" // Works outside of the window element
, "onmousemove" // Works outside of the window element
, "onmousewheel" // This will handle DOMMouseScroll aswell
];
Benefits of 'Haskell style'
Easy to read
'Haskell style' takes advantage of the column style layout. This column style makes your code more readable. In fact, it makes your code so much more readable that you use it all the time. Imagine writing code without tabs or leading spaces!
By taking advantage of column style layout, variable names, types, etc. are easier to read aswell. By grouping up variables by prefix, our future reader will easily find what he is looking for, without using a advanced search query.
Easy to document
Column style layout has more advantages. By grouping up our code we can add a column reserved for comments. Now you can read your code without even needing color highlighting, and adding information to your comment is as easy as finding the right column and modifying it.
Besides, this column-like style of documenting your code is pretty much what you get after using a documentation generator like Doxygen, removing the necessity for this kind of tool.
Easy to notice mistakes
Noticing a missing comma is a piece of cake using this style of coding. Simply look for a line that doesn't start with it! On the other side of the spectrum, we have the comma's at the end of the line. We missed one? Nope, because it is the last element, or because the expression continues on the next line.
And finding the first element in a list is as easy as could be. When dealing with long lines, the first element is easily overlooked, but by placing the first element on it's own line and puting a [ or { instead of a , right in front of it, it's easy to spot.
Easily scalable
You might say "But this layout style will get imposible to handle once the expression gets big!", which is quite true, but is this any different for the rest of your code?
I think that by using column style you will at least keep your code readable, which in the long run is worth more than the struggle you might have to fit it into a column layout.
All in one example!
var scalable = // This is a example variable
[
[ new MyObject // This is how I would style Object Allocation
( "11"
, "This is the first element"
, function // This is a very secret function...
( secret // ..with secret..
, variable // ..variable..
, names // ..names!
)
{
// <-- Use spaces, not tabs :)
}
)
, "12"
]
,
[ { id: 21 // Where's 20?
, name: "This is the third element" // It sure is
, func: function() { /* My body feels empty :c */ }
}
, "22" // Notice how 21 is a integer, not a string. Sneaky!
]
];
TL; DR
This style of placing comma's, 'Haskell style', has a couple of advantages:
Easy to read
Easy to document
Easy to notice mistakes
Easily scalable
If you have an extra comma in the end of the last line it will work in some browsers but not in all browsers. Making the error harder to detect than a extra comma at the beginning (which fails on all browsers). And most developers prefer to see the error right away (so they can fix it), instead of risking a production issue for inadvertently not supporting some browsers. Especially if the solution is as easy as removing a comma.
Plus, having the comma at the beginning of the line, make it simpler to add a line at the end and you will have to touch only that line (you will not need to add the comma in the line before). Which is important if you are using version control (e.g. diff, annotate, bisect). Someone can argue that adding a line at beginning of the array or object will need the same extra work of touching 2 lines (if you use commas at the beginning), but in my experience, inserting a line at the beginning is much less likely that inserting a line at the end.
This is because the comma belong to the new line next statement and not the previous one. (As #Dave Newton states it in his comment below: the pseudo-BNF would be foo [, foo]*-ish)
For example:
If you have this:
a,
b,
c
If you need to remove the c then you need to delete two things: de c and the comma on the previous line. If you do this:
a
,b
,c
now you only need to delete the ,c line. It makes more sense this way, because the comma behind the b in the first example only is needed because of the c. It does look worse this way though. It's a trade off between maintainability of your code and the way it looks.
I think it's done so that it's easier to spot a missed comma.
var something = 0,
foo = "a string",
somethingElse = []
bar;
var something = 0
, foo = "a string"
somethingElse = []
, bar;
It is easier to just look at your code to verify you have a comma where needed. If you had to scan the end of each line of code the missing commas wouldn't just jump out like they do when they are lined up on the left hand side.
This offers a little bit of protection in languages which don't accept trailing commas from accidentally introducing syntax errors with trailing commas
In SQL, trailing commas will cause syntax errors. In JavaScript, it will be accepted most places, but will fail with a cryptic error in some Internet Explorer versions, for example.
JS works in most browsers, but fails in some
var thing = {
a: 1,
b: 2,
// trailing comma
c: 3,
};
Syntax error in SQL
SELECT
col1,
col2,
-- Syntax error in SQL
col3,
FROM table
It's one way to make sure you don't forget the comma when adding a new item to a collection, and don't accidentally leave on a trailing comma in collections.
By putting it on the new line it's visually obvious.
I don't care for it, but I understand why people would.
You might be looking at generated code, for instance, when writing a loop to generate an SQL select statement sometimes I will write it like:
sql = "SELECT";
sql += " table.id"; // or some field that will always be in the query
for (var i = 0; i < 10; i++;) {
sql += ", table.field" + i;
}
sql += "FROM table" // etc
Instead of adding the comma at the end and then having a condition to omit it on the last iteration of the loop or doing:
sql = "SELECT";
for (var i = 0; i < 10; i++;) {
sql += " table.field" + i + ",";
}
sql += " table.id";
sql += "FROM table" // etc
Which is functionally equivalent, but then the ID doesn't appear where I usually want it.
Maybe because removing or adding line and its commas is simpler with second example
Related
This question already has answers here:
Template literal inside of the RegEx
(2 answers)
Closed 1 year ago.
hi I am coding an online shop ,
currently working on add to cart functionality,
like to store product ids and their quantity in a cookie like this id1:qt1,id2:qt2...
like to check if a product is already is in cart , looks like my regular expr doesn't work
const reg = new RegExp(`${product_id}:\d+`);
if (!reg.test(cart_cookie)){
const values = cart_cookie.split(',');
values.push(`${product_id}:1`);
setCookie('cart', values.join(','), 7);
}
else {
console.log('already in cart.')
}
Yep, your regex is off :)
It stumped me for a second, but its clear when you check what your "regex" string actually evaluates to: /product_id:d+/. This is because the string you're passing in sees the \d as a literal d. To fix this, just throw another \ in there so the original \ is whats being escaped. Before, you were matching things like "apple:ddddddd".
Once you do that, your code DOES seem to work, but maybe just not like you expect it to?
I've put your code into a function, since you would -- presumably -- be calling this every time you want to add an item to the cart, and added a console.log statement to show the end value of the "cookie."
// Just as a stand in for actual values
let cart_cookie = 'apples:2,oranges:3,bananas:1';
function addCartItem(product_id) {
const reg = new RegExp(`${product_id}:\\d+`);
console.log(reg)
if (!reg.test(cart_cookie)){
const values = cart_cookie.split(',');
values.push(`${product_id}:1`);
console.log('cart_cookie is now ', values.join(','));
setCookie('cart', values.join(','), 7);
}
else {
console.log('already in cart.')
}
}
addCartItem('apples');
// already in cart.
addCartItem('kiwis');
// cart_cookie is now apples:2,oranges:3,bananas:1,kiwis:1
Its fixed! 🥳 But...
I'm not quite sure what your product ids look like, but if they contain special characters (e.g. periods, question marks, etc.) it'll cause some issues with how your regex performs. I doubt you have things like question marks in it, but something like this illustrates my point:
let cart_cookie = '123.15:3,2.5.141:1';
/* ... */
addCartItem('1.3.15');
// already in cart.
I know, its a rather unlikely scenario -- and it might not even apply to you if you know your product ids won't contain anything tricky -- but if you're goal is to build an online shop, you'll probably want to cover all your bases.
Even fixing that, this still has a potential issue, as this will only let you add a quantity of 1 to an item thats not already in the cart, with no ability to increment it after that. Not sure if thats what you're going for.
This veers off of the main question you posed, but a potentially better solution might be using the browser's localstorage (or sessionstorage) to keep track of the cart. This would allow you to use more familiar data structures to store this info, rather than a string that you have to pray you're parsing correctly.
More info on that here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
you can use just array method instead you don't need for regex for that,
for example..
const values = cart_cookie.split(',');
values.foreach(value => {
if(value != product_id){
values.push(`${product_id}:1`);
setCookie('cart', values.join(','), 7);
}
});
I am implementing jQuery chaining - using Mika Tuupola's Chained plugin - in my rails project (using nested form_for partials) and need to dynamically change the chaining attribute:
The code that works without substitution:
$(".employee_title_2").remoteChained({
parents : ".employee_title_1",
url : "titles/employee_title_2",
loading : "Loading...",
clear : true
});
The attributes being substituted are .employee_title_1 and .employee_title_2:
var t2 = new Date().getTime();
var A1 = ".employee_title_1A_" + t2;
var B2 = ".employee_title_2B_" + t2;
In ruby speak, I'm namespacing the variables by adding datetime.
Here's the code I'm using for on-the-fly substitution:
$(`"${B2}"`).remoteChained({
parents : `"${A1}"`,
url : "titles/employee_title_2",
loading : "Loading...",
clear : true
});
Which throws this error:
Uncaught Error: Syntax error, unrecognized expression:
".employee_title_2B_1462463848339"
The issue appears to be the leading '.' How do I escape it, assuming that's the issue? Researching the error message Syntax error, unrecognized expression lead to SO question #14347611 - which suggests "a string is only considered to be HTML if it starts with a less-than ('<) character" Unfortunately, I don't understand how to implement the solution. My javascript skills are weak!
Incidentally, while new Date().getTime(); isn't in date format, it works for my purpose, i.e., it increments as new nested form fields are added to the page
Thanks in advance for your assistance.
$(`"${B2b}"`).remoteChained({
// ^ ^
// These quotes should not be here
As it is evaluated to a string containing something like:
".my_class"
and to tie it together:
$('".my_class"')...
Same goes for the other place you use backtick notation. In your case you could simply use:
$(B2).remoteChained({
parents : A1,
url : "titles/employee_title_2",
loading : "Loading...",
clear : true
});
The back tick (``) syntax is new for Javascript, and provides a templating feature, similar to the way that Ruby provides interpolated strings. For instance, this Javascript code:
var who = "men";
var what = "country";
var famous_quote = `Now is the time for all good ${who} to come to the aid of their #{what}`;
is interpolated in exactly the same way as this Ruby code:
who = "men"
what = "country"
famous_quote = "Now is the time for all good #{who} to come to the aid of their #{what}"
In both cases, the quote ends up reading, "Now is the time for all good men to come to the aid of their country". Similar feature, slightly different syntax.
Moving on to jQuery selectors, you have some flexibility in how you specify them. For instance, this code:
$(".my_class").show();
is functionally equivalent to this code:
var my_class_name = ".my_class";
$(my_class_name).show();
This is a great thing, because that means that you can store the name of jQuery selectors in variables and use them instead of requiring string literals. You can also build them from components, as you will find in this example:
var mine_or_yours = (user_selection == "me") ? "my" : "your";
var my_class_name = "." + mine_or_yours + "_class";
$(my_class_name).show();
This is essentially the behavior that you're trying to get working. Using the two features together (interpolation and dynamic jQuery selectors), you have this:
$(`"${B2}"`).remote_chained(...);
which produces this code through string interpolation:
$("\".employee_title_2B_1462463848339\"").remote_chained(...);
which is not correct. and is actually the cause of the error message from jQuery, because of the embedded double quotes in the value of the string. jQuery is specifically complaining about the extra double quotes surrounding the value that you're passing to the selector.
What you actually want is the equivalent of this:
$(".employee_title_2B_1462463848339").remote_chained(...);
which could either be written this way:
$(`${B2}`).remote_chained(...);
or, much more simply and portably, like so:
$(B2).remote_chained(...);
Try this little sample code to prove the equivalence it to yourself:
if (`${B2}` == B2) {
alert("The world continues to spin on its axis...");
} else if (`"${B2}"` == B2) {
alert("Lucy, you've got some 'splain' to do!");
} else {
alert("Well, back to the drawing board...");
}
So, we've established the equivalency of interpolation to the original strings. We've also established the equivalency of literal jQuery selectors to dynamic selectors. Now, it's time to put the techniques together in the original code context.
Try this instead of the interpolation version:
$(B2).remoteChained({
parents : A1,
url : "titles/employee_title_2",
loading : "Loading...",
clear : true
});
We already know that $(B2) is a perfectly acceptable dynamic jQuery selector, so that works. The value passed to the parents key in the remoteChained hash simply requires a string, and A1 already fits the bill, so there's no need to introduce interpolation in that case, either.
Realistically, nothing about this issue is related to Chained; it just happens to be included in the statement that's failing. So, that means that you can easily isolate the failing code (building and using the jQuery selectors), which makes it far easier to debug.
Note that the Javascript syntax was codified just last year with ECMAScript version 6, so the support for it is still a mixed bag. Check your browser support to make sure that you can use it reliably.
I have no script abilitiy, but i'd like to edit an existing script which is currently restricting the script from running on any page other then the one that has a certain string in the URL.
Here is the snippet of the script which limits it from running
if(location.href.indexOf("MODULE=MESSAGE")>0||location.href.indexOf("/message")>0)
This only allows the script to run on these pages
mysite/2014/home/11609?MODULE=MESSAGE1
and the pages range from Message1 to Message20
mysite/2014/home/11609?MODULE=MESSAGE20
I would like to also allow the script to be loaded and ran on these pages
mysite/2014/options?L=11609&O=247&SEQNO=1&PRINTER=1
where the SEQNO=1 ranges from 1 to SEQNO=20, just like the MESSAGE1-MESSAGE20 do
Can someone show me how i can edit that small snippet of script to allow the SEQNO string found in the url to work also.
Thanks
If you can't just remove the condition altogether (there's not enough context to know if that's an option), you can just add another or condition (||) like so:
if(location.href.indexOf("MODULE=MESSAGE")>0
||location.href.indexOf("/message")>0
||location.href.indexOf("SEQNO=")>0)
Note that the second clause there isn't actually being used in any of your examples, so could potentially be removed. Also note that this isn't actually checking for a number so it isn't restricted to Message1 to Message20 as you suggest. It would match Message21 or even MessageFoo. That may or may not be a problem for you. You can make the conditions as restrictive or as lose as makes sense.
If you just want to check for the existence of "SEQNO", simply duplicate what is being done for "MODULE_MESSAGE".
if(location.href.indexOf("MODULE=MESSAGE")>0 ||
location.href.indexOf("SEQNO=")>0 ||
location.href.indexOf("/message")>0)
If you want to also ensure that "MESSAGE" ends in 1-20, and "SEQNO=" ends in 1-20, you can use a regex.
// create the end part of the regex, which checks for numbers 1-20
var regexEnd = "([1-9]|1[0-9]|20)[^0-9]*$";
// create the individual regexes
var messageRegex = new RegExp("MODULE=MESSAGE" + regexEnd);
var seqnoRegex = new RegExp("SEQNO=" + regexEnd);
// now comes your if statement, using the regex test() function, which returns true if it matches
if(messageRegex.test(location.href) ||
seqnoRegex.test(location.href) ||
location.href.indexOf("/message")>0)
I have a bbcode -> html converter that responds to the change event in a textarea. Currently, this is done using a series of regular expressions, and there are a number of pathological cases. I've always wanted to sharpen the pencil on this grammar, but didn't want to get into yak shaving. But... recently I became aware of pegjs, which seems a pretty complete implementation of PEG parser generation. I have most of the grammar specified, but am now left wondering whether this is an appropriate use of a full-blown parser.
My specific questions are:
As my application relies on translating what I can to HTML and leaving the rest as raw text, does implementing bbcode using a parser that can fail on a syntax error make sense? For example: [url=/foo/bar]click me![/url] would certainly be expected to succeed once the closing bracket on the close tag is entered. But what would the user see in the meantime? With regex, I can just ignore non-matching stuff and treat it as normal text for preview purposes. With a formal grammar, I don't know whether this is possible because I am relying on creating the HTML from a parse tree and what fails a parse is ... what?
I am unclear where the transformations should be done. In a formal lex/yacc-based parser, I would have header files and symbols that denoted the node type. In pegjs, I get nested arrays with the node text. I can emit the translated code as an action of the pegjs generated parser, but it seems like a code smell to combine a parser and an emitter. However, if I call PEG.parse.parse(), I get back something like this:
[
[
"[",
"img",
"",
[
"/",
"f",
"o",
"o",
"/",
"b",
"a",
"r"
],
"",
"]"
],
[
"[/",
"img",
"]"
]
]
given a grammar like:
document
= (open_tag / close_tag / new_line / text)*
open_tag
= ("[" tag_name "="? tag_data? tag_attributes? "]")
close_tag
= ("[/" tag_name "]")
text
= non_tag+
non_tag
= [\n\[\]]
new_line
= ("\r\n" / "\n")
I'm abbreviating the grammar, of course, but you get the idea. So, if you notice, there is no contextual information in the array of arrays that tells me what kind of a node I have and I'm left to do the string comparisons again even thought the parser has already done this. I expect it's possible to define callbacks and use actions to run them during a parse, but there is scant information available on the Web about how one might do that.
Am I barking up the wrong tree? Should I fall back to regex scanning and forget about parsing?
Thanks
First question (grammar for incomplete texts):
You can add
incomplete_tag = ("[" tag_name "="? tag_data? tag_attributes?)
// the closing bracket is omitted ---^
after open_tag and change document to include an incomplete tag at the end. The trick is that you provide the parser with all needed productions to always parse, but the valid ones come first. You then can ignore incomplete_tag during the live preview.
Second question (how to include actions):
You write socalled actions after expressions. An action is Javascript code enclosed by braces and are allowed after a pegjs expression, i. e. also in the middle of a production!
In practice actions like { return result.join("") } are almost always necessary because pegjs splits into single characters. Also complicated nested arrays can be returned. Therefore I usually write helper functions in the pegjs initializer at the head of the grammar to keep actions small. If you choose the function names carefully the action is self-documenting.
For an examle see PEG for Python style indentation. Disclaimer: this is an answer of mine.
Regarding your first question I have tosay that a live preview is going to be difficult. The problems you pointed out regarding that the parser won't understand that the input is "work in progress" are correct. Peg.js tells you at which point the error is, so maybe you could take that info and go a few words back and parse again or if an end tag is missing try adding it at the end.
The second part of your question is easier but your grammar won't look so nice afterwards. Basically what you do is put callbacks on every rule, so for example
text
= text:non_tag+ {
// we captured the text in an array and can manipulate it now
return text.join("");
}
At the moment you have to write these callbacks inline in your grammar. I'm doing a lot of this stuff at work right now, so I might make a pullrequest to peg.js to fix that. But I'm not sure when I find the time to do this.
Try something like this replacement rule. You're on the right track; you just have to tell it to assemble the results.
text
= result:non_tag+ { return result.join(''); }
According to JSHint, a Javascript programmer should not add a space after the first parenthesis and before the last one.
I have seen a lot of good Javascript libraries that add spaces, like this:
( foo === bar ) // bad according to JSHint
instead of this way:
(foo === bar) // good according to JSHint
Frankly, I prefer the first way (more spaces) because it makes the code more readable. Is there a strong reason to prefer the second way, which is recommended by JSHint?
This is my personal preference with reasons as to why.
I will discuss the following items in the accepted answer but in reverse order.
note-one not picking on Alnitak, these comments are common to us all...
note-two Code examples are not written as code blocks, because syntax highlighting deters from the actual question of whitespace only.
I've always done it that way.
Not only is this never a good reason to defend a practice in programming, but it also is never a good reason to defend ANY idea opposing change.
JS file download size matters [although minification does of course fix that]
Size will always matter for Any file(s) that are to be sent over-the-wire, which is why we have minification to remove unnecessary whitespace. Since JS files can now be reduced, the debate over whitespace in production code is moot.
moot: of little or no practical value or meaning; purely academic.
moot definition
Now we move on to the core issue of this question. The following ideas are mine only, and I understand that debate may ensue. I do not profess that this practice is correct, merely that it is currently correct for me. I am willing to discuss alternatives to this idea if it is sufficiently shown to be a poor choice.
It's perfectly readable and follows the vast majority of formatting conventions in Javascript's ancestor languages
There are two parts to this statement: "It's perfectly readable,"; "and follows the vast majority of formatting conventions in Javascript's ancestor languages"
The second item can be dismissed as to the same idea of I've always done it that way.
So let's just focus on the first part of the statement It's perfectly readable,"
First, let's make a few statements regarding code.
Programming languages are not for computers to read, but for humans to read.
In the English language, we read left to right, top to bottom.
Following established practices in English grammar will result in more easily read code by a larger percentage of programmers that code in English.
NOTE: I am establishing my case for the English language only, but may apply generally to many Latin-based languages.
Let's reduce the first statement by removing the adverb perfectly as it assumes that there can be no improvement. Let's instead work on what's left: "It's readable". In fact, we could go all JS on it and create a variable: "isReadable" as a boolean.
THE QUESTION
The question provides two alternatives:
( foo === bar )
(foo === bar)
Lacking any context, we could fault on the side of English grammar and go with the second option, which removes the whitespace. However, in both cases "isReadable" would easily be true.
So let's take this a step further and remove all whitespace...
(foo===bar)
Could we still claim isReadable to be true? This is where a boolean value might not apply so generally. Let's move isReadable to an Float where 0 is unreadable and 1 is perfectly readable.
In the previous three examples, we could assume that we would get a collection of values ranging from 0 - 1 for each of the individual examples, from each person we asked: "On a scale of 0 - 1, how would you rate the readability of this text?"
Now let's add some JS context to the examples...
if ( foo === bar ) { } ;
if(foo === bar){};
if(foo===bar){};
Again, here is our question: "On a scale of 0 - 1, how would you rate the readability of this text?"
I will make the assumption here that there is a balance to whitespace: too little whitespace and isReadable approaches 0; too much whitespace and isReadable approaches 0.
example: "Howareyou?" and "How are you ?"
If we continued to ask this question after many JS examples, we may discover an average limit to acceptable whitespace, which may be close to the grammar rules in the English language.
But first, let's move on to another example of parentheses in JS: the function!
function isReadable(one, two, three){};
function examineString(string){};
The two function examples follow the current standard of no whitespace between () except after commas. The next argument below is not concerned with how whitespace is used when declaring a function like the examples above, but instead the most important part of the readability of code: where the code is invoked!
Ask this question regarding each of the examples below...
"On a scale of 0 - 1, how would you rate the readability of this text?"
examineString(isReadable(string));
examineString( isReadable( string ));
The second example makes use of my own rule
whitespace in-between parentheses between words, but not between opening or closing punctuation.
i.e. not like this examineString( isReadable( string ) ) ;
but like this examineString( isReadable( string ));
or this examineString( isReadable({ string: string, thing: thing });
If we were to use English grammar rules, then we would space before the "(" and our code would be...
examineString (isReadable (string));
I am not in favor of this practice as it breaks apart the function invocation away from the function, which it should be part of.
examineString(); // yes; examineString (): // no;
Since we are not exactly mirroring proper English grammar, but English grammar does say that a break is needed, then perhaps adding whitespace in-between parentheses might get us closer to 1 with isReadable?
I'll leave it up to you all, but remember the basic question:
"Does this change make it more readable, or less?"
Here are some more examples in support of my case.
Assume functions and variables have already been declared...
input.$setViewValue(setToUpperLimit(inputValue));
Is this how we write a proper English sentence?
input.$setViewValue( setToUpperLimit( inputValue ));
closer to 1?
config.urls['pay-me-now'].initialize(filterSomeValues).then(magic);
or
config.urls[ 'pay-me-now' ].initialize( fitlerSomeValues ).then( magic );
(spaces just like we do with operators)
Could you imagine no whitespace around operators?
var hello='someting';
if(type===undefined){};
var string="I"+"can\'t"+"read"+"this";
What I do...
I space between (), {}, and []; as in the following examples
function hello( one, two, three ){
return one;
}
hello( one );
hello({ key: value, thing1: thing2 });
var array = [ 1, 2, 3, 4 ];
array.slice( 0, 1 );
chain[ 'things' ].together( andKeepThemReadable, withPunctuation, andWhitespace ).but( notTooMuch );
There are few if any technical reasons to prefer one over the other - the reasons are almost entirely subjective.
In my case I would use the second format, simply because:
It's perfectly readable, and follows the vast majority of formatting conventions in Javascript's ancestor languages
JS file download size matters [although minification does of course fix that]
I've always done it that way.
Quoting Code Conventions for the JavaScript Programming Language:
All binary operators except . (period) and ( (left parenthesis) and [ (left bracket) should be separated from their operands by a space.
and:
There should be no space between the name of a function and the ( (left parenthesis) of its parameter list.
I prefer the second format. However there are also coding style standards out there that insist on the first. Given the fact that javascript is often transmitted as source (e.g. any client-side code), one could see a slightly stronger case with it than with other languages, but only marginally so.
I find the second more readable, you find the first more readable, and since we aren't working on the same code we should each stick as we like. Were you and I to collaborate then it would probably be better that we picked one rather than mixed them (less readable than either), but while there have been holy wars on such matters since long before javascript was around (in other languages with similar syntax such as C), both have their merits.
I use the second (no space) style most of the time, but sometimes I put spaces if there are nested brackets - especially nested square brackets which for some reason I find harder to read than nested curved brackets (parentheses). Or to put that another way, I'll start any given expression without spaces, but if I find it hard to read I insert a few spaces to compare, and leave 'em in if they helped.
Regarding JS Hint, I wouldn't worry- this particular recommendation is more a matter of opinion. You're not likely to introduce bugs because of this one.
I used JSHint to lint this code snippet and it didn't give such an advice:
if( window )
{
var me = 'me';
}
I personally use no spaces between the arguments in parentheses and the parentheses themselves for one reason: I use keyboard navigation and keyboard shortcuts. When I navigate around the code, I expect the cursor to jump to the next variable name, symbol etc, but adding spaces messes things up for me.
It's just personal preference as it all gets converted to the same bytecode/binary at the end of the day!
Standards are important and we should follow them, but not blindly.
To me, this question is about that syntax styling should be all about readability.
this.someMethod(toString(value),max(value1,value2),myStream(fileName));
this.someMethod( toString( value ), max( value1, value2 ), myStream( fileName ) );
The second line is clearly more readable to me.
In the end, it may come down to personal preference, but I would ask those who prefer the 1st line if they really make their choice because "they are used it" or because they truly believe it's more readable.
If it's something you are used to, then a short time investment into a minor discomfort for a long term benefit might be worth the switch.