loading...
Cover image for Learn Data Structure and Algorithm in JavaScript | Part 06

Learn Data Structure and Algorithm in JavaScript | Part 06

edisonpebojots profile image Edison Pebojot(πŸ‘¨β€πŸ’») Updated on ・8 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

Part Table of Contents Description
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! (πŸ”₯πŸ”₯πŸ”₯)

Part 06: JavaScript Object(😱 πŸ”₯ 🎲)

Alt Text

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 (🎲🎲)

Alt text

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

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'}

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 (πŸ”β†”οΈπŸ“)

Alt text

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

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 (πŸ”§πŸ”œπŸ“¦)

Alt text

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 (πŸ“š)

Alt text

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 (😀πŸ”₯πŸ‘Š)

Alt text

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)


Alt text

Discussion

markdown guide