Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Learning JavaScript Data  Structures and Algorithms
Learning JavaScript Data  Structures and Algorithms

Learning JavaScript Data Structures and Algorithms: Write complex and powerful JavaScript code using the latest ECMAScript , Third Edition

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Learning JavaScript Data Structures and Algorithms

JavaScript – A Quick Overview

JavaScript is a very powerful language. It is one of the most popular languages in the world and is one of the most prominent languages on the internet. For example, GitHub (the world's largest code host, available at https://github.com) hosts over 400,000 JavaScript repositories (the largest number of projects available is in JavaScript; refer to http://githut.info). The number of projects in JavaScript and GitHub grows every year.

JavaScript is not a language that can only be used in the frontend. It can also be used in the backend, and Node.js is the technology responsible for this. The number of Node Package Modules (npm), https://www.npmjs.org, has also grown exponentially. JavaScript can also be used for mobile development and is one of the most popular frameworks in Apache Cordova (https://cordova.apache.org), which is a mobile hybrid framework that allows developers to code using HTML, CSS, and JavaScript, which allows you to build an app and generate an APK file for Android and IPA file for iOS (Apple). And of course, let's not forget about desktop applications. We can write desktop applications compatible with Linux, Mac OS, and Windows using a JavaScript framework called Electron (https://electron.atom.io). JavaScript is also used in embedded and Internet of Things (IoT) devices. As you can see, JavaScript is everywhere!

JavaScript is a must-have on your resume if you are or are becoming a web developer.

In this chapter, you will learn the syntax and some necessary basic functionalities of JavaScript so that we can start developing our own data structures and algorithms. We will cover:

  • Setting up the environment and JavaScript basics
  • Controlling structures and functions
  • Object-oriented programming in JavaScript
  • Debugging and tools

JavaScript data structure and algorithms

In this book, you will learn about the most-used data structures and algorithms. Why should we use JavaScript to learn about data structures and algorithms? We have already answered this question. JavaScript is very popular and is appropriate for learning about data structures because it is a functional language. Also, this can be a very fun way of learning something new, as it is very different from (and easier than) learning about data structures with a standard language such as C, Java, or Python. And who said data structures and algorithms were only made for languages such as C and Java? You might need to implement some of these languages while developing for the frontend as well.

Learning about data structures and algorithms is very important. The first reason is that data structures and algorithms can solve the most common problems efficiently. This will make a difference to the quality of the source code you write in the future (including performance; if you choose the incorrect data structure or algorithm, depending on the scenario, you may have some performance issues). Secondly, algorithms are studied in college together with the introductory concepts of computer science. And finally, if you are planning on getting a job with one of the greatest Information Technology (IT) companies (such as Google, Amazon, Microsoft, eBay, and so on) data structures, and algorithms are the subjects of interview questions.

Let's get started!

Setting up the environment

One of the pros of the JavaScript language compared to other languages is that you do not need to install or configure a complicated environment to get started with it. Every computer has the required environment already, even though the user may never write a single line of source code. All we need is a browser!

To execute the examples in this book, it is recommended that you have a modern browser installed such as Google Chrome or Firefox (you can use the one you like the most), an editor of your preference (such as Visual Studio Code), and a web server (XAMPP or any other of your preference, but this step is optional). Chrome, Firefox, VS Code, and XAMPP are available for Windows, Linux, and Mac OS.

The minimum setup to work with JavaScript

The simplest environment that you can use for JavaScript development is a browser. The modern browsers (Chrome, Firefox, Safari, and Edge) have a functionality called Developer Tools. To access the DevTools in Chrome, you can click on the menu in the upper-right corner, More Tools | Developer Tools:

When you open the DevTools, you will see the Console tab, and you will be able to write all your JavaScript code in its command-line area, as demonstrated in the following screenshot (to execute the source code, you need to press Enter):

Using web servers

The second environment option you might want to install on your computer is also simple, but it requires installing a web server. If an HTML file contains only simple JavaScript code that does not require any request to a server (Ajax calls), it can be executed in the browser by right-clicking on the HTML file and selecting the Open with option. The code we will develop throughout this book is simple and it can be executed using this approach. However, it is always nice to have a web server installed.

There are many open source and free options available to you. If you are familiar with PHP, XAMPP (https://www.apachefriends.org) is a good option, and it is available for Linux, Windows, and Mac OS.

Since we will be focusing on JavaScript for the server side and the browser, there is also a simpler web server you can install in Chrome. It is the Web Server for Chrome extension, and this can be downloaded at https://goo.gl/pxqLmU. After installing it, you can access it through the Chrome URL chrome://apps:

After opening the Web Server extension, you can CHOOSE FOLDER you want to serve in the browser. You can create a new folder in which you can execute the source code we will implement throughout this book, or you can download the source code from this book and extract it to a directory of your preference and access it through the informed URL (the default is http://127.0.0.1:8887):

All examples from this book can be executed by accessing http://127.0.0.1:8887/examples. You will find an index.html with a list of all examples, as demonstrated in the following screenshot:

When executing the examples, always remember to have the Developer Tools enabled and the Console tab open to see the output. The Web Server for Chrome extension was also developed using JavaScript. For better experience, it is recommended to use this extension to execute the examples from this book or install the Node.js http-server we will learn in the next section.

Node.js http-server

The third option is having an environment that is 100 percent JavaScript! For this environment, we need to have Node.js installed. Go to http://nodejs.org, and download and install Node.js. After installing it, open the Terminal application (if you are using Windows, open the Command Prompt with Node.js, which was installed with Node.js) and run the following command:

    npm install http-server -g

Make sure you type the command and don't copy and paste it. Copying the command might give you some errors. You can also execute the command as an administrator. For Linux and Mac systems, use the following command:

    sudo npm install http-server -g

This command will install http-server, which is a JavaScript server. To start a server and run the examples from this book in the Terminal application, change the directory to the folder that contains the book's source code and type http-server, as displayed in the following screenshot:

To execute the examples, open the browser and access the localhost on the port specified by the http-server command.

Detailed steps to download the code bundle and run the examples are mentioned in the preface of this book. Please have a look. The code bundle for the book is also hosted on GitHub at https://github.com/loiane/javascript-datastructures-algorithms. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing. Check them out!

JavaScript basics

Before we start diving in to the various data structures and algorithms, let's have a quick overview of the JavaScript language. This section will present the JavaScript basics required to implement the algorithms we will create in the subsequent chapters.

To start, let's look at the two different ways we can use JavaScript code on an HTML page. The first example is demonstrated by the following code. We need to create an HTML file (01-HelloWorld.html) and write this code in it. In this example, we are declaring the script tag inside the HTML file and, inside the script tag, we have the JavaScript code:

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF-8"> 
  </head> 
  <body> 
    <script> 
      alert('Hello, World!'); 
    </script> 
  </body> 
</html> 
Try using the Web Server for Chrome extension or the http-server to run the preceding code and see its output in the browser.

For the second example, we need to create a JavaScript file (we can save it as 01- HelloWorld.js) and, inside this file, we will insert the following code:

alert('Hello, World!'); 

Then, our HTML file will look similar to this:

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="UTF-8"> 
    <title></title> 
  </head> 
  <body> 
    <script src="01-HelloWorld.js"></script> 
  </body> 
</html> 

The second example demonstrates how to include a JavaScript file inside an HTML file.

By executing any of these two examples, the output will be the same. However, the second example is the most used by JavaScript developers.

You may find JavaScript include statements or JavaScript code inside the head tag in some examples on the internet. As a best practice, we will include any JavaScript code at the end of the body tag. This way, the HTML will be parsed by the browser and displayed before the scripts are loaded. This boosts the performance of the page.

Variables

Variables store data that can be set, updated, and retrieved whenever necessary. Values that are assigned to a variable belong to a type. In JavaScript, the available types are number, string, boolean, function, and object. We also have undefined and null, along with arrays, dates, and regular expressions.

Although JavaScript has different available variable types, it is not a strongly typed language such as C/C++, C#, and Java. In strongly typed languages, we need to declare the type of the variable along with its declaration (for example, in Java, to declare an integer variable, we use int num = 1;). In JavaScript, we only need to use the keyword var, and we do not need to declare the variable type. For this reason, JavaScript is not a strongly typed language. However, there are discussions and a specification in draft mode for optional static typing (https://github.com/dslomov/typed-objects-es7) that can become part of the JavaScript specification (ECMAScript) in the future. We can also use TypeScript in case we want to type our variables when working with JavaScript. We will learn more about ECMAScript and TypeScript later in this chapter.

The following is an example of how to use variables in JavaScript:

var num = 1; // {1} 
num = 3; // {2} 
var price = 1.5; // {3} 
var myName = 'Packt'; // {4} 
var trueValue = true; // {5} 
var nullVar = null; // {6} 
var und; // {7}
  • In line {1}, we have an example of how to declare a variable in JavaScript (we are declaring a number). Although it is not necessary to use the var keyword declaration, it is a good practice to always specify when we declare a new variable.
  • In line {2}, we updated an existing variable. JavaScript is not a strongly typed language. This means you can declare a variable, initialize it with a number, and then update it with a string or any other datatype. Assigning a value to a variable that is different from its original type is also not a good practice.
  • In line {3}, we also declared a number, but this time it is a decimal floating point. In line {4}, we declared a string; in line {5}, we declared a boolean. In line {6}, we declared a null value, and in line {7}, we declared an undefined variable. A null value means no value, and undefined means a variable that has been declared but not yet assigned a value.

If we want to see the value of each variable we declared, we can use console.log to do so, as listed in the following code snippet:

console.log('num: ' + num); 
console.log('myName: ' + myName); 
console.log('trueValue: ' + trueValue); 
console.log('price: ' + price); 
console.log('nullVar: ' + nullVar); 
console.log('und: ' + und); 

The console.log method also accepts more than just arguments. Instead of console.log('num: ' + num), we can also use console.log('num: ', num). While the first option is going to concatenate the result into a single string, the second option allows us to add a description and also visualize the variable content in case it is an object.

We have three ways of outputting values in JavaScript that we can use with the examples of this book. The first one is alert('My text here'), which outputs an alert window on the browser, and the second one is console.log('My text here'), which outputs text on the Console tab of the debug tool (Google Developer Tools or Firebug, depending on the browser you are using). The third way is outputting the value directly on the HTML page that is rendered by the browser using document.write('My text here'). You can use the option that you feel most comfortable with.

We will discuss functions and objects later in this chapter.

Scope variable

The scope refers to where in the algorithm we can access the variable (it can also be a function when we work with function scopes). There are local and global variables.

Let's look at an example:

var myVariable = 'global'; 
myOtherVariable = 'global'; 
 
function myFunction() { 
  var myVariable = 'local'; 
  return myVariable; 
} 
 
function myOtherFunction() { 
  myOtherVariable = 'local'; 
  return myOtherVariable; 
} 
 
console.log(myVariable); //{1} 
console.log(myFunction()); //{2} 
 
console.log(myOtherVariable); //{3} 
console.log(myOtherFunction()); //{4} 
console.log(myOtherVariable); //{5} 

The above code can be explained as follows:

  • Line {1} will output global because we are referring to a global variable.
  • Line {2} will output local because we declared the myVariable variable inside the myFunction function as a local variable, so the scope will only be inside myFunction.
  • Line {3} will output global because we are referencing the global variable named myOtherVariable that was initialized on the second line of the example.
  • Line {4} will output local. Inside the myOtherFunction function, we referenced the myOtherVariable global variable and assigned the value local to it because we are not declaring the variable using the var keyword.
  • For this reason, line {5} will output local (because we changed the value of the variable inside myOtherFunction).

You may hear that global variables in JavaScript are evil, and this is true. Usually, the quality of JavaScript source code is measured by the number of global variables and functions (a large number is bad). So, whenever possible, try avoiding global variables.

Operators

We need operators when performing any operation in a programming language. JavaScript also has arithmetic, assignment, comparison, logical, bitwise, and unary operators, among others. Let's take a look at these:

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)); 

In line {1}, we have the arithmetic operators. In the following table, we have the operators and their descriptions:

Arithmetic operator

Description

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus (remainder of a division operation)

++

Increment

--

Decrement

 

In line {2}, we have the assignment operators. In the following table, we have the operators and their descriptions:

Assignment operator

Description

=

Assignment

+=

Addition assignment (x += y) == (x = x + y)

-=

Subtraction assignment (x -= y) == (x = x - y)

*=

Multiplication assignment (x *= y) == (x = x * y)

/=

Division assignment (x /= y) == (x = x / y)

%=

Remainder assignment (x %= y) == (x = x % y)

 

In line {3}, we have the comparison operators. In the following table, we have the operators and their descriptions:

Comparison operator

Description

==

Equal to

===

Equal to (both value and object type)

!=

Not equal to

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

 

Finally, in line {4}, we have the logical operators. In the following table, we have the operators and their descriptions:

Logical operator

Description

&&

And

||

Or

!

Not

 

JavaScript also supports bitwise operators, which are shown 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)); 

