post-css-position

Best JavaScript Definitive Guide for Beginners 2019 – Quick Start

JavaScript is the world’s most popular scripting language. This is the JavaScript definitive guide for beginners who want to become full stack developers. A JavaScript quick start will be given.

Start learning JavaScript right away, and don’t be eliminated by the Web era.

Preface

JavaScript derives all the Web pages you browse on your computer, mobile phone, tablet, and countless HTML5-based mobile apps.

Simply put, JavaScript is an interpreted programming language that runs in a browser.

So the question is, why do we have to learn JavaScript? Especially when you have mastered some other programming languages such as Java and C++.

The simple and rude answer is: because you have no choice. In the Web world, only JavaScript can drive Web pages across platforms and browsers to interact with users.

The ActionScript behind Flash has been popular for a while. But with the rise of mobile apps, no one will develope a mobile app with Flash. So it is now marginalized.

As HTML5 becomes more popular on PCs and mobiles, JavaScript becomes even more important. And, the emerging Node.js brings JavaScript to the server side.

JavaScript has become a versatile player.

JavaScript was once considered a toy programming language, and it has many flaws. So it is not valued by most back-end developers. Many people believe that writing JavaScript code is easy and JavaScript is just to add a bit of interaction and animation to the page.

But this is a completely wrong understanding. JavaScript is really easy to use, but its essence is not well-known to most developers. Writing high-quality JavaScript code is even harder.

A qualified developer should master JavaScript. If you already known other programming languages, or if you still can’t do programming, this JavaScript Definitive Guide is dedicated for you!

JavaScript History

To understand JavaScript, let’s first review the birth of JavaScript.

In the last century of 1995, Netscape is the most famous first-generation Internet company, when the Web era was opened with its Navigator browser.

Since Netscape wanted to add some dynamic effects to the static HTML page, they asked Brendan Eich to design the JavaScript language within two weeks. Actually, this buddy only took 10 days.

Why the name JavaScript? The reason is that the Java language was very popular at that time. So Netscape wanted to use Java’s fame to promote it. But, in fact, JavaScript is a bit like Java in terms of syntax, and the other parts are basically have nothing to do with it.

ECMAScript

A year later, Microsoft developed JScript in response to JavaScript. In order to make JavaScript a global standard, several companies have collaborated with ECMA (European Computer Manufacturers Association) to customize the standard for JavaScript language, called the ECMAScript standard.

So in a nutshell, ECMAScript is a language standard, and JavaScript is Netscape’s implementation of the ECMAScript standard.

So why not just set JavaScript as the standard? Because JavaScript is a registered trademark of Netscape.

But most of the time, we still use the word JavaScript. If you encounter the word ECMAScript, simply replace it with JavaScript.

JavaScript Version

The JavaScript language was designed in 10 days. Although the language designer is very excellent, it is a work urged by the deadline. Therefore, JavaScript has many design flaws. We will kindly remind you in our later JavaScript definitive guides.

In addition, because the standard of JavaScript, ECMAScript, is constantly evolving, the latest version of the ECMAScript 6 standard (ES6) has been officially released in June 2015. Therefore, when it comes to the version of JavaScript, it actually means the specific version of the ECMAScript standard.

Many users are still using the old version of the browser, which only support old version of JavaScript. This leads you to take care of the old browsers when writing JavaScript. You can’t write them with the latest ES6 standard. Otherwise, the old browser is unable to run the new version of the JavaScript code.

However, the core syntax of JavaScript has not changed much. Our tutorial will first talk about the core usage of JavaScript, and then introduce new features for ES6.

JavaScript Definitive Guide – Quick Start

Without further ado, let’s start learning JavaScript quickly.

JavaScript code can be embedded directly anywhere on the page, but usually we put the JavaScript code in <head> or just before the </body>.

<html>
<head>
  <script>
    alert('Hello, world');
  </script>
</head>
<body>
  ...
  <script>
    alert('Hello, world');
  </script>
</body>
</html>

The code contained inside <script>..</script> is your JavaScript code. The browser will interpret the code and execute it.

The second method is to put the JavaScript code into a separate .js file and then import the file in the HTML via <script src="/static/js/abc.js"></script>

