My Best Practices – JavaScript
1. Disable the cache
Firefox:
Open Developer Tools -> Open Settings (F1) -> "Disable HTTP Cache (when toolbox is open)"
Chrome:
Open Developer Tools -> Open Settings (F1) -> "Disable cache (while DevTools is open)"
2. Keep the JS console open
Open the Console tab in the DevTools and keep it open, so that step 1 stays in effect and you also catch network and JS errors.
Also worth recommending is this plugin, which displays JS errors even better, for when you forget to keep an eye on them yourself:
3. JavaScript: required reading – “You Don't Know JS”
- You Don't Know JS (1st Edition)
- Explains why you should avoid
this - Explains why seemingly weird things sometimes happen in JS (keywords: lexical scope, closures)
4. The semicolon
- Always use it
- It’s not mandatory, but it can help you avoid pitfalls like this one: Stack Overflow
- JavaScript inserts a semicolon automatically:
// you want to return 5 and have ugly formatting:
return
5
// JavaScript Interpretation:
return;
5;
5. Logical operators && and ||
- In Java,
a && banda || bare evaluated according to Boolean algebra.aandbhave to be booleans. - In JavaScript:
- With
a && b,bis returned ifais truthy - With
a || b,bis returned ifais falsy
- With
Expressions can be chained this way, too, which gives you the shortest if statement ever – syntactic sugar:
isAdmin && showDeleteButton();- (Strictly speaking, it’s no longer a statement)
It’s also popular for default values:
let sendNewsletter = form.getNewsletterOptIn() || false;
6. Is JavaScript pass-by-reference or pass-by-value?
It's interesting in JavaScript. Example:
function changeStuff(a, b, c) {
a = a * 10;
b.item = "changed";
c = {item: "changed"};
}
var num = 10;
var obj1 = {item: "unchanged"};
var obj2 = {item: "unchanged"};
changeStuff(num, obj1, obj2);
console.log(num);
console.log(obj1.item);
console.log(obj2.item);
Produces the following output:
10
changed
unchanged
If obj1 weren’t a reference at all, changing obj1.item would have no effect whatsoever on obj1 outside the function.
If the argument were a true reference, everything would change: num would be 100, and obj2.item would contain “changed”. Instead, num stays at 10 and
obj2.item stays “unchanged”.
In fact, the item is passed by value. But what gets passed by value is itself a reference. Technically, this is called call-by-sharing.
In practice, this means: if you change the parameter itself (as with num and obj2), it has no effect on the original object that was passed into the function.
If you change the parameter’s internal values, however, those changes do carry over (as with obj1).