JavaScript is a programming language required for Web development. It was created in 1995 to add programs to Web pages in the Netscape Navigator browser. Today, the language is supported by all other major web browsers.

Set up the environment

There will be many sample code snippets throughout this tutorial. To execute this code, simply open a browser and go to Developer Tools -> Console:

Or you can install Node.js on your computer, which allows you to run JavaScript programs using a command terminal. Once installed, type Node in the terminal to start typing JavaScript as follows:

You can also run JavaScript on online platforms such as Codepen.

The data type

In the computer world, it’s all about data. What a computer program does is essentially take some input data, process it, and eventually return some output data. Here’s a look at some of the different types of data that JacaScript can handle.

Number

Numbers are the easiest, because they work exactly the same way they were taught in elementary school math class.

// Integer 100 // decimal 10.56 // scientific notation 3.14e5 // 3.14 * 10^5 = 314000Copy the code

The main use of numbers is in arithmetic operations.

3 + 5 * 2 // Output 13Copy the code

One operator that you may not recognize is a modulo (%) operation. X % Y calculates the remainder of X divided by Y. Such as:

25% 5 // The result is 0 25% 10 // the result is 5Copy the code

string

Strings are used to represent text, and they are enclosed in quotes (either single or double quotes, I prefer double quotes), as shown below:

"Made in China.";
'Made in China.';
Copy the code

Single and double quotes work exactly the same as long as the quotes at the beginning and end of the string match.

Whenever a backslash \ is found in a string, it means that the character following it has a special meaning, commonly known as an escape character. For example, when the character n is followed by a backslash, the computer interprets it as a newline:

"Made in China \n ";Copy the code

The output is:

It is Made in ChinaCopy the code

Here are some common escape characters:

Escape character As shown in the meaning
\n A newline
\r A carriage return
\t Horizontal TAB character
\b Back space
\ \ The backslash\
\ ' Single quotes '
\" Single quotes "

The plus + operator can also be used for strings. Obviously, strings cannot be used for arithmetic operations. The plus sign in a string represents concatenation (concatenating two characters together).

"Made in China:" + "Made in China"Copy the code

The final output is:

Made in ChinaCopy the code

In ES6, there is a special kind of string, the backquoted string, often called template literals. It allows you to embed other variable values in a string:

const country = "China";
const str = `Made in ${country}`;
console.log(str); // Made in China
Copy the code

Of course, it may not be a variable, as follows:

Const STR = '100 half of ${100/2}'; console.log(str); // Half of 100 is 50Copy the code

Boolean value

The Boolean value type contains only two values: true and false, as follows:

console.log(1 == 1); // true console.log(1 > 2); // false console.log(1 < 0); // false console.log(1 ! = 2); // trueCopy the code

In the code above, == means equal,! = means unequal. In actual project development, it is recommended to use identity, replacing == and with ===! = = replace! =. Other similar operators include >= (greater than or equal to) and <= (less than or equal to).

In JavaScript, three logical operators can be applied to Boolean values, && (with), | | (or),! (a).

The && operator represents the logical and, and the result is true only if two or more values given to it are true.

console.log(true && false); // false
console.log(false && true); // false
console.log(false && false); // false
console.log(true && true && true); // true
console.log(false && false && true); // false
Copy the code

&& logic can be used to optimize conditional statements as follows:

const month = 12; const dosome = () => { console.log("dosom"); }; if (month === 12) { dosome(); } // Logic and simplification month === 12 && dosome();Copy the code

| | logic or the operator said, if it’s any value to true, the result is true. The result is false only when all conditions are false.

console.log(true || false); // true
console.log(false || true); // true
console.log(false || false); // false
console.log(true || true); //  true
Copy the code

| | logic or a default value can be user-defined variables, as follows:

const age = inputAge || 18; // When inputAge is false, the value 18 is assigned to ageCopy the code

! The operator represents a logical non and inverts the value.

console.log(! true); // false console.log(! false); // trueCopy the code

A null value