<html>
<head>
  <script src="/static/js/abc.js"></script>
</head>
<body>
  ...
</body>
</html>

In this way, /static/js/abc.js will be executed by the browser.

Putting JavaScript code in a separate .js file is more convenient for maintaining code. If some Web pages have similar interaction requirements, it is better to use a single .js in those pages to reuse the process logic.

Multiple .js files can be imported in one page, and the tag <script> can be written multiple times in the page. The browsers executes those scripts sequentially.

Sometimes you will see that the script also has a type attribute, e.g.,

<script type="text/javascript">
  ...
</script>

But this is not necessary, because the default type is JavaScript, so you don’t have to explicitly specify type as JavaScript.

Which Editor Should I Use?

To write JavaScript code, you will need a good text editor. Here we recommend the following text editors:

  • Visual Studio Code is a great code editor. Free! Cross-platform! Built-in JavaScript support, highly recommended!
  • Sublime Text is a handy text editor that is free, but will pop up a prompt box from time to time if you do not register.
  • Notepad++ is also a free text editor, but only for Windows.

Note: You can’t write JavaScript or HTML with Word or WordPad, because formatted text is not a plain text file and cannot be read by the browser. Also try not to write in Notepad, it will add a BOM header when saving UTF-8 formatted text.

How to Run JavaScript?

In order for a browser to run JavaScript, you must first have an HTML page, introduce JavaScript into the HTML page, and then let the browser load the HTML page to execute the JavaScript code.

You might think, create HTML and JavaScript files directly on my hard drive, and open them in a browser. Can you see the effect?

There is no problem to run some JavaScript code in this way, but due to the security restrictions of the browser, the address starting with file:// cannot accomplish certain functionalities such as networking. In the end, you still need to set up a Web server and then visit a site start with http:// to execute all JavaScript code normally.

However, at the beginning of the learning phase, you don’t have to care about how to set up the development environment. We recommend to use a free online environment to enter JavaScript code and run it directly on the page, allowing you to focus on JavaScript learning.

Exercise 1

Run the following code in js.do.

<script>
  alert('Hello, world');
</script>

The browser will pop up a dialog box that says “Hello, world”. You can also modify the contents inside the quotes and try to run.

Debugging

As the saying goes, “If you want to do something good, you must first sharpen it.” When writing JavaScript, if you want to display ABC, the result is XYZ. In the end, what went wrong with the code? Don’t be crazy, don’t be discouraged. As a beginner, you must be convinced that there is no problem with JavaScript itself, and there is no problem with browser execution. The problem must be the code.

How to find the problem code? This requires debugging.

How to debug JavaScript code in the browser?

First, you need to install the Google Chrome browser, which is very developer friendly and allows you to easily debug JavaScript code. Download the Chrome browser from here.

After installation, just open a Web page, and then click on the menu “View” – “Developer” – “Developer Tools”, the browser window will be split into two, below is the screenshot of Chrome developer tool:

Best JavaScript Definitive Guide for Beginners 2019 - Quick Start 1

First click on “Console”, in this panel you can directly enter the JavaScript code, press Enter to execute.

To view the contents of a variable, enter console.log(a); in the Console. The value displayed after the hit of Enter key is the content of the variable.

To close the Console, click on the “×” button in the upper right corner. Please be familiar with the use of Console. When writing JavaScript code, you often need to run the test code in Console.

If you have higher requirements for yourself, you can research the “Sources” of the developer tool, and master some advanced debugging techniques such as breakpoints and single-stepping.

Exercise 2

Open Github, then look at the page source code, find the imported JavaScript file and the JavaScript code written directly on the page. Then open the developer tool in Chrome, enter console.log('Hello'); in the Console, and press Enter to see the JavaScript code execution results.

Syntax of JavaScript

The syntax of JavaScript is similar to the Java language, with each statement ending with a semicolon ;, and each statement block within brackets {}. However, JavaScript does not mandate that adding semicolon at the end of each statement. The JavaScript engine, which is responsible for executing JavaScript code in the browser, will automatically fill a semicolon in at the end of each statement.

