× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Understanding Objects and Vectors in Javascript

In this article well see a very brief introduction about objects and vectors in JavaScript world.

There are times Javascript is seen as the language of the future. From the future or not, one thing is certain: there are many developers out there who have already handled languages of all kinds and purposes, but perhaps one does not have made them so amazed and excited by using it, and this is certainly Javascript. The language is simple, or at least should be, but so simplicity ends up to leave many people confused on what we can or cannot do with the language. Well, we know we can a lot, but the big problem is always to understand why things happen and the consequences of doing this or that.

In JavaScript, we have variables, methods (or rather functions); we have inheritance, polymorphism and many object oriented things. You can decide whether we want to give a type to an attribute or let the language do that, and then we change the type again and so on... However, one thing that always intrigues many people is to understand how Javascript works with objects. In this article, we will focus on two main points: objects and vectors. We understand how each one works and acts in the program context, according to some examples that you will follow throughout the article.


First, let's talk about the properties. Many JavaScript values have other values associated with them. These associations are called properties. Each string has a property called "lenght", which refers to a number, the number of characters of the string. The properties can be accessed in two ways (Listing 1).

Listing 1. Forms to access properties in Javascript

var text = "javascript mrbool";

The example should display the value "19". The second way is a shortcut to the first, and it only works when the property name is a valid variable name - when he has no space or symbols on it and does not start with a digit character. Null and undefined values do not have any properties. Trying to read the properties of such a value will produce an error. Try the following code, just to get an idea about the type of error message that your browser produces in such a case (which, for some browsers, can be a bit puzzling):

var empty = null;

Note: In order to reproduce the examples in this article you need to create an HTML page with the Javascript tag <script> enabled.

Listing 2 shows how to do this. There will not be focus of this article explain HTML concepts, it is understood that the reader already has such knowledge.

