Part I programming style

Chapter 4 variables, functions, and Operators

4.1 Variable Declaration

The authors recommend that the definition of local variables always be the first statement in a function, and that all var statements be merged into a single statement, with the initialization of each variable on a single line, and for variables that have no initial value, they should appear at the end of the var statement.

4.2 Function Declaration

It is always recommended to declare functions first and then use them. In addition, function declarations should not appear within a statement block.

4.3 Function Call Interval

In general, the recommended style for function calls is to write with no space between the function name and the opening parenthesis to distinguish it from the statement block.

4.4 Call the function immediately

JavaScript allows you to declare anonymous functions and assign them to variables or attributes.

This anonymous function can also be executed immediately by enclosing a pair of parentheses at the end and returning a value, which is then assigned to the variable.

// It's a bad way to write
var value = function(){
    return {
        message: "Hi"
    }
}();
Copy the code

In this example, value ends up being assigned to an object because the function executes immediately. The problem with this pattern is that it gives the impression that you are assigning an anonymous function to the variable, and until you read the whole code and see the parentheses on the last line, you don’t know whether you are assigning the function or the result of the function to the variable.

To make the immediate function visible at first sight, you can wrap the function around a pair of parentheses, such as:

// Good way to write it
var value = (function(){
    / / the function body
    return {
        message: 'Hi'
    }
})();
Copy the code

This code has an identifier (left parenthesis) on the first line, indicating that this is an immediate function. Adding a pair of parentheses does not change the logic of the code. Crockford’s programming specification recommends this pattern, and JSLing will warn if the parentheses are omitted.

4.5 Strict Mode

ECMAScript5 introduces “strict mode”, which is intended to carefully parse and execute JavaScript to reduce errors.

It is not recommended to use “use strict” in global effects, as this causes all code in the file to be parsed in strict mode, so if you join 11 files into a file and one file has strict mode enabled in global effects, all code will be parsed in strict mode. Because the operation rules in strict mode are very different from those in non-strict mode, it is very likely that the code in other files will report errors. Therefore, it is best not to use “use strict” in global effects. Here are some examples.

// Bad writing - global strict mode
"use strict"
function doSomething() {
    / / code
}

// Good code
function doSomething() {
    "use strict"
    / / code
}
Copy the code

If you want to apply strict mode to multiple files without having to write many lines of “use strict”, you can use the execute now function.

// Good way to write it
(function() {
    "use strict"
    function doSomething() {
        / / code
    }
    
    function doSomethingElse() {
        / / code}})Copy the code

Both JSHint and JSLint give warnings when “use strict” occurs outside of a function. JSLint and JSHint want all functions to include “use strict” by default. Of course, this option can be turned off in both tools. The authors recommend using strict mode whenever possible to reduce common errors.

Equal to 4.6

Equality is tricky in JavaScript because of its casting mechanism.

The most common scenario where casts occur is when the equality operators == and! When =, both operators are cast when the two worth types being compared are different.

Because of casting, we recommend not using == and! =, should use === and! ==, the comparison between the two operators does not involve casts.

4.6.1 eval ()

In JavaScript, eval() takes a string as an argument, and eval() executes the string as code. Developers can use this function to load external JavaScript code, or generate JavaScript code and execute it. Such as:

eval("alert("Hi!")");

var count = 10;
var number = eval("5 + count");
console.log(count); / / 12
Copy the code

Eval () is not the only Function that can execute JavaScript strings in JavaScript. The Function constructor also does this, as do setTimeout() and setInterval().

By default, both JSLint and JSHint warn against using eval(), Function, setTimeout(), and setInterval().

The ECMAScript5 strict mode has strict restrictions on eval(), which prohibits using it to create new variables or functions in a closed function. This limitation helps us avoid the inherent security vulnerabilities of eval(), however, it is still recommended to use eval() if there is really no other way to accomplish the task at hand.

4.6.2 Original packing type

There are three primitive wrapper types in JavaScript: String, Boolean, and Number. Each type represents a globally applied constructor in, and represents its corresponding original worth object, respectively. The primary purpose of primitive wrapper types is to make primitive values behave like objects, such as:

var name = "Nicholas";
console.log(name.toUppercase());
Copy the code

Even though name is a string and a primitive type, not an object, you can still use methods like toUpperCase() to treat a string as an object. This works because behind the appearance of this statement the JavaScript engine creates a new instance of String, which is then destroyed and another object is created when needed again. You can test this behavior by adding attributes to strings.

var name = "Nicholes";
name.author = true;
console.log(name.author); // undefined
Copy the code

After the end of line 2, the author attribute disappears. Because the temporary String representing the String is destroyed at the end of line 2, a new String is created in line 3. You can also create these objects manually.

// Bad practice
var name = new String("Nicholes");
var author = new Boolean(true);
var count = new Number(10);
Copy the code

Although these types of packaging can be used, the authors strongly recommend avoiding them. Developers often jump back and forth between objects and their original values, which increases the chance of bugs that confuse developers, and there’s no reason to create objects by hand.