WARNING: Allowing the JavaScript engine to automatically add a semicolon in some cases will change the semantics of the program, causing the results to be inconsistent with expectations.

In this tutorial, we will not omit semicolon ; in all statements.

For example, the following line of code is a complete assignment statement:

var x = 1;

The following line of code is a string, but can still be considered a complete statement:

'Hello, world';

The following line of code contains two statements:

var x = 1; var y = 2;
// It is not recommended to write multiple statements in one line!

A statement block is a collection of statements. For example, the following code makes a judgment first. If the judgment is true, all statements inside {} will be executed:

if (2 > 1) {
    x = 1;
    y = 2;
    z = 3;
}

Note that statements in curly braces {} have indentation, usually four spaces. Indentation is not required for JavaScript grammar requirements, but it helps us understand the level of code. So please follow the indentation rules when writing code. Many text editors have an “auto-indent” feature that organizes your code automatically.

{} can also be nested to form a hierarchical structure:

if (2 > 1) {
    x = 1;
    y = 2;
    z = 3;
    if (x < y) {
        z = 4;
    }
    if (x > y) {
        z = 5;
    }
}

JavaScript itself has no restrictions on the level of nesting, but too much nesting will undoubtedly increase the difficulty of understanding the code. In this case, you need to extract some of the code and define it as a function, which can reduce the complexity of the code.

Comment

Characters beginning with // until the end of the line are treated as line comments. Comments are intended for the developer, and the JavaScript engine automatically ignores them:

// This is a line of comment.
alert('hello'); // This is also a comment.

Another block comment is to wrap multiple lines of characters with /*...*/ and treat a large “block” as a comment:

/* Starting from here is a block comment
 Still a comment
 Still a comment
 End of comment */

Exercise 3

Comment out the following statement with line comments and block comments, respectively.

alert("Please comment me.");
alert("I don't want to being executed.");

Type of Data in JavaScript

Computers, as the name suggests, are machines that can do mathematical calculations. So computer programs can handle various numbers ​​of course. However, computers can handle far more than just numerical values. They can also process a variety of types of data such as text, graphics, audio, video, and Web pages.

JavaScript defines the following data types:

Number

JavaScript does not distinguish between integers and floating-point numbers. It is uniformly represented by Number. The following are valid Number types:

123; // integer 123
0.456; // floating point number 0.456
1.2345e3; // Scientific notation means 1.2345x1000, equivalent to 1234.5
-99; // negative number
NaN; // NaN means Not a Number, expressed as NaN when the result cannot be calculated
Infinity; // Infinity means infinite, when the value exceeds the maximum value that JavaScript can represent, it is expressed as Infinity

Because computers use binary representations, sometimes it is convenient to use hexadecimal to represent integers. Hexadecimal is represented by 0-9, a-f with a 0x prefix, for example: 0xff00, 0xa5b4c3d2, etc.

Numbers can do arithmetic directly, and the rules are consistent with what you have learned in school:

1 + 2; // 3
(1 + 2) * 5 / 2; // 7.5
2 / 0; // Infinity
0 / 0; // NaN
10 % 3; // 1
10.5 % 3; // 1.5

Note that % is a remainder operation.

String

A string is any text enclosed in single quotes ' or double quotes ", such as 'abc', "xyz", etc. Note that '' or "" itself is just a representation, not part of a string. So the string 'abc' has only 3 characters a, b, and c.

Boolean value

The Boolean value is exactly the same as the Boolean algebra. The Boolean type has only two values, true and false. It is either true or false. Meanwhile, there are Boolean operations dedicated for Boolean values:

true; // This is a true value
false; // This is a false value
2 > 1; // This is a true value
2 >= 3; // This is a false value

The && operation is an AND operation, and only all values are true, and the result of && operation is true:

true && true; // => true
true && false; // => false
false && true && false; // => false

The || operation is an OR operation, and if one of the values is true, and the result of || operation is true:

false || false; // => false
true || false; // => true
false || true || false; // => true

The operation ! is a non-operation, it is a monocular operator, turning true to false and false to true:

!true; // The result is false
!false; // The result is true
!(2 > 5); // The result is true