There are two special values in JavaScript, null and undefined, which indicate a meaningless value and can be interpreted as null. The two values don’t look very different, and in fact, in most cases, you can think of them as interchangeable. Having two different values for the same thing is an accident of JavaScript design. At the same time, this accident adds complexity to nullvalue judgment. Although null and undefined can be understood as the same meaning, they are still compared differently. For more information, see Null and undefined in JavaScript again.

Data type conversion

JavaScript is a weakly typed language, which leads to a very arbitrary nature of programming, with many cases of trying to execute the code submitted to it, even if the code doesn’t make sense. Such as:

console.log(8 * null); // 0 console.log("8" - 1); // 7 console.log("8" + 1); / / 81Copy the code

In the first example, NULL is converted to the number 0, and in the second example, the string “8” is converted to the number 8. However, in the third example, the number 1 is converted to the string “1”, concatenating the two strings with a plus sign, so the result becomes 81.

Program structure

Statement and assignment

In computer programming, “programs” can be thought of as instruction manuals for solving complex problems. Each instruction/sentence in this manual is called a statement. In JavaScript, each line of code should always be marked with a semicolon; At the end. This can be done automatically by the code editor.

const num = 10;
Copy the code

The code above is called change definition and assignment. It assigns the value 10 to the constant num using the = operator. If it is a variable, it can be defined using let or var, as follows:

let num = 10;
Copy the code

The keywords const, let, and var can all be used to define variables, but they have different scopes.

function

A function is a program that returns a value or has some side effects, or both. For example, the console.log() function above is used to output values at the terminal. Alternatively, the prompt() function displays a dialog that asks for user input and assigns the input value to the variable num.

Let num = prompt(" please enter a number: "); console.log(num);Copy the code

Displaying conversations and writing text to the screen are side effects. Functions without side effects are also useful. Such as:

console.log(Math.max(2, 4, 6, 8)); / / 8Copy the code

Math.max() has no side effects, it just takes a set of numbers and returns the maximum.

All of these features are built into the browser. You can also use JavaScript to create your own functions. Let’s look at the statements that make up the functions.

If statement

The if statement provides a way to execute different pieces of code under different conditions. Such as:

Const num = prompt(" Please enter an integer: "); If (num < 10) {console.log(" < 10"); } else {console.log(" > 10"); }Copy the code

This program asks you to enter an integer. If the number is less than 10, the statement console.log(” less than 10″); Will be executed, the program will output less than 10. If the number is greater than 10, the program prints greater than 10.

If you need to include more than one condition, you can also use multiple if/else pairs:

Const num = prompt(" Please enter an integer: "); If (num < 10) {console.log(" < 10"); } else if (num < 100) {console.log(" < 100"); } else {console.log(" > 100"); }Copy the code

The for loop

A for loop provides a way to execute the same code over and over again, provided certain conditions are met.

for (let num = 0; num <= 12; num = num + 2) {
    console.log(num);
}
Copy the code

The while loop

The while loop works in a similar way, except that it requires only one expression. In fact, you can easily change the previous example of a for loop to a while loop. As follows:

let num = 0;
while (num <= 12) {
    console.log(num);
    num = num + 2;
}
Copy the code

The do while loop

A do-while loop differs from a while loop only in that it guarantees that the body of the loop is executed at least once.

let num = 10;
do {
    num = num + 1;
    console.log(num);
} while (num <= 1);
Copy the code

This time, the initial value of num is 10, and there is no condition that triggers the loop to continue. But because this is a do-while loop, the body still executes once. If this were a while loop, it wouldn’t execute at all.

Cyclic interrupt

A condition that does not trigger the loop to continue is not the only way to stop the loop. For example, ask to find a number greater than 100 that is divisible by 9.

for (let num = 100; ; num = num + 1) { if (num % 9 === 0) { console.log(num); break; }}Copy the code

Notice that there is no expression that determines whether the loop continues. Instead, there is an if statement with a break keyword in it that will break out of the loop if it is executed.