Learning something new every day can put a rational person on the road to greatness. As a developer, continuous learning of new things is part of our work, whether these new things come from positive learning experience.
In this tutorial, I'll point out some of the important JavaScript best practices that you don't have to learn in another difficult way. Get ready to upgrade your code!
1. Avoiding pollution to global scopes
Declaring variables is a very interesting thing. Sometimes even if you do not want to do this, it is possible to define a global variable. In today's browsers, global variables are stored in window objects. And because there are a lot of things in that, you might be able to overwrite some of the default values.
Suppose you have an HTML file containing a <script> tag that contains (or is loaded by referencing a JavaScript file) the following:
var foo =;
Console.log (foo);
This code is obviously going to give the console a 42 output. But since the code is not put into a function to execute, the context in which it executes is the one that is global. Therefore, the variable is appended to the Window object. This means that the value of Window.foo will also be 42.
This is dangerous because you can override a global variable that already exists:
function print () {
//do something
}
print ();
When executing window.print (or just print), it does not open the Print window because we have covered the original print window logic.
The solution to this problem is fairly simple; We need a closure function that will be called immediately after the definition, as follows:
Declare an anonymous function (
function () {
var foo = n;
Console.log (Window.foo);
→undefined
Console.log (foo);
→42
}) ();
^ and call it immediately
Or you can choose to pass the window and other global things (such as document) as arguments to that function (which may also improve performance):
(Function (Global, doc) {
global.settimeout (function () {
Doc.body.innerHTML = "hello!";
}, 1000);
}) (window, document);
So you have to use the closure function to avoid creating something global. Note that because you want to focus on the code itself, I'm not going to use the closure function in subsequent snippets.
Tip: Browserify is another way to avoid creating global variables. It takes the same way that you use the Require function in Node.js.
By the way, Node.js will automatically encapsulate your files into functions. They look like this first:
(function (exports, require, module, __filename, __dirname) {
//...
So, if you think the Require function is global, well, it's not. It is nothing more than a parameter of a function.
Do you know?
Because the Window object contains all the global variables, and because it is global, window itself refers to itself:
Window.window.window
//=> window {...}
This is a window object is a circular reference object. The following shows how to create an object like this:
Create an object
var foo = {};
Point a key value to the object itself
foo.bar = foo;
The ' Foo ' object just became a circular one:
foo.bar.bar.bar.bar
//→foo
Or, in order to show your infinite love for JavaScript, you can be a fan, as the following code reads:
Yes, you can expand this object almost endlessly (and possibly until the browser crashes).
2. Good use strict habits
Use strict! Strictly This is simply adding a line to your code and adding more tricks to your script.
For example:
This is bad, since your do create a global without have anyone to tell you
(function () {
a =;
Console.log (a);
→42
}) ();
Console.log (a);
→42
Using use strict, you can get a little more error information:
(function () {
"use strict";
A =;
Error:uncaught referenceerror:a is not defined
}) ();
You may wonder why you can place "use strict" outside of the encapsulated function. This can be true, but it will be applied to the global. That's not too bad, but if there's code that comes from other libraries, or you want to package everything in a file, it's going to have an impact.
3. Strictly equal
This is relatively short. If you use = = to compare A and B in JavaScript (as in other programming languages), you may find that the way it runs is a bit strange: if you have a string and a number like this, they will be equal (= =):
"//→true" = =
For some obvious reasons (for example, validation operations), it is best to use strict equals (= = = =):
"//→false" = =
4. Use && and | | To make a little trick.
Root what you need to do, you can use logical operators to make the code shorter.
Take default values
"" || " Foo "
//→" foo "
undefined | |
//→42
//Note this if you want to handle 0 there, your need
//to Che CK If a number was provided:
var a = 0;
A | |
//→42
//This are a ternary operator-works like a inline if-else statement
var b = typeof A = = "Numbe R "? a:42;
→0
You can simply do this without using an if expression to check that something is true:
Expr && dosomething ();
Instead of:
if (expr) {
dosomething ();
}
If you need to go through dosomething (): To decide which results to return, this is cooler:
function dosomething () {return
{foo: ' Bar '};
}
var expr = true;
var res = expr && dosomething ();
Res && Console.log (res);
→{foo: "Bar"}
You may not agree with me on this, but as I said, it actually works better. If you don't want to confuse your code like this, this is actually what the JavaScript simplifications actually do.
If you ask me, I'll say this makes the code shorter, but still readable.
5. Conversion of value types
There are several ways to translate from your ideas. The most commonly used methods are the following:
from anything to a number var foo = "42"; Var mynumber = +foo; // shortcut for number (foo)// → 42// Tip: you can convert it directly into a negative number var Negativefoo = -foo; // or -number (foo)// → -42// From object to array// tip: ' arguments ' is an object and in general you want to use it as array var args = { 0: "foo",
1: "Bar", length: 2 }; Array.prototype.slice.call (args)// → [ ' foo ', ' Bar ' ]// anything to
Boolean/// non non p is a boolean p var t = 1; var f = 0;!! T// → true!! F// → false/// and non-p is&Nbsp;a boolean non-p!t// → false!f// → true// anything to string
var foo = 42; "" + foo // shortcut for string (foo)// → "foo = { "
hello: "World" };
Json.stringify (foo); → ' { "Hello": "World" &NBSP;} ' Json.stringify (foo, null, 4); // beautify the things// →// ' {// "hello": "World"//&NBSP;} '// Note
you cannot json.stringify circular structures json.stringify (window); ⚠ typeerror: json.stringify cannot serialize cyclic structures.
6. Code style/Style guide
In the new project, make all the files conform to the same code style. For an existing project, use the existing code style, unless you just decide to change its style (hint: talk to your partner about this). Even you have to create and record your own code style, and then go on to follow it.
Some of the different code styles that are available are as follows:
Bonus tips for extra benefits:
Some of the other important JavaScript best practices you should keep in mind are the tools that can help you format your code. Here are some of them:
Js-beautify: Beautify Your code
UGLIFYJS (2): confusing/Minimizing your code
Jshint: Detects errors or potential problems in JavaScript code
Jscs: A style guide checker that can be configured
The last one is: Do not always console.log, to debug your code.
I wish you a happy programming!
Original address: Https://www.codementor.io/johnnyb/tutorials/javascript-best-practices-du107mvud