Boolean values ​​are often used in conditional judgments, such as:

var age = 15;
if (age >= 18) {
    alert('adult');
} else {
    alert('teenager');
}

Comparison Operator

When we compare Numbers, we get a Boolean value by comparison operators:

2 > 5; // => false
5 >= 2; // => true
7 == 7; // => true

In fact, JavaScript allows comparisons of arbitrary data types:

false == 0; // => true
false === 0; // => false

Pay special attention to the equality operator ==. When designing JavaScript, there are two comparison operators:

  • The first one is == comparison, which automatically converts the data types and compares them. In many cases, you get very weird results.
  • The second is === comparison, it does not automatically convert the data type, if the data type is inconsistent, it returns false, if it is consistent, then compare.

IMPORTANT: Due to the design flaw of JavaScript, don’t use == comparison, always insist on using === comparison.

Another exception is that the special Number of NaN is not equal to all other values, including itself:

NaN === NaN; // => false

The only way to determine NaN is through the isNaN() function:

isNaN(NaN); // => true

Finally, pay attention to the equality comparison of floating point numbers:

1 / 3 === (1 - 2 / 3); // false

This is not a design flaw in JavaScript. Floating-point numbers produce errors during the operation because the computer cannot accurately represent infinite loop fractions.

To compare the equality of two floating-point numbers, you can only calculate the absolute value of their difference to see if it is less than a certain threshold:

Math.abs(1 / 3 - (1 - 2 / 3)) < 0.0000001; // => true

Null and Undefined

null represents an “empty” value, which is different from 0 and the empty string ''. 0 is a number, '' is a string of length 0, and null is “empty”.

In other languages, there are also null-like representations. For example, Java also uses null, Swift uses nil, and Python uses None. However, in JavaScript, there is also a symbol undefined, which means “undefined”.

The JavaScript designer wants to use null to represent an empty value, while undefined means that the value is undefined. The difference between the two is of little significance. In most cases, we should use null. undefined is only useful if you want to determine whether a function argument has been passed.

Array

An array is a set of ordered collection, each of which is called an element. Arrays are represented by [], separated by ,. In JavaScript, an array can include any data type. E.g:

[1, 2, 3.14, 'Hello', null, true];

The above array contains 6 elements.

Another way to create an array is through the Array() function:

new Array(1, 2, 3); // created array [1, 2, 3]

However, for code readability considerations, it is highly recommended to use [] directly.

To access elements of an array, you can use index. Note that the starting value of the index is 0:

var arr = [1, 2, 3.14, 'Hello', null, true];
arr[0]; // return the element with index 0, i.e., 1
arr[5]; // returns an element with an index of 5, which is true
arr[6]; // index is out of range, return undefined

Object

A JavaScript object is a set of unordered collection of key-values, such as:

var person = {
    name: 'Bob',
    age: 20,
    tags: ['js', 'Web', 'mobile'],
    city: 'Beijing',
    hasCar: true,
    zipcode: null
};

The keys of a JavaScript object are all string types, and the value can be of any data type. The above person object defines a total of six key-value pairs, each of which is also called the object’s attribute. For example, the person’s name attribute has value 'Bob' and the zipcode attribute has value null.

To get the value of an attribute from an object, we use the . operator.

person.name; // 'Bob'
person.zipcode; // null

Variable

The concept of variables is basically the same as the equation variables of junior high algebra. But in computer programs, variables can be not only numbers, but also arbitrary data types.

A variable is represented by a variable name, which is a combination of uppercase and lowercase English characters, numbers, $, and _, and cannot begin with a number. Variable names can’t be JavaScript keywords, such as if, while, and so on. Declare a variable with a var statement, such as:

var a; // declare the variable a, the value of a is undefined
var $b = 1; // declare the variable $b and assign a value to $b.
// The value of $b is 1.
var s_007 = '007'; // s_007 is a string
var Answer = true; // Answer is a boolean true
var t = null; // the value of t is null

In JavaScript, use the equal sign = to assign a value to a variable. You can assign any data type to a variable. The same variable can be assigned repeatedly, and it can be a different type of variable, but be careful to declare it once with var, for example:

