Alexa Metrics
RoBOOGarden Halloween Howler Event

JavaScript for Beginners: Data structures in JavaScript

2018-10-10
Image of icons showing different data structures in JavaScript

What are Data Structures?

Data structures are data containers used to store, manipulate, and ease access to stored data in different programming languages. In JavaScript, arrays are used to store multiple values in a single variable. Unlike in other languages, in JavaScript these values can hold different types, as we will see later.


If you have a list of shapes, for example, you can use the following line of code as a declaration of your array:

var shapes = [“Triangle”,”Rectangle”,”Circle”];

Of course, you can also use multiple lines:

var shapes = [

“Triangle”,

”Rectangle”,

”Circle”

];


The real benefit of arrays and data structures become clear when you start handling larger amounts of data. For example, an array would come in handy if you wanted to store 100 different shapes.

You can always access the value of a certain array element by using its index. For example, if you want to assign the value “Circle” to variable x, you would do the following:

var x = shapes[2];

Remember that we start counting spots in an array at zero. In other words, the first slot in our example array is:

shapes[0]

You can also change the value of any spot inside the array using the index:

shapes[2] = “Square”;


What’s New?

New is the keyword we use to create an object like an array and populate it with values:

var shapes = new array("Triangle", "Rectangle", "Circle");

What is the typeof?

In JavaScript, the typeof operator returns the types of the objects inside an array. Remember that arrays in JavaScript can hold objects of different types.

The following example describes a car array with some of the car’s specs:

var car = [“Volvo”, “Red”, 1999];

This array holds integer and string variable types and we can access each spot inside the array using its index. In other words, car[2] returns 1999. You can have many different object types together inside the same array, even functions.


Methods

Arrays in JavaScript come armed with built-in methods that can be very handy. For example, shapes.length() will return the length of that array, while shapes.sort() will sort the elements of the array from least to greatest.


Give It a Little Push

You can use the method called “push” to add a new element to an array. For example, the method

shapes.push(“Square”);

will add “Square” to the end of the shapes array. Its length will now be four. Got it? There is much more to come! Start your learning journey now with RoboGarden. Register for free.

JavaScript Series Introduction to JavaScript

RELATED BLOGS

Start JavaScript coding

Let's start JavaScript coding with RoboGarden learning journey.

Canada Flag Privacy Policy Terms of Use
Got an invite