The following table contains a more detailed description of the bitwise operators:

Bitwise operator

Description

&

And

|

Or

~

Not

^

Xor

<<

Left shift

>>

Right shift

 

The typeof operator returns the type of the variable or expression. For example, have 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'}); 

The output will be as follows:

    typeof num: number
    typeof Packt: string
    typeof true: boolean
    typeof [1,2,3]: object
    typeof {name:John}: object
 

According to the specification, there are two data types in JavaScript:

  • Primitive data types: Null, undefined, string, number, boolean, and symbol
  • Derived data types/objects: JavaScript objects, including functions, arrays, and regular expressions 

JavaScript also supports the delete operator, which deletes a property from an object:

var myObj = {name: 'John', age: 21}; 
delete myObj.age; 
console.log(myObj); //outputs Object {name: "John"} 

In this book's algorithms, we will be using some of these operators.

Truthy and falsy

In JavaScript, true and false are a little bit tricky. In most languages, the boolean values true and false represent the true/false results. In JavaScript, a string such as Packt evaluates to true.

The following table can help us better understand how true and false work in JavaScript:

Value Type

Result

undefined

false

null

false

Boolean

true is true and false is false

Number

The result is false for +0, -0, or NaN; otherwise, the result is true

String

The result is false if the string is empty (length is 0); otherwise, the result is

