A Shallow Dive into Data Structures in JavaScript

The Deep Dive will come later guys, don't get ambitious ,first we have to learn about Data Structures before we can jump into the good stuff, the part where we actually learn how to truly have fun with Data Structures in JavaScript and we actually dominate coding in this language which, to be honest and after almost 70 hours spent learning it, I can say it is quite simple once you understand the logic of how to think it before you write it, the problem is actually understanding the logic, which is why I am still in what most devs would consider a "beginner level" in JS.

But if you think about it, there's one reason there's a shortage of developers, and I'm sure as hell that being an easy language to learn is not one of them, which leads me to believe I am in front of a mirage and I am actually fooling myself, and the real challenge and actual obstacles of learning JS haven't even thought of approaching me, I am still a rookie and they don't even think of me as a worthy opponent.

So I'm not gonna get ahead of myself and won't get cocky and actually get the job done before calling JS an easy language to learn once you understand the logic behind it, because perhaps you don't even know what the logic is really about, after all, and 70 hours into it is not enough to get full of myself and brag.

But, but, like Leonidas right after deflecting several waves of Persian attackers in the Thermopilae aka the hot gates, I am starting to believe I can actually win this battle, let's just hope I don't have a sneaky bastard stabbing in me the back - which in this case, and in most, is myself (and yourself if you're trying to learn how to code).

Well, enough for intros, let's get to work.

Data Structures

image.png

Arrays

We use arrays when we want to store multiple data in variables so that we can use them later, without arrays, we would have to type in each value we get and store it into an individual variable, and you can imagine how complicated - not to say boring - it would get very soon...

const hiveUser1 = "@lunaticpandora";
const hiveUser2 = "@cadawg";
const hiveUser3 = "@deathwing";
const hiveUser4 = "@galenkp";
const hiveUser5 = "@abh12345";
const hiveUser6 = "@tarazkp";
const hiveUser7 = "@jeffjagoe";

By the way, if you're not following these dudes, go do it now, this is not a shoutout, I just wanted to write something and instead of setting food names I decided to store hive usernames and these are the first that came to mind. Go follow them, their content might not be top of the line (wink wink) but they are quite ok

Imagine if I wanted to write out and store each Hive User and store them into a variable. That would not be fun at all, imagine writing all of them like this, having to store them each into a variable.

That's why we have Data structures, which simplify the life of the JS coder, allowing him to store multiple pieces of data in a single variable, such as an Array.

The two most important data structures in JS are arrays and objects, so to use an array to store the Hive users we do like this:

const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", "abh12345", "tarazkp", "jeffjagoe"];

And then we can call all of them by just:

console.log(hiveUsers); 

The output of the above will be:
[
'lunaticpandora',
'cadawg',
'deathwing',
'galenkp',
'abh12345',
'tarazkp',
'jeffjagoe'
]

So as you can see, it is so much easier to manipulate big chunks of data that share a characteristic (in this case, all of them are Hive users).

There is also another way to code Arrays, but personally I like the first way more, and it seems that most devs feel the same way, either way I'll show it to you for the sake of knowledge.

const hiveUsers = new Array("Pedro", "Pablo", "Juan");

An array can hold as many values as we like and of any type of value, but it only stores them, to actually call them we must:

const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", "abh12345", "tarazkp", "jeffjagoe"];
console.log(friends[0]); //1
  1. Arrays are zero based, so if we want to call lunatic, we put a zero inside the brackets, and we are calling him.
console.log(friends.length);                  //2 
console.log(friends[friends.length-1]); //3
  1. We are calling all the elements in the array because the length of the array means the number of elements, this means we are calling all the indexes in the array.
  2. This way we are calling the last value of the array, we could call the second to last with a -2, and so on. If the array has 5 elements, the length of the array is 5, and since arrays are zero based, the last element is in the position 4 of the array. array.length -1 is actually calling the array in the position 4, the last element in the array. This logic works no matter how many elements are in the array.

The square brackets are not only to retrieve elements from the array, but we can also use them to mutate the array and add or take elements from it. The code next will replace the element in the second position with another value:

const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", "abh12345", "tarazkp", "jeffjagoe"];

hiveUsers[2] = "newHiveUser";
console.log(hiveUsers);

And our new output will be:

[
'lunaticpandora',
'cadawg',
'newHiveUser', <=== See the new user?
'galenkp',
'abh12345',
'tarazkp',
'jeffjagoe'
]

Unlike values that we store in a const variable, Arrays stored in a const variable are not immutable, so we can change them like we did above, we can mutate arrays but we cannot replace them entirely, we can only do it element by element.

We can also use variables with values already stored in them and then store them as part of the Array, and we can actually put arrays inside an array.

const hiveFriend1 = "abh12345";
const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", hiveFriend1, "tarazkp", "jeffjagoe"];
const cryptoUsers = [hiveUsers, "Satoshi", "ElonMusk"];
console.log(cryptoUsers);

If you've made it this far, you now understand the logic behind arrays, which doesn't really give you anything yet, but you now have the basis for more complicated problems and to later on, understand objects.

Methods

These are basic array operations and are built in functions that we can apply directly into an array. There are countless of methods, but here are some basic ones that we should learn:

const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", "anh12345", "tarazkp", "jeffjagoe"];
hiveUsers.push("anomadsoul"); //4

console.log(hiveUsers);

Output: ["lunaticpandora", "cadawg", "deathwing", "galenkp", "anh12345", "tarazkp", "jeffjagoe", "anomadsoul"];

  1. Push is a function that we call on the array, and that's why the "dot" is there, to attach it to the array hiveUsers. .push pushes the element we put as argument at the end of the array. It mutates the previous array and replaces it.

If we don't want to mutate the array and actually create a new array, we have to store that new array into a variable:

const newHiveUsers = hiveUsers.push("anomadsoul");   

We can also add elements to the beginning of the array

const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", "anh12345", "tarazkp", "jeffjagoe"];
hiveUsers.unshift("anomadsoul");
console.log(hiveUsers);

Output: ["anomadsoul", lunaticpandora", "cadawg", "deathwing", "galenkp", "anh12345", "tarazkp", "jeffjagoe"];

We can also remove the last elements from the array using a simple method

const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", "anh12345", "tarazkp", "jeffjagoe"];
hiveUsers.pop();        
console.log(hiveUsers);

Ouput: ["lunaticpandora", "cadawg", "deathwing", "galenkp", "anh12345", "tarazkp"]

If we want to remove the first element in the array, we can use another method called .shift

const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", "anh12345", "tarazkp", "jeffjagoe"];
hiveUsers.shift();        
console.log(hiveUsers); 

Ouput: ["cadawg", "deathwing", "galenkp", "anh12345", "tarazkp", "jeffjagoe"];

If we know that we have a specific element inside an Array, we can use a function to return in what position inside the array that element is using the built in method .indexOf

const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", "anh12345", "tarazkp", "jeffjagoe"];
console.log(hiveUsers.indexOf("galenkp"));````

To find out if an element exists inside the array, we use the method .includes and it returns a boolean. This method uses strict equality, which means that it does not do type coertion (if you don't know go back to basics, but if you don't want to, I'll tell you, type coertion is something that JS does behind the curtains, changing the type of the value so it can work with it).

const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", "anh12345", "tarazkp", "jeffjagoe"];
console.log(hiveUsers.includes("anomadsoul"));

Ouput: False

We can also combine methods with the if function:

const hiveUsers = ["lunaticpandora", "cadawg", "deathwing", "galenkp", "anh12345", "tarazkp", "jeffjagoe"];
if (hiveUsers.includes("cadawg")){ //5
    console.log("There is a Hive user called Cadawg")
}  
  1. Since the boolean value is true, then we get the string printed.

There are many more methods to manipulate arrays, but these are the most used ones and if you understood all of them, you're set at least for the moment.

Objects

When it comes to arrays, we can reference them by their index number (the position or order they are in the array), but we don't actually have a way of calling them by name, they are just pieces of data inside a box. Objects solve this situation by giving them a key or property, allowing us to call them through that property.

const hive = {
    stableCoin: "SBD",
    videoDapp: "3Speak",
    financeDapp: "Leo",
    creationYear: 2020,
    hiveUsers: ["lunaticpandora", "cadawg", "deathwing", "galenkp", "anh12345", "tarazkp", "jeffjagoe"]
};

The object called Hive has 5 properties (keys) and each property has a value. Objects are the most fundamental part of JS, so obviously, there are several ways to code an object.

The main difference between objects and arrays besides the one mentioned above, is that for objects it is not important the order of the elements whereas in arrays the order is the most important part, because we use that order to call them. So with that info, we can infer that we use objects for ordered data and arrays for unordered data.

To call a property value all we have to do is use the dot notation, which is the most popular one, just like this:

console.log(hive.creationYear);     // Output: 2020

But we can also call an object's property value by using the brackets notation.

console.log(hive["stableCoin"]);    // Output: SBD

Using the bracket notation gives us an advantage because we can use any expression that we want and not only the property (key) to call it, just like this:

A good example of when we could need the bracket notation is when we don't know yet which property we want to print, and we will get the information from an user's input:

const anomadsoul = {
    favCoin: "hive",
    reputation: 77,
    votesWitnesses: true,
};
console.log(anomadsoul);
const interestedIn = prompt("What do you want to know about anomadsoul? Choose between favCoin, reputation, or if he votes for witnesses");
console.log(anomadsoul[interestedIn]);

If the user wants to know about a property that doesn't exist in the object, such as "votingPower", then we can code a response to that in the form of a string with the if method.

if(anomadsoul[interestedIn]) {
    console.log(anomadsoul[interestedIn]); // 6
} else {
    console.log("That value doesn't exist for anomadsoul! What do you want to know about anomadsoul? Choose between favCoin, reputation, or if he votes for witnesses");
}
  1. If the value exists, it will be true, if it doesn't it will be false.

Now that we know how to use the dot and bracket notations, let's dive into how to add or take properties from an object using them.

anomadsoul.votingPower = "10,000 SP";
anomadsoul["delegations"] = false;

console.log(anomadsoul); // 7
  1. We are calling the object after we added two properties with a value using both notations.

Output:
{
favCoin: 'hive',
reputation: 77,
votesWitnesses: true,
votingPower: '10,000 SP',
delegations: false
}

Object Methods

Objects just like arrays can hold multiple types of data, but objects go a step further.

Using the dot notation:

const anomadsoul = {
    favCoin: 'hive',
    reputation: 77,
    votesWitnesses: true,
    steemPower: 10000,
    liquidSteem: 5000,
    delegations: false,
    favoriteTags: ["javascript", "ocd", "coding"],
    name: "Eric",
    accountValue: function(steemPower, liquidSteem) {
        return `anomadsoul's account is worth ${steemPower + liquidSteem} Hive`;
    }
};

console.log(anomadsoul.accountValue(anomadsoul.steemPower, anomadsoul.liquidSteem));

Or using the bracket notation:

console.log(anomadsoul["accountValue"](10000, 5000)); // bracket notation

But there's a way to keep the code clean and without much tangles, for that we can use the .this keyword. It is a way to call a method inside an object.

So, the function is inside the object "anomadsoul", right? So whenever we use the .this in that function, we are referring to the object anomadsoul.

const anomadsoul = {
    favCoin: 'hive',
    reputation: 77,
    votesWitnesses: true,
    steemPower: 10000,
    liquidSteem: 5000,
    delegations: false,
    favoriteTags: ["javascript", "ocd", "coding"],
    name: "Eric",
    accountValue: function () {
    return `anomadsoul's account is worth ${this.steemPower + this.liquidSteem} Hive`;
    },
    nextPowerDown: function (){
        this.powerDown = this.steemPower / 13;
        return this.powerDown;
    }
}
console.log(anomadsoul.accountValue(this.steemPower, this.liquidSteem));
console.log(anomadsoul.nextPowerDown(this.steemPower));
console.log(anomadsoul);

Any function that is attached to an object is called a method

Note to self: Remember that "? :" is a quick way of writing an if method for booleans where we can only have two results.

e.g. this.delegations ? "Yes" : "No"



And that is pretty much it for Data Structures intros, if you made it till the end and you're learning JS, then you're set with the basics and you're ready to take on more complicated information regarding DS.

I know my coding posts might be boring for most people, so if you think I should drop a notch and post less frequently about this topic, please do. I know I don't have the engagement I used to have on my posts a couple of years ago, so if you are one of the few still reading, your input is much valued.

Have a great Friday night / Saturday morning amigos!


For all my coding content I use @ecency, if you haven't checked it out, please do, you won't regret it!

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Ecency