 # Learn Data Structure and Algorithm in JavaScript | Part 06 Edison Pebojot(👨‍💻) Updated on ・11 min read

# Prerequisite (✋😐)

If you're reading this article right now, please considered to read our Part 01: Big-O Notation, Part 02: JavaScript Unique Part, Part 03: JavaScript Numbers, Part 04: JavaScript Strings and Part 05: JavaScript Array

01 Big-O Notation By the end of this chapter, you will understand how to analyze an implementation of an algorithm with respect to both time (execution time) and space (memory consumed).
02 JavaScript Unique Parts Big-O is important for analyzing and comparing the efficiencies of algorithms. The analysis of Big-O starts by looking at the code, and, applying the rules, applying the rules is because to simplify the Big-O notation linear or quadratic rule is not enough.
03 JavaScript Numbers This part 3 will focus on JavaScript number operations, number representation, Number objects, common number algorithms, and random number generation.
04 JavaScript Strings This part 4 will focus on strings, JavaScript String object, and the String object’s built-in functions. You will learn how to access, compare, decompose, and search strings for commonly used real-life purposes. In addition, the chapter will explore string encoding, decoding, encryption, and decryption.
05 JavaScript Arrays As a JavaScript developer, you will use the array often; it is the most commonly used data structure. Arrays in JavaScript come with a lot of built-in methods. By the end of this part, you will understand arrays and choose the right method
06 JavaScript Object This part will focus on what JavaScript objects are, how they are declared, and how their properties can be changed. In addition, this part will cover how JavaScript classes are implemented using prototypal inheritance. Also this part will be short.
07 JavaScript Memory Management A variable takes up some memory. In C, the programmer allocate and deallocate memory manually. In contrast, modern JavaScript engines have garbage collectors that delete unused variables. However, there are pitfalls(unexpected) that developers can fall into(❗) This part will show these unexpected and present techniques to help the garbage collector minimize the memory problems.
08 Recursion This part 8 introduces the concept of recursion and recursive algorithms(Remember they are different, we will discuss them later(😉)). We will also discuss the definition of recursion and fundamental rules for recursive algorithms.
09 Sets This part focuses on the concepts of sets from both a mathematical definition and on the implementation. Also, Common set operations, as well as their implementations, are covered in great detail (💡).
10 Searching and Sorting This part 10 focuses on searching and sorting for arrays. By the end of this part 10, you will understand how to use sorting and searching algorithms for arrays. Also, this article is a bit complicated for beginners, so as much as possible the visual aids is your friend (👀). (😃)
11 Hash Tables A hash table is a fixed-sized data structure in which the size is defined at the start. This part 11 explains how hash tables work, and the method of generating a unique key. By the end of this part 11, you will understand various hashing techniques and know how to implement a hash table. (😃)
12 Stacks and Queues This part 12 covers stacks and queues(pronounce as kyooz (🔈)) not (kwewe) okay? hehehe (😅); both are data structures used in the implementation of complex data structures. You'll learn what the stacks and queues are, how they're used, when they're used, and how to implement them (😃) Let's go! (🔥🔥🔥)
13 Linked Lists A linked list is a data structure in which each node (or element) points to another node. Unlike arrays, which have a fixed size, a linked list is a dynamic data structure. By the end of this part 13, you will understand how to implement and work with linked lists. And oh! (😮) There are two types of linked lists: singly (➡️) and doubly (↔️). Let’s examine the singly linked list first.(😃) Let's go! (🔥🔥🔥)
14 Caching Caching is the process of storing data into temporary memory so that it can be easily retrieved for later use if it is required again. As an example, a database keeps data cached to avoid re-reading the hard drive, and a web browser caches web images to avoid re-downloading. In this part 14, two caching techniques will discussed: LFU and LRU caching.
15 Trees A general tree data structure is composed of nodes with children nodes. The top node is called the root node. This part 15 will explore different types of trees such as binary trees, binary search trees, and self-balancing binary search trees. First, this part 15 will cover what trees are and how they are structured. Then, it will cover methods of traversing(crossing or taking a zigzag path) the tree data structure in detail. Finally, you will learn about binary search trees and self-balancing binary search trees to understand how to store searchable data. (😃)
16 Heaps A heap is an important data structure that returns the highest or lowest element in O(1) time. This part 16 will focus on explaining how heaps are implemented as well as how to work with them. One example is heap sort, which is a sorting algorithm based on heaps.
17 Graphs In this Part 17, you will learn graph basics, including fundamental terminology and graph types. The Part 17 will also cover working with these different graph types and methods of representing graphs in data structures. Finally, algorithms for traversing, searching, and sorting graphs are explored to solve problems such as finding the shortest path between two graph nodes. (👍)
18 Advance Strings Part 18 will cover more complex string algorithms than covered in the previous section. Now that you have heard of certain other data models or structures, they should be easier to comprehend. Specifically, Part 18 will focus on string searching algorithms. (😉)
19 Dynamic Programming Dynamic programming involves breaking down problems into their subproblems. Solving the subproblems and saving those results into memory to access them whenever a repeated problem needs to be solved, the algorithmic complexity decreases significantly (⬇️). To explain dynamic programming, let’s re examine the Fibonacci sequence that was discussed in Part 8. Then Part 19 will cover the rules of dynamic programming and walk you through some examples to make the concepts more concrete. (😉)
20 Bit Manipulation Bit manipulation is an advanced topic that JavaScript developers typically do not need to know. However, you should learn a bit about bit manipulation if you want to implement high-performance server-side code. Understanding bit manipulation requires some knowledge of digital logic. Any introductory course in discrete math or circuits would be helpful to understand these concepts.