true (length >= 1)

Object

true

Let's consider some examples and verify their output:

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 is always true) 
 
testTruthy(1); // true 
testTruthy(-1); // true 
testTruthy(NaN); // false 
testTruthy(new Number(NaN)); // true (object is always true) 
 
testTruthy({}); // true (object is always true) 
 
var obj = { name: 'John' }; 
testTruthy(obj); // true 
testTruthy(obj.name); // true 
testTruthy(obj.age); // age (property does not exist) 

Functions of the equals operators (== and ===)

The two equals operators supported by JavaScript can cause a little bit of confusion when working with them.

When using ==, values can be considered equal even when they are of different types. This can be confusing even for a senior JavaScript developer. Let's analyze how == works using the following table:

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, then JavaScript will use the equals method to compare the two values or objects. Any other combination that is not listed in the table gives a false result.

The toNumber and toPrimitive methods are internal and evaluate the values according to the tables that follow.

The toNumber method is as follows:

Value type

Result

undefined

This is NaN

null

This is +0

Boolean

If the value is true, the result is 1; if the value is false, the result is +0

Number

This is the value of the number

 

Finally, toPrimitive is as follows:

Value Type

Result

Object

If valueOf returns a primitive value, it returns the primitive value; otherwise, if toString returns a primitive value, it returns the primitive value and otherwise returns an error

 