var a = 123; // the value of a is an integer 123
a = 'ABC'; // a becomes a string

Dynamic Language vs Static Language

A language in which the type of a variable is not fixed is called a dynamic language. In contrast, there exist static languages, e.g., C++. Static languages ​​must specify the variable type when defining a variable. If the type does not match to that being assigned, an error will be reported.

For example, Java is a static language, and the assignment statement is as follows:

int a = 123;
// a is an integer type variable, the type is declared with int
a = "ABC";
// Error: Cannot assign a string to an integer variable

This is the reason why dynamic languages ​​are more flexible than static languages.

Please do not consider the equal sign of the assignment statement as the mathematical equal sign. For example, the following code:

var x = 10;
x = x + 2;

If you understand x = x + 2 mathematically, it doesn’t work anyway. In the program, the assignment statement first evaluates the expression x + 2 on the right, and gets the result 12 and assigns it to the variable x. The value x is declared as 10, and it becomes 12 after reassignment.

Exercise 4

Display the content of a variable. Open the Chrome console and use the console.log(x) to print the variable.

var x = 100;
console.log(x);

The advantage of using console.log() instead of alert() is to avoid popping up annoying dialogs.

Strict mode

At the beginning of the design of JavaScript, in order to facilitate beginners to learn, it is not mandatory to declare variables with var. This design error has serious consequences: if a variable is not declared by a var declaration, the variable is automatically declared as a global variable:

i = 10; // i is now a global variable

In different JavaScript files on the same Web page, if you do not use var declaration, and use the variable i directly, this can result in erroneous results that are difficult to debug. That’s because the variable i is in the global scope.

A variable declared with var is not a global variable, its scope is limited to the body of the variable to be declared, and the variable of the same name does not conflict with each other in different functions (the concept of the function will be explained later).

In order to fix the serious design flaw of JavaScript, ECMA introduced the strict mode in the subsequent specification. The JavaScript code running in strict mode forces the variable to be declared by var. If the variable is not declared by var, it will cause a running error.

The way to enable strict mode is to write on the first line of the JavaScript code:

'use strict';

This is a string. Browsers that don’t support strict mode will treat it as a string statement. Browsers that support strict mode will open strict mode to run JavaScript.

To test if your browser supports strict mode:

'use strict';
abc = 'Hello, world';
console.log(abc);

Run the code, if the browser reports an error, please fix it before running. If the browser does not report an error, your browser is too old. You better to upgrade it as soon as possible.

NOTE: Variables that are not declared byvar are treated as global variables. To avoid this drawback, all JavaScript code should use strict mode.

The JavaScript code that we write in the JavaScript Definitive Guide Serial will all be in strict mode.

String

JavaScript strings are represented by characters enclosed in '' or "".

If ' is also a character, you can use "" to enclose it. For example, "I'm OK" contains characters of 6 characters: I, ', m, space, O, and K.

Also, you can write:

'A famous quote of Hamlet is "To be, or not to be--that is the question.".';

What if the string contains both ' and "? It can be identified by the escape character \, for example:

'I\'m \"OK\"!';

The content of the string represented is: I'm "OK"!

The escape character \ can escape many characters, such as \n for newline, \t for tab. And the character \ itself is \\.

ASCII characters can be expressed in hexadecimal form in the form \x##, for example:

'\x41'; // This is exactly the same as 'A'.

You can also use \u#### to represent a Unicode character:

'\u03B1\u03B4'; // This is exactly the same as 'αδ'.

Multi-Line String

Multi-line strings are harder to write with \n. The latest ES6 standard adds a representation of multi-line strings, represented by backquotes ``:

`This is a
multi-line
string`;

Note: The backquote is below the ESC of the keyboard, to the left of the number key 1:

Best JavaScript Definitive Guide for Beginners 2019 - Quick Start 2

Exercise 4

Test if your browser supports the ES6 standard. If not, please re-display the multi-line string with \n:

console.log(`multiple lines
string
test`);

Template String

To connect multiple strings, you can connect them with the + sign:

var name = 'John';
var age = 20;
var message = 'Hello, ' + name + '. You are ' + age + ' old!';
alert(message);

If there are many variables that need to be connected, it is troublesome to use the + symbol. ES6 has a new template string that represents the multi-line string using the same method as above. But it automatically replaces the variables in the string:

var name = 'John';
var age = 20;
var message = `Hello, ${name}. You are ${age} old!`;
alert(message);

Exercise 5

Test if your browser supports ES6 template strings. If not, change the template string to + connected ordinary string:

'use strict';
var name = 'John';
var age = 20;
var message = `Hello, ${name}. You are ${age} old!`;
console.log(message);

Manipulating Strings

The common operations of strings are as follows. Get the length of a string:

var s = 'Hello, world!';
s.length; // 13

To get a character at a specified position in a string, use an Array-like subscript operation with the index number starting at 0:

var s = 'Hello, world!';

s[0]; // 'H'
s[6]; // ' '
s[7]; // 'w'
s[12]; // '!'
s[13]; // This returns undefined.
// Indexes that are out of range will not report an error, but will always return undefined.

It’s important to note that strings are immutable. If you assign a value through the index, there won’t be any errors, but it has no effect:

var s = 'Test';
s[0] = 'X';
alert(s); // s is still 'Test'

JavaScript provides some common methods for strings. Calling these methods does not change the content of the original string. They only return a new string.

toUpperCase

toUpperCase() changes all strings to uppercase:

var s = 'Hello';
s.toUpperCase(); // return 'HELLO'

toLowerCase

toLowerCase() changes all strings to lowercase:

var s = 'Hello';
var lower = s.toLowerCase(); // return 'hello' and assign it to the variable lower
lower; // 'hello'

indexOf

indexOf() will search for the position where the specified string appears:

var s = 'hello, world';
s.indexOf('world'); // return 7
s.indexOf('World'); // did not find the specified substring, return -1

substring

substring() returns the substring of the specified index interval:

var s = 'hello, world'
s.substring(0, 5); // From index 0 to 5 (not including 5), return 'hello'
s.substring(7); // From index 7 to the end, return 'world'

Array

An Array of JavaScript can contain any type of data and access each element through index.

To get the length of an Array, go directly to the length property:

var arr = [1, 2, 3.14, 'Hello', null, true];
arr.length; // 6

Note that assigning a new value directly to the length of the Array will result in a change in the size of the Array:

var arr = [1, 2, 3];
arr.length; // 3
arr.length = 6;
arr; // arr becomes [1, 2, 3, undefined, undefined, undefined]
arr.length = 2;
arr; // arr becomes [1, 2]

You can modify the corresponding element to a new value through the index. Therefore, assigning an element to an Array directly modifies the Array:

var arr = ['A', 'B', 'C'];
arr[1] = 99;
arr; // arr now becomes ['A', 99, 'C']

Note that if the index is out of the range when assigning an element through the index, it will also cause the Array size to change:

var arr = [1, 2, 3];
arr[5] = 'x';
arr; // arr becomes [1, 2, 3, undefined, undefined, 'x']

Most other programming languages do not allow you to directly change the size of an array. An out-of-bounds access index error will be reported. However, JavaScript array does not report such a error.

It is not recommended to directly modify the size of the Array. When accessing an element, make sure that the index does not cross the boundary.

indexOf

Similar to String, Array can also search for the position of a specified element via indexOf():

var arr = [10, 20, '30', 'xyz'];
arr.indexOf(10); // The index of element 10 is 0
arr.indexOf(20); // The index of element 20 is 1
arr.indexOf(30); // Element 30 not found, returns -1
arr.indexOf('30'); // The index of the element '30' is 2

Note that the number 30 and the string '30' are different elements.

slice

slice() is the substring() version of String, which intercepts some of the elements of an Array and returns a new Array:

var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
arr.slice(0, 3); // Starts at index 0 and ends at index 3, but does not include index 3: ['A', 'B', 'C']
arr.slice(3); // From index 3 to the end: ['D', 'E', 'F', 'G']

Note that the function slice() includes the start index and does not include the end index.

If you don’t pass any arguments to slice(), it will intercept all elements from start to finish. With this, we can easily copy an Array:

var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
var aCopy = arr.slice();
aCopy; // ['A', 'B', 'C', 'D', 'E', 'F', 'G']
aCopy === arr; // false

push and pop

push() adds several elements to the end of the Array, and pop() removes the last element of the Array:

var arr = [1, 2];
arr.push('A', 'B'); // Returns the new length of the Array: 4
arr; // [1, 2, 'A', 'B']
arr.pop(); // pop() returns 'B'
arr; // [1, 2, 'A']
arr.pop(); arr.pop(); arr.pop(); // 3 consecutive pops
arr; // []
arr.pop(); // pop an empty array will not report an error, but returns undefined
arr; // []

unshift and shift

If you want to add a few elements to the head of the Array, use the unshift() method, and the shift() method removes the first element of the Array:

var arr = [1, 2];
arr.unshift('A', 'B'); // Returns the new length of the Array: 4
arr; // ['A', 'B', 1, 2]
arr.shift(); // 'A'
arr; // ['B', 1, 2]
arr.shift();
arr.shift();
arr.shift();
// 3 consecutive shifts
arr; // []
arr.shift(); // empty array continues shift will not report an error, but returns undefined
arr; // []

sort

sort() can sort an Array. It will directly modify the position of the elements of the current Array. Sorted in the default order:

var arr = ['B', 'C', 'A'];
arr.sort();
arr; // ['A', 'B', 'C']

Can we specify the order of the sort? That’s okay. We’ll talk about it later.

reverse

reverse() reverses the elements of the entire Array:

var arr = ['one', 'two', 'three'];
arr.reverse();
arr; // ['three', 'two', 'one']

splice

The splice() method is a “universal method” that modifies an Array. It can remove several elements from the specified index and then add several elements from that location:

var arr = ['Microsoft', 'Apple', 'Yahoo', 'AOL', 'Excite', 'Oracle'];
// Remove 3 elements starting with index 2, then add two more elements:
arr.splice(2, 3, 'Google', 'Facebook'); // Return the deleted element ['Yahoo', 'AOL', 'Excite']
arr; // ['Microsoft', 'Apple', 'Google', 'Facebook', 'Oracle']
// only delete, do not add:
arr.splice(2, 2); // ['Google', 'Facebook']
arr; // ['Microsoft', 'Apple', 'Oracle']
// only add, don't delete:
arr.splice(2, 0, 'Google', 'Facebook'); // return [] because no elements have been deleted
arr; // ['Microsoft', 'Apple', 'Google', 'Facebook', 'Oracle']

concat

The concat() method concatenates the current Array with another Array and returns a new Array:

var arr = ['A', 'B', 'C'];
var added = arr.concat([1, 2, 3]);
added; // ['A', 'B', 'C', 1, 2, 3]
arr; // ['A', 'B', 'C']

NOTICE: The concat() method does not modify the current Array, but instead returns a new Array.

In fact, the concat() method can accept any number of elements and Arrays. It automatically unpack arrays and then add all elements to the new Array:

var arr = ['A', 'B', 'C'];
arr.concat(1, 2, [3, 4]); // ['A', 'B', 'C', 1, 2, 3, 4]

join

The join() method is a very useful method. It concatenates each element of the current Array with the specified string and returns the concatenated string:

var arr = ['A', 'B', 'C', 1, 2, 3];
arr.join('-'); // 'A-B-C-1-2-3'

If the element of the Array is not a string, it will be automatically converted to a string and then concatenated.

Multidimensional Arrays

If an element of an array is an Array, you can form a multidimensional array, for example:

var arr = [[1, 2, 3], [400, 500, 600], '-'];

The above Array contains 3 elements, of which the first two elements are themselves Array.

Exercise 6

Get the value 500 by index:

'use strict';
var arr = [[1, 2, 3], [400, 500, 600], '-'];

Closing Words

Congratulations! You have make great progress so far! Now you know how to run JavaScript codes, how to declare a variable, and how to use strings and arrays.

But I should tell you the truth that this is just the beginning. You must continue to learn and practice. Following in-depth articles can help you become a JavaScript expert:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *