Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Learning JavaScript Data Structures and Algorithms
Learning JavaScript Data Structures and Algorithms

Learning JavaScript Data Structures and Algorithms: JavaScript Data Structures and algorithms can help you solve complex development problems – learn how by exploring a huge range of JavaScript data types

Arrow left icon
Profile Icon Loiane Avancini
Arrow right icon
£16.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (24 Ratings)
Paperback Oct 2014 218 pages 1st Edition
eBook
£20.98 £29.99
Paperback
£36.99
Subscription
Free Trial
Renews at £16.99p/m
Arrow left icon
Profile Icon Loiane Avancini
Arrow right icon
£16.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (24 Ratings)
Paperback Oct 2014 218 pages 1st Edition
eBook
£20.98 £29.99
Paperback
£36.99
Subscription
Free Trial
Renews at £16.99p/m
eBook
£20.98 £29.99
Paperback
£36.99
Subscription
Free Trial
Renews at £16.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. £16.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Learning JavaScript Data Structures and Algorithms

Chapter 1. JavaScript – A Quick Overview

JavaScript is a very powerful language. It is the most popular language 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 is in JavaScript; refer to http://goo.gl/ZFx6mg). The number of projects in JavaScript in 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 as well, and Node.js is the technology responsible for this. The number of Node Packages Modules (https://www.npmjs.org/) also grows exponentially.

JavaScript is a must-have on your résumé if you are or going to become a web developer.

In this book, you are going to learn about the most used data structures and algorithms. But why use JavaScript to learn about data structures and algorithms? We have already answered this question. JavaScript is very popular, and JavaScript is appropriate to learn 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 (and easier) than learning about data structures with a standard language such as C or Java. 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 because data structures and algorithms can solve the most common problems efficiently. This will make a difference on 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 can have some performance issues). Secondly, algorithms are studied in college together with introductory concepts of Computer Science. And thirdly, if you are planning to get a job in the greatest IT (Information Technology) companies (such as Google, Amazon, Ebay, and so on), data structures and algorithms are subjects of interview questions.

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 Google Chrome or Firefox installed (you can use the one you like the most), an editor of your preference (such as Sublime Text), and a web server (XAMPP or any other of your preference—but this step is optional). Chrome, Firefox, Sublime Text, and XAMPP are available for Windows, Linux, and Mac OS.