# Part 06: JavaScript Object(😱 🔥 🎲) This part will focus on what JavaScript objects are, how they are declared, and how their properties can be changed. In addition, this part will cover how JavaScript classes are implemented using prototypal inheritance. Also this part will be short. (👍)

## JavaScript Object Property (🎲🎲) JavaScript objects can be created via the object literal {} or via the syntax new Object(). Additional properties can be added or accessed in one of two ways: object.propertyName or object[ 'propertyName' ]:

Example:

``````var javaScriptObject = {}; // Object Literal or via 'var javaScriptObject = New Object()'
var testArray = [1, 2, 3, 4];

console.log(javaScriptObject); // {array: [1,2,3,4]}

console.log(javaScriptObject); // {array: [1,2,3,4], title: 'Algorithms'}
``````

Execution:

``` ``` ``` var javaScriptObject = {}; // Object Literal or via 'var javaScriptObject = New Object()' var testArray = [1, 2, 3, 4]; javaScriptObject.array = testArray; // Added console.log(javaScriptObject); // {array: [1,2,3,4]} javaScriptObject['title'] = 'Algorithms'; // Added console.log(javaScriptObject); // {array: [1,2,3,4], title: 'Algorithms'} ```

The array and title property was added to the JavaScript object.

## Prototypal Inheritance (🐔↔️🐓) In JavaScript, the function is added as a property of class. Here is an example of a class in JavaScript using this.functionName = function(){}:

Example:

``````function ExampleClass() {
this.name = "JavaScript";
this.sayName = function () {
console.log(this.name);
}
}

// New Object
var example1 = new ExampleClass();
example1.sayName(); // Prints "JavaScript"
``````

Execution:

``` ``` ``` function ExampleClass() { this.name = "JavaScript"; this.sayName = function () { console.log(this.name); } } // New Object var example1 = new ExampleClass(); example1.sayName(); // Prints "JavaScript" ```

This adds the sayName function in the constructor(which is the ExampleClass). This pattern is known as prototypal inheritance (See more on Wikipedia): Inheritance (object-oriented programming)

In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object or class, retaining similar implementation. Also defined as deriving new classes from existing ones such as super class or base class and then forming them into a hierarchy of classes. In most class-based object-oriented languages, an object created through inheritance, a "child object", acquires all the properties and behaviors of the "parent object", with the exception of: constructors, destructor, overloaded operators and friend functions of the base class. Inheritance allows programmers to create classes that are built upon existing classes, to specify a new implementation while maintaining the same behaviors, to reuse code and to independently extend original software via public classes and interfaces. The relationships of objects or classes through inheritance give rise to a directed graph.

Prototypal inheritance is the only method of inheritance in JavaScript. To add functions of a class, simply use the .prototype property. (😃)

When you use the .prototype property, you are extending
the property of the object
. This isn’t possible for compiled languages. because they will throw an error on compilation (❗). This unique property of JavaScript lets developers take advantage of the prototypical inheritance. (😇) Here’s an example of using .prototype:

Example:

``````
function ExampleClass() {
this.array = [1, 2, 3, 4, 5];
this.name = "JavaScript";
}

// New object
var example1 = new ExampleClass();

// Adding sayName function using prototype
ExampleClass.prototype.sayName = function () {
console.log(this.name);
}

example1.sayName(); // Prints "JavaScript"

``````

Execution:

``` ``` ``` function ExampleClass() { this.array = [1, 2, 3, 4, 5]; this.name = "JavaScript"; } // New object var example1 = new ExampleClass(); // Adding sayName function using prototype ExampleClass.prototype.sayName = function () { console.log(this.name); } example1.sayName(); // Prints "JavaScript" ```

## Constructor and Variables (🔧🔜📦) Because variables of a class in JavaScript are properties of that class, any properties declared with this.propertyName will be available in public. This means that the object’s properties can be accessed in other scopes:

Example:

``````
function ExampleClass(name, size) {
this.name = name;
this.size = size;
}

var example = new ExampleClass("Public", 5);
console.log(example); // Prints '{name:"Public", size: 5}'

// Accessing public variables
console.log(example.name); // Prints "Public"
console.log(example.size); // Prints '5'

``````

Execution:

``` ``` ``` function ExampleClass(name, size) { this.name = name; this.size = size; } var example = new ExampleClass("Public", 5); console.log(example); // Prints '{name:"Public", size: 5}' // Accessing public variables console.log(example.name); // Prints "Public" console.log(example.size); // Prints '5' ```

To mimic a private variable, you can declare a local variable and have getter/setters(we will see that later (😉)) that allow access to that variable. This way, the variable is available only to the constructor’s scope:

Example:

``````
function ExampleClass(name, size) {
var privateName = name;
var privateSize = size;

this.getName = function () { return privateName; }
this.setName = function (name) { privateName = name; }

this.getSize = function () { return privateSize; }
this.setSize = function (size) { privateSize = size; }
}

var example = new ExampleClass("Edison", 3);
example.setSize(12);
console.log(example.privateName); // Prints 'undefined'
console.log(example.getName()); // Prints 'Edison'
console.log(example.size); // Prints 'undefined'
console.log(example.getSize()); // Prints '12' instead of '3', why?

``````

Execution:

``` ``` ``` function ExampleClass(name, size) { var privateName = name; var privateSize = size; this.getName = function () { return privateName; } this.setName = function (name) { privateName = name; } this.getSize = function () { return privateSize; } this.setSize = function (size) { privateSize = size; } } var example = new ExampleClass("Edison", 3); example.setSize(12); console.log(example.privateName); // Prints 'undefined' console.log(example.getName()); // Prints 'Edison' console.log(example.size); // Prints 'undefined' console.log(example.getSize()); // Prints '12' instead of '3', why? ```

# Summary (📚) In JavaScript, prototypical inheritance is the preferred method of inheritance. Prototypical inheritance works by adding new functions to a JavaScript class via .prototype. A private variable is not supported in JavaScript, to mimic the private variable, you need to create a variable that is scoped to the constructor function. Declaring a variable as part of that object in the constructor via this.variableName automatically makes that property public.

# Challenge (😤🔥👊) Have some time to solve this riddle while waiting for part 7. However, there is sample and explanation, solve this on your own, just make sure to share it in the comment: (😅)

## ADDING A PROPERTY TO AN OBJECT

Problem: Add an exampleKey property to an empty JavaScript object in two different ways and set it to exampleValue.

Explanation: As discussed earlier in this part, a property can be added to an object in two ways. There is no performance advantage or disadvantage of using one way over the other; the choice comes down to style.

## DEFINING CLASSES

Problem: Create two classes: Animal and Dog. The Animal class should take two parameters in the constructor (name and animalType). Set them as its public properties.

Explanation: In addition, the Animal class should have two functions: sayName and sayAnimalType. sayName prints name, and sayAnimalType prints animalType initialized in the constructor.

Hint: Dog.prototype = Object.create(Animal.prototype);

# Up Next👉 Part 07: JavaScript Memory Management (🔥🔥) (July 10-11, 2020) Posted on by: ### Edison Pebojot(👨‍💻)

I started using computers and writing software around 2008 and 2009, I taught myself Programming. However, I wasn't a typical "nerd-klutz". 😅

### Discussion   