Listing 2. Examples of execution code

                <script type="text/javascript">
                function test() {
                               var empty = null;
<body onload="test()">

The result of the example cannot be viewed in the browser as HTTP error message; this means that you need to access the same developer tools. Here, we will be based on the Chrome browser. To access it simply select the F12 shortcut and open the last tab that appears, of "Console" name. There we have listed all the errors related to client side scripts. The error resulting from the execution of a null value is "Uncaught TypeError: Can not read property 'length' of null" for Chrome.

The properties of a string value cannot be changed. There are more properties than the lenght, as we shall see, but you do not have permission to add or remove any of them.

This is different with the text object values. Its main role is not only the realization of other values. They have, you might say, its own set of tentacles in the form of properties. You are free to modify them, remove them or add new ones. An object can thus be written as shown in Listing 2.

Listing 2. Object representation in Javascript

var shoes = {color: "brown", brand: "Nike", size: 42};
shoes.size = 47;
// Consider that the show function really exist and works...
delete shoes.size;

Like variables, a string marks each property attached to an object. The first statement creates an object in which the property "color" holds the "brown" string, the "brand" property is connected to the string "Nike", and the "size" property refers to the number 42. The second statement gives to the size of the named property a new value, which is made in the same way as the modification of a variable.

The keyword "delete" removes specific properties. When you try to read a non-existent property, it returns the value "undefined". If a property that does not yet exist is defined with the assignment operator =, it is added to the object, for example:

var empty = {};
empty.soThatnot= 1000;

Properties whose names are not valid variable names must be cited to create the object, and marked using brackets:

Listing 3. Correct syntax of properties.

var article = {"title": "Introduction to JavaScript", "5": 22};
article["5"] = 20;
show(article[2 + 3]);
delete article["title"];

As you can see, the part in brackets can be any expression. It is converted to a string to determine the name of the property to which it relates. We can even use variables to name properties:

var propertyName = "length";
var text = "Hello World";

Therefore, we have greater flexibility in the use and manipulation of variables in conjunction with the operators...

Values objects

Values objects apparently can change. The types of values for variables in JavaScript are all immutable, which means that it is impossible to change an existing value of these types. You can combine them and get new values from them, but when you take a specific string value, the text inside it cannot change. With objects, on the other hand, the contents of a value can be modified by changing their properties.

When we have two numbers, 2.4 and 2.4, they can be considered the same precise number for all practical purposes. With objects, there is a difference between having two references to the same object and having two different objects that contain the same properties. Consider the code contained in Listing 4.

Listing 4. Objects with equal values.

var object1 = {valor: 2.4};
var object2 = object1;
var object3 = {valor: 2.4};
show(object1 == object2);
show(object1 == object3);
object1.value= 4.8;

The object1 and object2 are two variables that have the same value. In fact, there is only one object, which explains why changing the value of object1 also changes the value of object2. The variable object3 points to another object, which initially contains the same properties as object1, but lives a separate life.

The operator ==, when used to compare objects, will only return "true" if both values assigned to it are precisely the same value. Comparing different objects with identical content will always return "false". This is useful in some situations, but impractical in others.

Values of objects can be used for several different things. Behaving as a collection is just one of those things.


Imagine a variable in Javascript, which will stores emails values to be sent by a system of a company. The manner in which the email file is stored is still an interesting question. It contains a series of emails. An email can be a string, of course. The entire file could be placed in a huge string, but this is impractical. What we want is a collection of distinct strings.

Collections of things are the purpose for which the objects are used. You can make an object like this:

var fileEmails = {"first email": "Dear, our meeting would be postponed...",
                   " second email": "..."
                   /* and so on ... */};

But, that makes it difficult to see the emails from start to finish - how the program guess the name of these properties? This can be solved by more names of predictable properties:

var fileEmails = {0: " Dear, our meeting would be postponed... (email num #1)",
                   1: "(email num #2)",
                   2: "(email num #3)"};
for (var cont = 0; cont in fileEmails; cont++)
  print("Processing email #", cont, ": ", fileEmails[cont]);

However, this type of structure can be very confusing, especially considering the amount of possible new records to be included in the model. We can solve the situation using the resources called vectors (or arrays). They provide various facilities such as a length property, which contains the number of values in the array, and a number of useful operations for this type of collection.

To create a new vector just use the brackets ([ and ]), as shown in Listing 5.

Listing 5. Creating new vector in Javascript

var fileEmails = ["email one", "email two", "email tree"];
for (var cont = 0; cont < fileEmails.length; cont++)
  print("Processing email #", cont, ": ", fileEmails[cont]);

In this example, the number of elements is not explicitly specified. The first element is automatically located in position 0, the second at position number 1 and so on. And this is a common question among beginners at programming: Why start at 0? People tend to start counting from 1. As intuitive as it sounds, the numbering of the elements in a collection of 0 is often more practical. Just accept this for now and will see over time the practicality of it.

Starting from 0 element also means that in a collection of x elements, the last element can be found at x - 1. This is why the loop in Listing 5 checks "cont <fileEmails.length". There is no element in fileEmails.length position, so as soon as "cont" receives this value, the loop too.

Properties of objects and vectors

Both string and vector object contains, besides the lenght property, a number of properties that refer to the function values:

var abc = "abc";
show(typeof abc.toUpperCase);

Every string has a property called "toUpperCase". When called, it will return a copy of the string where all letters are converted to uppercase. There is also the opposite property, "toLowerCase" which converts the entire string to lowercase.

Note that although the call to toUpperCase not pass any arguments, the function in some way, have access to the string "abc", whose value is a property. The properties that contain functions are commonly called methods, as in "toUpperCase is a method of a string object." See Listing 6.

Listing 6. Example vector and calls to functions/methods

var list = [];
show(list.join(" "));

The method "push", which is associated with the vector, can be used to add value to it. Right after that, we have a call to the "pop" method (the push opposite): it removes and returns the last value of the vector. The method "join" builds a single large string from a string vector. The last parameter is interposed between the values in the vector.

The above example acts on whitespace to separate different words and join them possibly in a sentence. The strings themselves are nothing more than objects that manipulate characters to make words, sentences and texts. Imagine then how would work a paragraph structure at that same scheme.

The first question that arises is what exactly is a paragraph. In this case, the string value itself cannot help us much: The concept of "text" for the JavaScript will not be deeper than the idea of 'string of characters', so the paragraphs can be defined in these terms: a sequence of characters. The way it is structured and divided is already another issue to be addressed.

So that the structure is actually equals to a paragraph, we must consider the new line operator, which can be represented by a character in JavaScript and is what most people use to divide paragraphs. Consider a paragraph, then, as a part of an email that begins with a newline character or at the beginning of the content, and ends at next newline character or at the end of the content. The advantage of using functions is that they also may already exist natively, which means that someone has written, tested and released them before. The strings already has a method called "split", which is (almost) the opposite vector method of "join". It splits a string into an array using the string given as an argument to determine where to cut it. See the example listed in Listing 9.

Listing 9. Example of string breakage using the split method

var frase = " Welcome to Mrbool";
show(frase.split(" "));

In this example we can split a string into several smaller pieces, thus, breaking new lines ( "\ n") can be used to split an email into paragraphs.

In addition, think that you might want your paragraphs to not start with words "but" or "however" and that our program should ignore them. How do we test whether a string starts with a particular word? The method "charAt" can be used to obtain a specific character from a string. "X.charAt (0)" returns the first character, 1 is the second, and so on. One way to check if a string starts with "But" would be:

var paragraph = "But the only way you can win is not giving up...";
show(paragraph.charAt(0) == "B" && paragraph.charAt(1) == "u" && paragraph.charAt(2) == "t");

However, this is not very good - imagine checking a word of ten characters or thirty. Note that when a line is ridiculously long, can be split into multiple lines. The result can be easier to read, aligning the start of the new row with the first element in the original line, which plays a similar role. Strings also have a method called "slice". It copies a piece of string from the character in the position given by the first argument, and ending before (not including) the character at position given by the second. This allows the selection to be written in a shorter form:

show(paragraph.slice(0, 3) == "But");

Nevertheless, what happens when the functions "charAt" or "slice" are used to get a piece of a string that does not exist? Does the "startsWith" still work when the pattern is greater than the string in place? Look:

show("World".slice(1, 12));

The "charAt" function will return "" when there is a character at the given position, as "slice" will simply leave out the part of the new string that does not exist.

So yes, this version of "startsWith" works. When startsWith("Market", "peanut butter and cinnamon") function is called, the call to slice function (because the string does not have enough characters) always returns a string that is smaller than the standard. Therefore, the comparison with == will return false, which is correct. This helps to always have a moment to consider the unusual entries (but valid) for a program, which are usually called "corner cases" and it is very common that programs that work perfectly on all "normal" inputs and stop at a corner case. Therefore, we can sum up the code previously made by Listing 10.

Listing 10. Summary of known functions and methods

var fileEmails = recoveryEmails();
var autores = {"MrBool": true};
for (var mail = 0; mail < fileEmails.length; mail++) {
  var paragrafos = arquivoEmails[mail].split("\n");
  for (var paragrafo = 0;
       paragrafo < paragrafos.length;
       paragrafo++) {
    if (startsWith(paragrafos[paragrafo], "Mas")) {
      var nomes = getNomes(paragrafos[paragrafo]);
      for (var nome = 0; nome < nomes.length; nome++)
        autores[nomes[nome]] = true;
    else if (startsWith(paragrafos[paragrafo], "Contudo")) {
      var nomes = getNomes(paragrafos[paragrafo]);
      for (var nome = 0; nome < nomes.length; nome++)
        delete autores[nomes[nome]];

Some pieces of code look like an impenetrable jungle. One way to do some light shine through it is adding a few strategic lines in white. This makes it look better but does not solve the problem. What is needed here is to break up the code. We have already written two auxiliary functions, startsWith and getNames, caring for a small part of the understandable problem. We will continue doing this. See Listing 11.

Listing 11. Creating auxiliary functions

function addToCollection(set, values) {
  for (var i = 0; i < values.length; i++)
    set[values[i]] = true;
function removeFromCollection(set, values) {
  for (var i = 0; i < values.length; i++)
    delete set[values[i]];


It is quite likely that you already know one or more of the topics explained so far and the idea is that even incite in you the desire to know the language further. This was just a very basic approach of how objects, functions and vectors behave in Javascript. Search, train and learn deeper the Javascript.

Web developer and passioned for web design, SEO and front end technologies.

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login