Let's verify the results of some examples. First, we know that the output of the following code is true (string length > 1):

console.log('packt' ? true : false); 

Now, what about the following code? Let's take a look:

console.log('packt' == true); 

The output is false, so let's understand why:

  • First, it converts the boolean value using toNumber, so we have packt == 1.
  • Then, it converts the string value using toNumber. Since the string consists of alphabetical characters, it returns NaN, so we have NaN == 1, which is false.

What about the following code? Let's take a look:

console.log('packt' == false); 

The output is also false, and the following is why:

  • First, it converts the boolean value using toNumber, so we have packt == 0.
  • Then, it converts the string value using toNumber. Since the string consists of alphabetical characters, it returns NaN, so we have NaN == 0, which is false.

What about the === operator? This is much easier. If we are comparing two values of different types, the result is always false. If they have the same type, they are compared according to the following table:

Type(x)

Values

Result

Number

x has the same value as y (but not NaN)

true

String

x and y are identical characters

true

Boolean

x and y are both true or both false

true

Object

x and y reference the same object

true

 

If x and y are different types, then the result is false. Let's consider some examples:

console.log('packt' === true); //false  
console.log('packt' === 'packt'); //true 
var person1 = {name:'John'};  
var person2 = {name:'John'}; 
console.log(person1 === person2); //false, different objects 

