JavaScript minimalist tutorial (1) : the basics

  • 2020-03-30 04:10:39
  • OfStack

Reading this article requires programming experience in other languages.

Before we start learning

Most programming languages have good parts and bad parts. This article only covers the good parts of JavaScript because:

1. Only the good parts can shorten the learning time
2. Write more robust code
Write code that is easier to read
4. Write code that is easier to maintain

Weak and strong

In general, the sooner you fix a bug, the less it costs. Compilers for strongly typed languages can check for certain errors at compile time. JavaScript is a weakly typed language, and its interpreter cannot check for type errors, but practice shows that:

1. The errors that strong typing avoids are not the critical ones
2. Weak typing brings flexibility without the baggage of strong typing

JavaScript related standards

The ecma-262 standard defines the language ECMAScript. JavaScript and ActionScript, as we know them, are based on ECMAScript. The current mainstream USES ecma-262 version 5, which Google's V8 engine implements.

Hello JavaScript

JavaScript is a scripting language that requires an interpreter to interpret execution. You can interpret JavaScript in the browser or use node. js directly, which incorporates Google's V8 JavaScript engine. Because node.js is so easy to use, I use node.js here to explain executing JavaScript. Now look at the first JavaScript program:


// test.js
console.log("Hello JavaScript");

Execute this program:


node test.js

grammar

annotation

JavaScript USES the same annotation approach as C++, with // for single-line annotations and multi-line annotations.

Numeric types

JavaScript has only one numeric type, a 64-bit floating point number. The number type has two special values NaN and Infinity, NaN means not a number (not a number), use the function isNaN to check for NaN, and Infinity means Infinity. In the Math object, there is a set of methods that manipulate Numbers, for example, the math.floor method is used to round down.

string

The string literal can be wrapped in single or double quotes, escape characters using \ (not unlike many other languages). Each character in JavaScript is two bytes and USES the Unicode character set. String has a length property:


"Hello".length //The value is 5, not "Hello".length()

Strings cannot be changed (just like Lua), and there are methods other than the length property mentioned here, such as:


'cat'.toUpperCase() === 'CAT'

statements

The var statement is used to declare a local variable, otherwise the variable is global and the value of an uninitialized variable is undefined:


function f() {
    var localVar = 123;
    globalVar = 456;
    var i; //The value of I is undefined
};
 
f();
 
console.log(globalVar); // ok
console.log(localVar); //Error, localVar is not defined

A set of statements wrapped in {} is called a Block. Unlike other languages, functions in JavaScript do not create new scopes and blocks do not, for example:


{
    var v = 123;
}
console.log(v); // ok

If statement


if (expression)
    statement

or


if (expression)
    statement1
else
    statement2

or


if (expression1)
    statement1
else if (expression2)
    statement2
else if (expression3)
    statement3
else
    statement4

The if statement decides to execute or skip certain statements by determining whether the value of the expression is true or false. In JavaScript, the following values are false (all other values are true) :

1. The false
2. Null
3. The undefined
4. Empty string
5.0
6. NaN

A statement in an if can be either a statement or a statement block.

A switch statement


switch (n) {
    case 1: //If n is equal to 1 is less than br over >     //Execute block
    break;
    case 2: //If n is equal to 2 is less than br over >     //Execute block
    break;
    default: //If n is neither 1 nor 2
    //Execute block
    break;
}

The break here is used to exit a loop or switch statement. In JavaScript, there are two operators for comparing two values:

1.== (corresponding! = operator), equal, the two operand types are different, this operator tries to convert the operand type to make a comparison, for example:


var x = 1;
x == 1; // true
x == "1"; // true

2.=== (corresponding! == operator), exactly equal, compare two operands without operand type conversion, for example:


var x = 1;
x === 1; // true
x === "1"; // false

Notice that NaN is not equal to any value, if x is NaN, then x! == x (only true for NaN), we can implement the isNaN function like this:


function isNaN(n) {
    return n !== n;
}

The above switch statement is converted to if statement:


if (n === 1)
    // ...
else if (n === 2)
    // ...
else
    // ...

While and do-while statements


while (expression)
    statement

If expression is true, repeat the statement until expression is false.


do
    statement
while (expression);

Similar to a while loop, except that the statement is executed and then the conditional expression is checked.

For statement


for (initialize ; test ; increment)
    statement

Initialize is first executed once (usually to initialize loop variables), then test the condition (usually to test loop variables), stop the loop if the test condition is false, otherwise execute the statement, then increment (often to update loop variables), then test the condition, and so on. Examples of use:


for (var i=0; i<5; ++i) {
    console.log(i);
}

Another form of for is used to enumerate all the property names of an object:


for (variable in object)
    statement

Example:


var obj = {
    a: 1,
    b: 2,
    c: 3
};
 
for (var name in obj)
    console.log(name);

Note that we use the hasOwnProperty method to check whether the property name belongs to the object or is found in the prototype chain (which prototype will cover in the next article) :


for (var in obj) {
    if (obj.hasOwnProperty(var)) {
        // ...
    }
}

Return statement

The return statement is used to return a value. If the function does not explicitly use return, return undefined:


function f() { }
var v = f(); // v === undefined

The & # 63; : conditional operator (the only ternary operator in JavaScript)
The & # 63; : the conditional operator exists in many programming languages. When the first operand is true, the operator returns the value of the second operand. Otherwise, the value of the third operand is returned.


function abs() {
    return x > 0 ? x : -x;
}

The typeof operator

The typeof operator is used to get the typeof the variable and its return value includes:

1. The 'number'
2. 'string'
3. 'Boolean'
4. "undefined"
5. 'function'
6. 'object'

The result of the special typeof null is 'object'. Example of typeof:


var a = typeof 'hello'; // a === 'string'
var b = typeof null; // b === 'object'

The + operator

The + operator can be used for addition or string concatenation in JavaScript:


var message = 'hello' + 'world'; // message === 'helloworld'

Ampersand and || operators

The && operator returns the value of the first operand when the first operand is false, otherwise the value of the second operand
The || operator returns the value of the first operand when the first operand is true, otherwise the value of the second operand


var a = 1 && true; // a === true
var b = 1 || false; // b === 1

An idiom for || :


name = name || 'unknown'; //Set the default value of 'unknown' for name


Related articles: