Chapter 1 takes a quick look at JavaScript
Learning JavaScript Data Structures and Algorithm
By Loiane Groner
JavaScript is a powerful language. It is one of the most popular and cutting-edge programming languages in the world. For example, there are over 400,000 JavaScript repositories on gitHub. And JavaScript projects are growing every year.
JavaScript can be used not only in the front-end domain, but also in the back-end domain (node.js is for the back-end). The use of NPM is also growing rapidly.
If you want to become a web developer, JavaScript is a must-have item on your resume.
In this book, you will learn the most common data structures and algorithms. But why implement data structures and algorithms in JavaScript? Well, we’ve already answered that question. JavaScript is a popular language and a programmatic language worth learning. It’s also fun to learn new things, and it’s easier to implement data structures and algorithms in JavaScript than in standard programming languages like C and Java.
Learning about data structures and algorithms is very final. First of all, data structure and algorithm can solve the problem of field view more effectively. This will make the code you write better. Second, data structures and algorithms are required courses for computer science majors in universities. Third, if you want to get a job in a large IT company, data structures and algorithms are also one of the interview topics.
Set up the environment
The advantage of JavaScript over other languages is that you don’t have to install and configure an environment. Every computer already has a JavaScript environment, even though many computer users have never written a line of source code. All we need is a browser!
The book recommends using Google Chrome or Firefox (whichever you prefer), an editor of your choice (such as Sublime Text), and a web server (XAMPP or whatever – this step is optional).
If you’re using Firefox, use firefox with Firebug (getFirebug.com).
Now, let’s set up the environment.
One browser
The simplest environment we can use is a browser.
You can use Firefox +Firbug. When you install Firebug, you’ll see this icon in the upper right corner:
When you open Firebug, you see the Console panel and can write code from the command line:
You can also resize Firebug.
You can also use Google Chrome. Google Chrome already has developer tools installed. To open it, follow the image below:
After that, you can write JavaScript code in the Console panel:
Using a Web Server (XAMPP)
The second environment to install is also simple, but a little more complex than the browser.
You will need to install XAMPP, or some other server. After that, in the XAMPP folder, you will find the htdocs directory. You can place the book code in a folder here, or download the source code here, as follows:
Later, you can use the local URL (after starting the XAMPP server) to access your source code, as shown in the screenshot below:
When Tip executes code, it’s important to open Google Developer Tools or Firebug to see the results.
That’s all JavaScript is (Node.js)
The third environment to install is Node.js. Unlike XAMPP, which is an Apache server, Node.js is a JavaScript server.
To do this, we will install Node.js. You can download and install Node.js at nodejs.org. After that, open the terminal and run the following code:
npm install http-server -g
Copy the code
For Linux and Mac systems, you can use the following code:
sudo npm install http-server -g
Copy the code
This line of code installs the JavaScript HTTP server. If you want to start the server, run the sample code, convert the folder to a folder with source code in the terminal, and type HTTP-server in the terminal, as shown below:
Then, open your browser and enter the terminal number specified by http-server in the address box.
JavaScript based
Before we dive into data structures and algorithms, let’s take a quick look at the features of the JavaScript language. This chapter covers the language features of JavaScript in more detail.
We can run JavaScript code in HTML pages in different ways:
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <script> alert('Hello World ! '); </script> </body> </html>Copy the code
The first way to run JavaScript code is to declare aScrip tag in an HTML file and write the JavaScript code there.
The second method is to generate a JavaScript file and type the following code inside the file:
alert('Hello World ! ');Copy the code
After that, our code looks like this:
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <script src="01-HelloWorld.js"> </script> </body> </html>Copy the code
The second method is used to reference JavaScript code within HTML.
The results are the same for both methods. The second, however, is to compare recommended best practices.
variable
Variables are used to store data, change data, and get data. In JavaScript, the data types available are numbers, Strings, Booleans, functions, and Objects. Also, Arrays *, dates, and regular expression. The following is an example of using variables in JavaScript:
var num =1; //{1}
num = 3; //{2}
var price = 1.5; //{3}
var name = Packt; //{4}
var trueValue = true; //{5}
var nullValue = null; //{6}
var und; //{7}
Copy the code
In line {1}, we declare a variable in JavaScript. Although you can do without the var keyword, it is a good code practice to use it when declaring variables.
In line {2}, we update the value of the variable. JavaScript is not a strongly typed language. This means that we can declare a variable, assign a value to it, and update its value to a string or other type. Of course, converting a variable to a value of another type is not recommended.
In line {3}, we also declare a number, but this time we declare a decimal. In line {4}, we declare a string; In line {5}, we declare a Boolean value. In line {6}, we declare a NULL. In line {7}, we declare a value of undefined. Null means that the value of this variable is null; Undefined means that the variable is declared but not yet assigned:
console.log("num: " + num );
console.log("name: " + name );
console.log("trueValue: " + trueValue );
console.log("price: " + price );
console.log("nullVar: " + nullVar );
console.log("und: " + und );
Copy the code
After that, you can view the output of this code on the console.
Variable scope
Line {1} prints global because we are accessing the global variable. Line {2} will print local, because we declared a local variable inside myFunction, so its scope is only inside myFunction.
Line {3} prints global because we are accessing a global variable named myOtherVarible. Line {4} prints local. Inside the myOtherFunction function, since the var keyword is not used, we access the global variable myOtherVaribale and point to its value as local. Therefore, line {5} prints local (because we changed the value of myOtherVariable inside myOtherFunction).
You’ve probably heard that global variables are evil in JavaScript. Yes, global variables are not recommended in general practice.
The operator
When programming, we need operators to perform certain operations. JavaScript provides arithmetic operators, assignment operators, comparison operators, logical operators, bitwise operators, and unary operators. Let me look at these operators:
var num = 0; // {1} num = num + 2; num = num * 3; num = num / 2; num++; num--; num += 1; // {2} num -= 2; num *= 3; num /= 2; num %= 3; console.log('num == 1: ' + (num ==1)); // {3} console.log('num === 1: ' + (num ===1)); console.log('num ! = 1: ' + (num ! = 1)); console.log('num > 1: ' + (num > 1)); console.log('num < 1: ' + (num < 1)); console.log('num >= 1: ' + (num >= 1)); console.log('num <= 1: ' + (num <= 1)); console.log('true && false : ' + (true && false)); // {4} console.log('true || false : ' + (true || false)); console.log('! true : ' + (! true));Copy the code
Line {1} shows the arithmetic operator. Here is an illustration of the arithmetic operator:
Arithmetic operator | function |
---|---|
+ | add |
– | subtraction |
* | The multiplication |
/ | division |
& | modulo |
++ | Gal. |
— | Minus one |
Line {2} shows the assignment operator. The following is an illustration of the assignment operator:
The assignment operator | function |
---|---|
= | The assignment |
+ = | Add the assignment |
– = | Subtraction assignment |
* = | Multiplication assignment |
/ = | Divide the assignment |
% = | Remainder assignment |
Line {3} shows the comparison operator. The following is an illustration of the comparison operator:
Comparison operator | function |
---|---|
= = | Is equal to the |
= = = | Strictly equal to the |
! = | Is not equal to |
> | Is greater than |
> = | Greater than or equal to |
< | Less than |
< = | Less than or equal to |
Line {4} shows the logical operators. The following is an illustration of the logical operators:
Logical operator | function |
---|---|
&& | and |
|| | or |
! | non |
JavaScript also supports bitwise operators, as follows:
console.log('5 & 1:', (5 & 1));
console.log('5 | 1:', (5 | 1));
console.log('~5:', (~5));
console.log('5 ^ 1:', (5 ^ 1));
console.log('5 << 1:', (5 << 1));
console.log('5 >> 1:', (5 >> 1));
Copy the code
The following is an illustration of bitwise operators:
An operator | function |
---|---|
& | and |
| | or |
~ | non |
^ | Exclusive or |
<< | Shift to the left |
>> | Moves to the right |
The typeof operator is used to return a variable’s type. Take a look at the following code:
console.log('typeof num: ', typeof num ); console.log('typeof Packt: ', typeof 'Packt'); console.log('typeof true: ', typeof true); Console. log('typeof [1,2,3]: ', typeof [1,2,3]); console.log('typeof {name:'John'}: ', typeof {name:'John'});Copy the code
The code output looks like this:
Typeof num: number typeof Packt: string typeof true: Boolean typeof [1,2,3]: Boolean typeof {name:'John'}: objectCopy the code
JavaScript also provides the delete operator. Delete deletes the properties of an object:
var myObj = { name:'John', age: 21 }; delete myObj.age; console.log(myObj); Object {name:'John'}Copy the code
We will use some of these operators throughout this book
True and false values
In JavaScript, the question of true and false is a little more complicated. In most languages, Boolean types represent true and false. In JavaScript, strings like ‘Packt ‘can also represent truth.
The following diagram helps us understand JavaScript truth and falsehood better:
Value types | The results of |
---|---|
undefined | false |
null | false |
Boolean | True is true, false is false |
Number | False if the number is +0, -0, or NaN; All others are true |
String | False if the string is empty (length 0); True if the character is not empty |
Object | true |
Let’s look at some examples and check the values:
function testTruthy(val){ return val ? console.log('truthy') : console.log('falsy'); } testTruthy(true); // true testTruthy(false); // false testTruthy(new Boolean(false)); // true (object is always true) testTruthy(" "); // false testTruthy('Packt'); // true testTruthy(new String('')); // true (object always true) testTruthy(1); // true testTruthy(-1); // true testTruthy(NaN); // false testTruthy(new Number(Nan)); // true (object is always true) testTruthy({}); // true (the object is always true) var obj = {name: 'John'}; testTruthy(obj); // true testTruthy(obj.name); // true testTruthy(obj.age); // false (because age does not exist)Copy the code
Equality operators (== and ===)
The two equality operators can cause some confusion when used.
When using ==, two values can be treated as equal even if the variables are of different types. Let’s examine the == operator as follows:
Type(x) | Type(y) | result |
---|---|---|
null | undefined | true |
undefined | null | true |
Number | String | x == toNumber(y) |
String | Number | toNumber(x) == y |
Boolean | Any | toNumber(x) == y |
Any | Boolean | x == toNumber(y) |
String or Number | Object | x == toPrimitive(y) |
Object | String or Number | toPrimitive(x) == y |
If x and y are of the same type, JavaScript uses the equal method to compare two values or objects. Type combinations that do not appear in this table return false.
The following is the output table of the toNumber method:
Value types | The results of |
---|---|
undefined | NaN. |
null | + 0. |
Boolean | If true, the result is 1; If the value is false, the result is +0. |
Number | Returns the number itself. |
String | It parses the string into a number. If the string is alphanumeric, the result is NaN; If the string is composed of numbers, the result is a number. |
Object | ToNumber (toPrimitive (value)). |
The following is the toPrimitive method:
Value types | The results of |
---|---|
Object | If valueOf returns the original value, toPrimitive returns the original value. If toString returns the original value, toPrimitive returns the original value; Otherwise, error is returned |
Let’s verify this with some examples. We know that if the string length is greater than 1, its truth value is true:
console.log('packt' ? true: false );
Copy the code
So what is the result of the following code?
console.log('packt' == true );
Copy the code
The result of this code is wrong! Let’s understand why:
1. First, the Boolean value is converted to 1. 2 by the toNumber method. After that, the string is converted by the toNumber method. Because the string is composed of letters, it is converted to NaN. So NaN == 1, which is false.
Take a look at this code:
console.log('packt' == false );
Copy the code
The output is also false. 1. First, the Boolean value is converted to 0.2 by the toNumber method. After that, the string is converted by the toNumber method. Because the string is composed of letters, it is converted to NaN. So NaN == 0, which is false.
What about using the ‘===’ operator? That would be a lot easier. If we compare two values with ‘===’, the result must be false. If two values are of the same type, they are compared according to the following rules:
Type(x) | value | The results of |
---|---|---|
Number | X and y have the same value (except NaN) | true |
String | X and y have the same string | true |
Boolean | X and y have the same Boolean value | true |
Object | X and y refer to the same object | true |
If x and y are of different types, the return value is false.
Let’s look at some examples:
console.log('packt' === true); // false conosle.log('packt' === 'packt'); // true var person1 = {name:'John'}; var person2 = {name:'John'}; console.log(person1 === person2); //false because they are two different objectsCopy the code
Control structure
JavaScript’s control structure is very similar to that of C and Java. Conditional predicates have if… Else and switch statements. Loops include while, do… While and for statements.
Conditional predicates
First, let’s look at the if… The else statement.
If we want the machine to execute a particular program when the condition is true, we can use the if statement
var num = 1;
if (num ===1 ){
console.log("num is equal to 1");
}
Copy the code
If we want to execute subroutine A if the condition is true and subroutine B if the condition is not, we can use if… Else statements:
var num =0;
if (num ===1 ){
console.log("num is equal to 1");
}else{
console.log("num is notequal to 1,the value of num is "+ num);
}
Copy the code
if… Else statements can be converted to ternary expressions:
if (num === 1){
num++;
}else{
num--;
}
Copy the code
Can be converted to:
(num === 1) ? num++: num--;
Copy the code
If the condition we want to judge is non-binary, we can use else if:
var month = 5 ;
if (month ===1 ){
console.log("January");
} else if (month === 2){
console.log("February");
} else if (month === 3){
console.log("March");
} else (month === 2){
console.log("Month is not January,February or March");
}
Copy the code
Finally, we can use the switch statement. Execute the previous code with the switch statement as follows:
var month = 5;
switch(month) {
case 1:
console.log("January");
break;
case 2:
console.log("February");
break;
case 3:
console.log("March");
break;
defalut:
console.log("Month is not January,February or March");
}
Copy the code
cycle
We’ll use loops a lot when dealing with arrays (which, of course, is the subject of the next chapter). In particular, we’re going to use the for loop a lot in our algorithm.
The for loop in JavaScript is the same as the for loop in C and Java. The for loop consists of a starting point, an end point, and a number of steps.
In the example below, we will use a for loop. When I is less than 10, it prints the value of I in the console; I is initialized to 0, so the following output is 0 to 9:
for (var i= 0; i< 10; i++){
console.log(i);
}
Copy the code
The next one is the while loop. As long as the condition of the while is true, the machine will execute the statement in the while. In the code below, we have an I initialized to 0, and then we print I when I is less than 10. Its output is 0 to 9.
var i = 0;
while( i < 10 ){
console.log(i);
i++;
}
Copy the code
But do… The while loop is very similar to the while loop. The only difference is that… The while loop executes the statement first, then judges the condition; A while loop evaluates and then executes the statement. do… A while loop ensures that the loop is executed at least once. The following is an output from 0 to 9 to do… The while loop:
var i = 0;
do {
console.log(i);
i++;
} while(i<10)
Copy the code
function
Functions are very important when using JavaScript. We will also use many functions later in the book and in examples.
The following code shows the function to basic syntax. This function has no arguments or return values:
function sayHello(){ console.log('Hello ! ');Copy the code
This function can be called with statements like this:
sayHello();
Copy the code
We can also pass parameters to functions. Parameters are the variables that a function uses to handle a particular task. The following code shows how to use arguments within a function:
function output(text){
console.log(text);
}
Copy the code
To call this function, use the following code:
output('Hello','Other text');
Copy the code
In this example, only the first parameter is used, and the second parameter is ignored.
The function can also return a value like this:
funciton sum(num1,num2){
return num1 + num2;
}
Copy the code
This function evaluates the sum of two arguments. Let’s test it out:
Var result = sum (1, 2); output(result);Copy the code
Object-oriented programming
JavaScript objects are a series of key-value pairs. There are two ways to generate JavaScript objects. The first method is as follows:
var obj = new Object();
Copy the code
The second method is as follows:
var obj = {};
Copy the code
We can also generate a complete object like this:
var obj = {
name:{
first:"Gandalf",
last:"the Grey"
},
address:"Middle Earth"
};
Copy the code
In object-oriented programming, an object is an instance of a class. Class is responsible for defining the characteristics of an object. At that time, we will use classes to represent some data structure or algorithm. Here is our code for generating a class named book:
function Book(title,pages,isbn){ this.title = title; this.pages = pages; This. Isbn = isbn; }Copy the code
To instantiate this class, we can execute the following code:
var book = new Book('title','pag','isbn');
Copy the code
After that, we can capture and update its characteristics:
console.log(book.title); // Output title book.title = 'new title'; // Update its value to new title console.log(book.title); // Output is new titleCopy the code
A class can also have functions. We can declare and use functions as follows:
Book.prototype.printTitle = function(){
conosle.log(book.title);
}
book.printTitle();
Copy the code
We can also define functions inside a class:
function Book(title,pages,isbn){
this.title = title;
this.pages = pages;
this.isbn = isbn;
this.printIsbn = function(){
conosle.log(book.isbn);
}
}
book.printIsbn();
Copy the code
Note In the prototype example, all instances of the class will have the prinTitle method and a copy of that method will then be produced. In the internal class definition, as in the previous example, each instance of the class makes a copy of the function. Using the Prototype method to define methods saves space. However, the Prototype method can only be used to define public methods and public properties. Inside a class, you can define private properties and methods. You will find that many of the examples later in this book use methods defined within classes (because we want some properties and methods to be private properties, private methods). However, we should always use Prototype to define class methods.
Now, we’ve covered the basic concepts of JavaScript. With this knowledge, we can begin our wonderful journey of data structures and algorithms.
A tool for troubleshooting
Knowing how to troubleshoot code is just as important as knowing how to program in JavaScript. When troubleshooting, we can better find errors in the code, and we can make the code run slower to help us understand what’s happening inside the code (call stack usage, variable assignment, etc.).
Firefox and Chrome both provide troubleshooting tools. The following links are using Google Chrome for troubleshooting tutorial developer.chrome.com/devtools/do…
We can use any editor to write JavaScript programs. However, there are several editors that can make the development process more efficient:
- Aptana: Aptana is a free open source integrated development environment that supports programming languages such as JavaScript, CSS3, and HTML5.
- Webstorm: It is a very powerful JavaScript integrated development environment with the latest technologies and frameworks. This is a paid software, of course, you can download the 30-day trial of www.jetbrains.com/webstorm.
- Sublime Text: It is a lightweight editor that you can customize by installing various plug-ins. You can purchase a serial number to support the professional development team, but of course you can use the free version. www.sublimetext.com/.
summary
In this book, we set up an environment for JavaScript programming.
We also covered the basics used to implement data structures and algorithms.
In the next chapter, we’ll look at the first data structure, arrays. Arrays are the most basic data structures supported by most programming languages, including JavaScript.
Note: This article is translated from "Learning JavaScript Data Structures and Algorithm" by Loiane Groner.