Control structures

JavaScript has a similar set of control structures as the C and Java languages. Conditional statements are supported by if...else and switch. Loops are supported by the while, do...while, and for constructs.

Conditional statements

The first conditional statement we will take a look at is the if...else construct. There are a few ways we can use the if...else construct.

We can use the if statement if we want to execute a block of code only if the condition (expression) is true, as follows:

var num = 1; 
if (num === 1) { 
  console.log('num is equal to 1'); 
} 

We can use the if...else statement if we want to execute a block of code and the condition is true or another block of code just in case the condition is false (else), as follows:

var num = 0; 
if (num === 1) { 
  console.log('num is equal to 1'); 
} else { 
  console.log('num is not equal to 1, the value of num is ' + num); 
} 

The if...else statement can also be represented by a ternary operator. For example, take a look at the following if...else statement:

if (num === 1) { 
  num--; 
} else { 
  num++; 
} 

It can also be represented as follows:

(num === 1) ? num-- : num++; 

Also, if we have several expressions, we can use if...else several times to execute different blocks of code based on different conditions, as follows:

var month = 5; 
if (month === 1) { 
  console.log('January'); 
} else if (month === 2) { 
  console.log('February'); 
} else if (month === 3) { 
  console.log('March'); 
} else { 
  console.log('Month is not January, February or March'); 
} 

Finally, we have the switch statement. If the condition we are evaluating is the same as the previous one (however, it is being compared to different values), we can use the switch statement:

var month = 5; 
switch (month) { 
  case 1: 
    console.log('January'); 
    break; 
  case 2: 
    console.log('February'); 
    break; 
  case 3: 
    console.log('March'); 
    break; 
  default: 
    console.log('Month is not January, February or March'); 
} 

One thing that is very important in a switch statement is the use of the case and break keywords. The case clause determines whether the value of switch is equal to the value of the case clause. The break statement stops the switch statement from executing the rest of the statement (otherwise, it will execute all the scripts from all case clauses below the matched case until a break statement is found in one of the case clauses). Finally, we have the default statement, which is executed by default if none of the case statements are true (or if the executed case statement does not have the break statement).

Loops

Loops are often used when we work with arrays (which are the subject of the next chapter). Specifically, we use the for loop in our algorithms.

The for loop is the same as in C and Java. It consists of a loop counter that is usually assigned a numeric value, then the variable is compared against another value (the script inside the for loop is executed while this condition is true), and finally, the numeric value is increased or decreased.

In the following example, we have a for loop. It outputs the value of i on the console, where i is less than 10; i is initiated with 0, so the following code will output the values 0 to 9:

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