If you use Firefox, it is also recommended to install the Firebug add-on (https://getfirebug.com/).

We are going to present you with three options to set up your environment.

The browser is enough

The simplest environment that you can use is a browser.

You can use Firefox + Firebug. When you have Firebug installed, you will see the following icon in the upper-right corner:

The browser is enough

When you open Firebug (simply click on its icon), you will see the Console tab and you will be able to write all your JavaScript code on its command-line area as demonstrated in the following screenshot (to execute the source code you need to click on the Run button):

The browser is enough

You can also expand the command line to fit the entire available area of the Firebug add-on.

You can also use Google Chrome. Chrome already comes with Google Developer Tools. To open it, locate the setting and control icon and navigate to Tools | Developer Tools, as shown in the following screenshot:

The browser is enough

Then, in the Console tab, you can write your own JavaScript code for testing, as follows:

The browser is enough

Using web servers (XAMPP)

The second environment you might want to install on your computer is also simple, but a little bit more complex than just using a browser.

You will need to install XAMPP (https://www.apachefriends.org) or any web server of your preference. Then, inside the XAMPP installation folder, you will find the htdocs directory. You can create a new folder where you can execute the source code we will implement in this book, or you can download the source code from this book and extract it to the htdocs directory, as follows:

Using web servers (XAMPP)

Then, you can access the source code from your browser using your localhost URL (after starting the XAMPP server) as shown in the following screenshot (do not forget to enable Firebug or Google Developer Tools to see the output):

Using web servers (XAMPP)

Tip

When executing the examples, always remember to have Google Developer Tools or Firebug open to see the output.

It's all about JavaScript (Node.js)

The third option is having an environment that is 100 percent JavaScript! Instead of using XAMPP, which is an Apache server, we can use a JavaScript server.

To do so, we need to have Node.js installed. Go to http://nodejs.org/ and download and install Node.js. After that, open the terminal application (if you are using Windows, open the command prompt with Node.js that 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:

It's all about JavaScript (Node.js)

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

It's all about JavaScript (Node.js)

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

For this book, the code files can be downloaded from this GitHub repository: https://github.com/loiane/javascript-datastructures-algorithms.

JavaScript basics

Before we start diving into 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 see the two different ways we can use JavaScript code in an HTML page:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    <script>
        alert('Hello, World!');
    </script>
</body>
</html>

The first way is demonstrated by the previous code. We need to create an HTML file and write this code on it. In this example, we are declaring the script tag inside the HTML file, and inside the script tag, we have the JavaScript code.

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 like this:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</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 best practice.

Note

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 needed. Values that are assigned to a variable belong to a type. In JavaScript, the available types are numbers, strings, Booleans, functions, and objects. We also have undefined and null, along with arrays, dates, and regular expressions. 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 name = 'Packt'; //{4}
var trueValue = true; //{5}
var nullVar = null; //{6}
var und;  //7

On 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 are declaring a new variable.

On line {2}, we are updating an existing variable. JavaScript is not a strongly-typed language. This means you can declare a variable and initialize it with a number, and then update it with a string or any other data type. Assigning a value to a variable that is different from its original type is also not a good practice.

On line {3}, we are also declaring a number, but this time it is a decimal floating point. On line {4}, we are declaring a string; on line {5}, we are declaring a Boolean. On line {6}, we are declaring a null value, and on line {7}, we are declaring an undefined variable. A null value means no value and undefined means a variable that has been declared but not yet assigned a value:

console.log("num: "+ num);
console.log("name: "+ name);
console.log("trueValue: "+ trueValue);
console.log("price: "+ price);
console.log("nullVar: "+ nullVar);
console.log("und: "+ und);

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

Note

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 will output an alert window on the browser; the second one is console.log('My text here'), which will output text on the Console tab of the debug tool (Google Developer Tools or Firebug, depending on the browser you are using). Finally, the third way is outputting the value directly on the HTML page that is being rendered by the browser by using document.write('My text here'). You can use the option that you feel most comfortable with.

The console.log method also accepts more than just arguments. Instead of console.log("num: "+ num), we can also use console.log("num: ", num).

We will discuss functions and objects later in this chapter.

Variable scope

Scope refers to where in the algorithm we can access the variable (it can also be a function when we are working 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}

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 be inside myFunction only.

Line {3} will output global because we are referencing the global variable named myOtherVariable that was initialized in the second line of the example. Line {4} will output local. Inside the myOtherFunction function, we are referencing the myOtherVariable global variable and assigning 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 them:

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

On 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

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

On 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 (value and object type both)

!=

Not equal to

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

And on 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, 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 more detailed descriptions 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

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 suchas "Packt" has the value true, for example.

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 see 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); //false (age does not exist)

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 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 presented here:

Value type

Result

undefined

NaN.

null

+0.

Boolean

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

Number

The value of the number.

String

This parses the string into a number. If the string consists of alphabetical characters, the result is NaN; if the string consists of numbers, it is transformed into a number.

Object

toNumber(toPrimitive(value)).

And toPrimitive is presented here:

Value type

Result

Object

If valueOf returns a primitive value, this returns the primitive value; otherwise, if toString returns a primitive value, this returns the primitive value; 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 see:

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

The output is false! Let's understand why:

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

And what about the following code? Let's see:

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

The output is also false! The following are the steps:

  1. First, it converts the Boolean value using toNumber, so we have packt == 0.
  2. Then, it converts the string value using toNumber. As the string consists of alphabetical characters, it returns NaN, so we have NaN == 0, which is false.

And what about the operator ===? It 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 see 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 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 script only if the condition is true:

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 script if the condition is true or another script just in case the condition is false (else):

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

And if we have several scripts, we can use if…else several times to execute different scripts based on different conditions:

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 usage of 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). And 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 very often used when we work with arrays (which is the subject of the next chapter). Specifically, we will be using the for loop in our algorithms.

The for loop is exactly 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 then 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 while 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 script 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 outputted 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 very similar to the while loop. The only difference is that in the while loop, the condition is evaluated before executing the script, and in the do…while loop, the condition is evaluated after the script is executed. The do…while loop ensures that the script is executed at least once. The following code also outputs the values 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 a lot 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 call this code, we simply use the following call:

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

Object-oriented programming

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 object entirely as follows:

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

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 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 attributes and update them as follows:

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

A class can also contain functions. We can declare and use a function 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();

Note

In the prototype example, the printTitle function is going to be shared between all instances, and only one copy is going to be created. When we use 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 in regards to 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. You will notice in the examples of this book that we use a class-based definition (because we want to keep some properties and functions private). But, whenever possible, we should use the prototype method.

Now we have covered all the basic JavaScript concepts that are needed for us to start having some fun with data structures and algorithms!

Debugging and tools

Knowing how to program with JavaScript is important, but so is knowing how to debug your code. Debugging is very useful to help find bugs in your code, but it can also help you execute your code at a lower speed so 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).

Both Firefox 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. But there are other great tools that can help you be more productive when working with JavaScript as well:

  • Aptana: This is a free and open source IDE that supports JavaScript, CSS3, and HTML5, among other languages (http://www.aptana.com/).
  • 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/.

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 constructing the algorithms and data structures covered in this book.

In the next chapter, we will look at our first data structure, which is array, the most basic data structure that many languages support natively, including JavaScript.

Left arrow icon Right arrow icon
Download code icon Download Code

Description

If you are a JavaScript developer or someone who has basic knowledge of JavaScript, and want to explore its optimum ability, this fast-paced book is definitely for you. Programming logic is the only thing you need to know to start having fun with algorithms.

What you will learn

  • Declare, initialize, add, and remove items from arrays, stacks, and queues
  • Create and use the most complex data structure, graphs, along with DFS and BFS algorithms
  • Grasp the power of linked lists, doubly linked lists, and circular linked lists
  • Store unique elements with hash tables, dictionaries, and sets
  • Explore the applications of binary trees and binary search trees
  • Sort data structures using bubble sort, selection sort, insertion sort, merge sort, and quick sort
  • Search elements in data structures using sequential sort and binary search
  • Understand the importance of big O notation, dynamic programming, and greedy algorithms

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 27, 2014
Length: 218 pages
Edition : 1st
Language : English
ISBN-13 : 9781783554874
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. £16.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Oct 27, 2014
Length: 218 pages
Edition : 1st
Language : English
ISBN-13 : 9781783554874
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.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
£169.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
£234.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 £ 115.97
Object-Oriented JavaScript - Second Edition
£41.99
Mastering JavaScript Design Patterns
£36.99
Learning JavaScript Data Structures and Algorithms
£36.99
Total £ 115.97 Stars icon

Table of Contents

11 Chapters
1. JavaScript – A Quick Overview Chevron down icon Chevron up icon
2. Arrays Chevron down icon Chevron up icon
3. Stacks Chevron down icon Chevron up icon
4. Queues Chevron down icon Chevron up icon
5. Linked Lists Chevron down icon Chevron up icon
6. Sets Chevron down icon Chevron up icon
7. Dictionaries and Hashes Chevron down icon Chevron up icon
8. Trees Chevron down icon Chevron up icon
9. Graphs Chevron down icon Chevron up icon
10. Sorting and Searching Algorithms Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(24 Ratings)
5 star 62.5%
4 star 25%
3 star 4.2%
2 star 0%
1 star 8.3%
Filter icon Filter
Top Reviews

Filter reviews by




IntegralBill May 20, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is one of my favorite algorithm texts. It gets straight to the point providing you with examples of how the data structure or algorithm can be used and application of the algorithm in JavaScript. If you are studying algorithms in school, you're probably using the Cormen text or possibly Sedgewick's or Kleinberg's. Definitely recommend using this as a supplement for those texts.If you're not taking an algorithm class and want to see how to implement common data structures and algorithms in JavaScript, or you're looking to brush-up for a job interview, or you have some JavaScript background and want to improve your skills, definitely pick this up! The price is great as well.
Amazon Verified review Amazon
Josh Goldberg Dec 02, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book's title undersells it a little. The first chapter is a solid, concise introduction to using the language, and is followed by a series of chapters that each bring the reader into a better understanding of how to use both JavaScript and programming concepts in general. I see this book as a good companion for teaching Computer Science II level material in JavaScript. The examples are straightforward and logical, as are the explanations. It's hard to find fault with the book's approach to teaching because there's so little chaff to complain about. It simply teaches you what you need to know, which I found very refreshing.Overall, while the book isn't positioned as the be-all and end-all of understanding the JavaScript language, it is an overall excellent introduction to the language and implementing data structures in it.
Amazon Verified review Amazon
Brent Farwick Feb 22, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I gave this 5 stars in spite of the considerable errata. The author does an excellent job of explaining the fundamentals of data structures and algorithms. If you're going to get a degree in CS, go ahead and pass on this book, but if like me, you discovered your love of computers too late in life, this is your ticket to penetrating some of the mystery surrounding terms like linked lists, hashes, binary trees and their traversals, queues, stacks, graphs, search algos, and sorting. I really wish there were more books like this. You can leave your math books on the shelf, the explanations and programs in this book are conceptual and explanatory. Lots of fun code to type in an play with -- of course you can just download all the code and copy paste, but there's a lot to be said for slowing down and typing it in -- as Donald Knuth said, "Information sinks into the brain at about the same rate it always has," or words to that effect. Some of the programs will make your head hurt. The author, Loiane Groner, can teach... not every writer can.
Amazon Verified review Amazon
Sam chao Jun 04, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I got the item on time and it was the one I wanted.
Amazon Verified review Amazon
Silvia Jul 01, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Clear and concise material, good for a beginner (with some knowledge) to get up to speed with the subject.
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 included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.