The next loop construct we will look at is the while loop. The block of code inside the while loop is executed while the condition is true. In the following code, we have a variable, i, initiated with the value 0, and we want the value of i to be output while i is less than 10 (or less than or equal to 9). The output will be the values from 0 to 9:

var i = 0; 
while (i < 10) { 
  console.log(i); 
  i++; 
} 

The do...while loop is similar to the while loop. The only difference is that in the while loop, the condition is evaluated before executing the block of code, and in the do...while loop, the condition is evaluated after the block of code is executed. The do...while loop ensures that the block of code is executed at least once. The following code also outputs the values from 0 to 9:

var i = 0; 
do { 
  console.log(i); 
  i++; 
} while (i < 10); 

Functions

Functions are very important when working with JavaScript. We will also use functions in our examples.

The following code demonstrates the basic syntax of a function. It does not have arguments or the return statement:

function sayHello() { 
  console.log('Hello!'); 
} 

To execute this code, we simply use the following statement:

sayHello(); 

We can also pass arguments to a function. Arguments are variables with which a function is supposed to do something. The following code demonstrates how to use arguments with functions:

function output(text) { 
  console.log(text); 
} 

To use this function, we can use the following code:

output('Hello!'); 

You can use as many arguments as you like, as follows:

output('Hello!', 'Other text'); 

In this case, only the first argument is used by the function, and the second one is ignored. A function can also return a value, as follows:

function sum(num1, num2) { 
  return num1 + num2; 
} 

This function calculates the sum of two given numbers and returns its result. We can use it as follows:

var result = sum(1, 2); 
output(result); // outputs 3 

Object-oriented programming in JavaScript

JavaScript objects are very simple collections of name-value pairs. There are two ways of creating a simple object in JavaScript. The first way is as follows:

var obj = new Object(); 

And the second way is as follows:

var obj = {}; 

We can also create an entire object, as follows:

obj = { 
  name: { 
    first: 'Gandalf', 
    last: 'the Grey' 
  }, 
  address: 'Middle Earth' 
}; 

As we can see, to declare a JavaScript object, [key, value] pairs are used, where the key can be considered an attribute of the object and the value is the property value. All classes that we will create in this book are JavaScript objects, such as Stack, Set, LinkedList, Dictionary, Tree, Graph, and so on.

In Object-oriented programming (OOP), an object is an instance of a class. A class defines the characteristics of the object. For our algorithms and data structures, we will create some classes that will represent them. This is how we can declare a class (constructor) that represents a book:

function Book(title, pages, isbn) { 
  this.title = title; 
  this.pages = pages; 
  this.isbn = isbn; 
} 

To instantiate this class, we can use the following code:

var book = new Book('title', 'pag', 'isbn'); 

Then, we can access its properties and update them as follows:

console.log(book.title); // outputs the book title 
book.title = 'new title'; // update the value of the book title 
console.log(book.title); // outputs the updated value 

A class can also contain functions (generally also referred to as methods). We can declare and use a function/method as the following code demonstrates:

Book.prototype.printTitle = function() { 
  console.log(this.title); 
}; 
 
book.printTitle(); 

We can declare functions directly inside the class definition as well:

function Book(title, pages, isbn) { 
  this.title = title; 
  this.pages = pages; 
  this.isbn = isbn; 
  this.printIsbn = function() { 
    console.log(this.isbn); 
  }; 
} 
book.printIsbn(); 
In the prototype example, the printTitle function will be shared between all the instances and only one copy will be created. When we use a class-based definition, as in the previous example, each instance will have its own copy of the functions. Using the prototype method saves memory and processing cost regarding assigning the functions to the instance. However, you can only declare public functions and properties using the prototype method. With a class-based definition, you can declare private functions and properties, and the other methods inside the class can also access them. ECMAScript 2015 (ES6) introduces a simplified syntax like the class-based example and it is prototype-based. We will discuss more on this later in this chapter.

Debugging and tools

Knowing how to program with JavaScript is important, but so is knowing how to debug your code. Debugging is very useful in helping you find bugs in your code, but it can also help you execute your code at a lower speed so that you can see everything that is happening (the stack of methods called, variable assignment, and so on). It is highly recommended that you spend some time debugging the source code of this book to see every step of the algorithm (it might help you understand it better as well).

Firefox, Safari, Edge, and Chrome support debugging. A great tutorial from Google that shows you how to use Google Developer Tools to debug JavaScript can be found at https://developer.chrome.com/devtools/docs/javascript-debugging.

You can use any text editor of your preference. However, there are other great tools that can help you be more productive when working with JavaScript as well, which are listed as follows:

  • WebStorm: This is a very powerful JavaScript IDE with support for the latest web technologies and frameworks. It is a paid IDE, but you can download a 30- day trial version (http://www.jetbrains.com/webstorm).
  • Sublime Text: This is a lightweight text editor and you can customize it by installing plugins. You can buy the license to support the development team, but you can also use it for free (the trial version does not expire) at http://www.sublimetext.com.
  • Atom: This is also a free text editor created by GitHub. It has great support for JavaScript and it can also be customized by installing plugins (https://atom.io).
  • Visual Studio Code: This is a free and open source code editor created by Microsoft, written with TypeScript. It has JavaScript autocomplete functionality with IntelliSense and provides built-in debug capability directly from the editor. It can also be customized by installing plugins (https://code.visualstudio.com).

All of the aforementioned editors are available for Windows, Linux, and Mac OS.

Debugging with VSCode

To debug JavaScript or ECMAScript code directly from VSCode, first, we need to install the Debugger for Chrome extension (https://goo.gl/QpXWGM).

Next, open the Web Server for Chrome extension and open the link to see the book examples in the browser (the default URL is http://127.0.0.1:8887/examples).

The following screenshot demonstrates how to debug directly from the editor:

  1. In the editor, open the JavaScript file you want to debug, pass the mouse pointer near the line numbers, and click on the line to add a breakpoint (as demonstrated by 1 in the preceding screenshot). This is where the debugger will stop so we can analyze the code.
  2. Once the Web Server is up and running, click on the Debug view (2), select Chrome (3), and click on the Play icon to initiate the debugging process.
  3. Chrome will be opened automatically. Navigate to the desired example to evoke the code we want to debug. Once the line we added the breakpoint to is reached by the debugger, the process will stop and the editor will receive the focus.
  4. We can control how the code is debugged using the top toolbar (4). We can resume the process, go to a method call, go to the next line, and restart and stop the process. It is the same behavior we have in the debugger in Chrome and other browsers.
  5. The advantage of using this built-in debug functionality is that we can do everything from the editor (coding, debugging, and testing). And we also have the variables declared and call stack, we can watch variables and expressions (5), hover the mouse over a variable to see its current value (6), and see the console output as well (7).

The source code of this book was developed using Visual Studio Code and the code bundle also contains configured launch tasks so you can debug the code and the tests directly from the VSCode (all details are in the .vscode/launch.json file). All extensions recommended to run the source code from this book are also listed in the .vscode/extensions.json file.

Summary

In this chapter, we learned how to set up the development environment to be able to create or execute the examples in this book.

We also covered the basics of the JavaScript language that are needed prior to getting started with developing the algorithms and data structures covered in this book.

In the next chapter, we will learn about new functionalities introduced to JavaScript since 2015 and also how to leverage static typing and error checking using TypeScript.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Implement common data structures and the associated algorithms along with the context in which they are used
  • Master existing JavaScript data structures such as arrays, sets, and maps, and learn how to implement new ones such as stacks, linked lists, trees, and graphs in ES 8
  • Develop abstract data types to make JavaScript a more flexible and powerful programming language

Description

A data structure is a particular way of organizing data in a computer to utilize resources efficiently. Data structures and algorithms are the base of every solution to any programming problem. With this book, you will learn to write complex and powerful code using the latest ES 2017 features. Learning JavaScript Data Structures and Algorithms begins by covering the basics of JavaScript and introduces you to ECMAScript 2017, before gradually moving on to the most important data structures such as arrays, queues, stacks, and linked lists. You will gain in-depth knowledge of how hash tables and set data structures function as well as how trees and hash maps can be used to search files in an HD or represent a database. This book serves as a route to take you deeper into JavaScript. You’ll also get a greater understanding of why and how graphs, one of the most complex data structures, are largely used in GPS navigation systems in social networks. Toward the end of the book, you’ll discover how all the theories presented in this book can be applied to solve real-world problems while working on your own computer networks and Facebook searches.

Who is this book for?

If you’re a JavaScript developer who wants to dive deep into JavaScript and write complex programs using JavaScript data structures and algorithms, this book is for you.

What you will learn

  • • Declare, initialize, add, and remove items from arrays, stacks, and queues
  • • Create and use linked lists, doubly linked lists, and circular linked lists
  • • Store unique elements with hash tables, dictionaries, and sets
  • • Explore the use of binary trees and binary search trees
  • • Sort data structures using algorithms such as bubble sort, selection sort, insertion sort, merge sort, and quick sort
  • • Search elements in data structures using sequential sort and binary search
Estimated delivery fee Deliver to Latvia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 30, 2018
Length: 426 pages
Edition : 3rd
Language : English
ISBN-13 : 9781788623872
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Latvia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Apr 30, 2018
Length: 426 pages
Edition : 3rd
Language : English
ISBN-13 : 9781788623872
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 110.97
Learning JavaScript Data  Structures and Algorithms
€36.99
Mastering JavaScript Functional Programming
€36.99
Hands-On Data Structures and Algorithms with JavaScript
€36.99
Total 110.97 Stars icon
Banner background image

Table of Contents

16 Chapters
JavaScript – A Quick Overview Chevron down icon Chevron up icon
ECMAScript and TypeScript Overview Chevron down icon Chevron up icon
Arrays Chevron down icon Chevron up icon
Stacks Chevron down icon Chevron up icon
Queues and Deques Chevron down icon Chevron up icon
Linked Lists Chevron down icon Chevron up icon
Sets Chevron down icon Chevron up icon
Dictionaries and Hashes Chevron down icon Chevron up icon
Recursion Chevron down icon Chevron up icon
Trees Chevron down icon Chevron up icon
Binary Heap and Heap Sort Chevron down icon Chevron up icon
Graphs Chevron down icon Chevron up icon
Sorting and Searching Algorithms Chevron down icon Chevron up icon
Algorithm Designs and Techniques Chevron down icon Chevron up icon
Algorithm Complexity Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.1
(9 Ratings)
5 star 44.4%
4 star 0%
3 star 11.1%
2 star 11.1%
1 star 33.3%
Filter icon Filter
Top Reviews

Filter reviews by




Kindle Customer Feb 05, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
First I was scared of previews reviews but then I quickly used book.google to find get some content of the book.In my experience , the best resources out there to learn Algorithm and Data Structures . You'll need to start from references online and then practice with this book.Thanks once again for this wonderful book
Amazon Verified review Amazon
webdeveloperpr Jul 20, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I purchased this book after failing horribly at a software developer interview. I have been a developer for 4 years but as a self taught developer I lacked some of the CS fundamentals. This book has taught me a lot about how to solve many CS problems by using data structures. I have not finished the book yet but I already feel pretty confident with the new things I have learned.
Amazon Verified review Amazon
Amazon Customer May 22, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
what is new in this version? I noticed the modules section about es6 modules in node. And a full chapter on es6 and ECMAScript
Amazon Verified review Amazon
Joaquim Pagian Barboza Apr 27, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Livro maravilhoso da Loiane sobre estrutura de dados em JavaScript; melhor explicação até então sobre o assunto.
Amazon Verified review Amazon
DEEPIKA CHITIKELA Apr 24, 2019
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
too many references to the code written elsewhere. It becomes tiresome to go go back and remind yourself. Many errors in the code.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela