× 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

Objects and arrays in JavaScript

This article shows the basics of objects, functions, and vectors in JavaScript language.

A programming aspect that always puzzles developers is how JavaScript works with objects. In this article we will understand how JavaScript works with objects considering two main points: objects and arrays. We will comprehend how each one works and acts through some examples that will be described in the article.

But first, let's talk about properties. A simple definition can be stated as “a lot of values have values associated with them”. These associations are called properties. Each string has a special property called "length" that represents the number of characters that form the string.

The JavaScript properties of one date type can be manipulated in one of two ways, as shown in Listing 1.

Listing 1. Two ways to access properties in JavaScript

var text = "javascript MrBool";   


After running the example code of Listing 1, two message boxes will be shown and both of them will have the text “19”.

The second way is a shortcut to the first and it is only executed when the property name is a valid variable name, i.e. when it does not have any spaces or symbols and does not begin with a digit character.

Null and undefined values do not have any properties. Any attempt to read properties of such values will produce an error. As an example, the code in Listing 2 just produce an error message that may be different for some browsers (which can be a bit cryptic).

Listing 2. Trying to read the size of a null

var e = null; alert(e.length);

Note: In order to reproduce the examples in this article the reader must create a HTML page with an enabled <script> tag for the JavaScript language. Listing 3 shows how to do this. The main goal of this article is not on the explanation of HTML concepts and we assume that the reader already has such knowledge.

Listing 3. Message error example with HTML tags

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

The result of the example found on Listing 3 cannot be viewed in the browser as a HTTP error message and the developer will need to access specific developer tools to see it. In this article we are going to use the Google Chrome Browser to run and test the examples. To access the developer tools of this browser just hit the F12 key and access the last tab that appears, which is called "Console". This is the place that lists all client side scripting errors.

The error message produced from the execution of a code in Listing 3 is "Uncaught TypeError: Cannot read property 'length' of null". This is the message provided by the Chrome Browser upon this type of error as shown in Figure 1.

Property error message provided by Chrome

Figure 1. Property error message provided by Chrome

The properties of a string value cannot be changed and there are others properties than the length, as we will see, but we are not allowed to add or remove any of them. However, text and other objects in JavaScript have their own properties that can be modified, removed or added, as shown in Listing 4.

Listing 4. Representing an object in JavaScript

var shoes = {color: "brown", brand: "Nike", size: 7};

// Assume that the show() function already exist and it is functional

shoes.size= 8;      

delete shoes.size;   


Each object property attached to an object is marked by a string just like a variable. The first line of Listing 4 creates an object with the "color" property connected with the string "brown", with the "brand" property connected to the string "Nike", and with the "size" property with the number 7. The next executable statement in Listing 4 assigns the value 8 to the recently created “size” property in a similar way that we assign values to variables.

The keyword JavaScript "delete" removes specific properties. Any attempt to read a nonexistent property will produce an "undefined" value.

If a property that does not exist yet is used with the assignment operator = the JavaScript engine adds it to the object, as shown in Listing 5.

Listing 5. Creating a property

var emty = {};   

emty.newProperty = 1000;   


Properties whose names are not valid variable names have to be mentioned while creating the object and marked with brackets, as shown in Listing 6.

Listing 6. Variable name

var paper = {"title": "Javascript introduction", "5": 22};


paper["5"] = 20;   

show(paper[2 + 3]);

delete paper["title"];

As we can see, the value inside the brackets can be any expression since it is converted to a string to name the property to which it relates. It is even possible to use variables to name properties, as shown in Listing 7.

Listing 7. Using variables for property names

var propertyName = "length";   

var text = "something strange";   


This JavaScript feature allows a great level of flexibility when working with variables and operators.

Objects and values

The values of objects can change over time. However the values assigned to variables that are created from primitive data types are all immutable, which means that it is impossible to change an existing value of the JavaScript primitive types. It is possible to combine them and get new data types, but when you assign a specific string to a variable the text inside it cannot changed. Objects, on the other hand, can be changed by modifying Their properties.

For instance, let’s take two equal numbers (2.4 and 2.4). JavaScript deals with these two numbers as if they are the same in comparisons and assignments. However, JavaScript manage objects in a different way, since there is a big difference between having two references to the same object and having two different objects that have the same values for their properties. The code in Listing 8 shows another example of this difference.

Listing 8. Objects with equal values

var object1 = {value: 2.4};   
var object2 = object1;   
var object3 = {value: 2.4};       

show(object1 == object2);   
show(object1 == object3);       
object1.value = 4.8;   


In the code of Listing 8 object1 and object2 are two variables that have the same value. There is only one object in fact, 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.

When the == JavaScript operator compares objects it return "true" if both values (left and right hand sides) are precisely the same. When comparing different objects with identical contents the operator will always return "false". This is useful in some situations, but impractical in others.

Object values can serve for many different situations and their behaviors to act as a whole is just one of their features.


Let’s suppose we have a variable in JavaScript that will hold all the details of some emails that need to be sent by a system. How we store this email information in JavaScript poses an interesting situation. It may contain a series of strings like emails. In fact, the entire set of emails could be placed in a huge string, but this is impractical. What we want is a collection of distinct strings.

Collections of general elements are the purpose for which the objects are used in JavaScript. For instance, the following code shows how to create a set of string properties to store email data.

var emailsSet = {"first e-mail": "Everyone, the meeting has to be postponed...", "second e-mail": "..." /* and so on... */};

This approach makes it hard to see the emails from start to finish. How the programmer guesses the name of these properties? This can be solved by naming the properties with predictable names, as shown in Listing 9.

Listing 9. Predictable property names

var emailsSet = {"0": "Everyone, the meeting has to be postponed... #1", 1: "(email num #2)" , 2: "(email num #3)"};    

for (var i = 0; i in emailsSet; i++)
     print("Processing e-mail #",i,":",emailsSet [i]);

However, this type of structure can be very confusing, especially considering the potential for the inclusion of new records in the model. We can solve the situation using the resource called arrays which have many features, such as the length property that contains the number of values in the array.

To create a new array we need to use square brackets ([and]), as shown in Listing 10.

Listing 10. Creating new array in JavaScript

var emailsSet = ["email one", "email two", "email three"];

for (var i = 0; i < emailsSet.length; i++)
     print("Processing e-mail #",i,":",emailsSet[i]);

In the example of Listing 10 the number of elements is not explicitly specified. The first element is automatically located in position 0, the second number in position 1, and so on.

This example create a common question among beginners: Why start at 0? People tend to start counting from 1. As intuitive as it sounds, the numbering of elements in a collection of 0 is often more practical. Starting from the element 0 implies that a collection that contains x elements will store the last element at position x-1. That’s the reason why the for loop in Listing 10 checks the expression "i

Properties of objects and arrays

Objects and Strings in JavaScript have other properties besides the length. The example of Listing 11 shows the use of properties that belong to the String data type.

Listing 11. Properties example for the String data type

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

Every string has a property called "toUpperCase" that returns a copy of the string with all letters converted to uppercase. There is also the opposite property, "toLowerCase", which converts the entire string to lowercase.

The reader should note that although the call to toUpperCase do not require any arguments, the function somehow have access to the string "abc", whose value is a property. The properties that contain functions are usually called methods. For instance, the "toUpperCase is a method of the String data type. Listing 12 shows other methods calls of the String data type.

Listing 12. Example of array and functions/methods call

var list = [];


show(list.join(" "));   



The "push" method, which is part of the array, can be used to add values to it. The “pop” method performs the opposite operation: removes and returns the last value of the array. The "join" method constructs a single large string from an array of strings and it requires a parameter that will be inserted in the string after each value of the array.

The example shown in Listing 12 acts on white spaces to separate different words and possibly joining them in a sentence. The strings themselves are nothing more than objects that manipulate characters to make words, sentences and texts. Imagine then how to describe the structure of a paragraph in the same schema.

The first question that arises is what exactly a paragraph is. In this case, the string value cannot help us much: the concept of "text" to JavaScript goes no deeper than the idea of 'string', so the paragraphs can be defined accordingly. The way it is structured and divided is another issue to be addressed.

In order to make the structure equal to a paragraph we must use the new line sign represented by a character in JavaScript since this is what most people use to divide paragraphs. We will assume that a paragraph is as a part of an email that starts with a newline and ends next newline character or end of the content. The advantage of using functions is that they also exist natively, meaning that someone else wrote, tested and released it for everyone. The Strings data type already has a method called "split", which is (almost) the opposite of method "join", since it divides a string into an array, using the given string as an argument to determine where to break it. Check the example presented in Listing 13.

Listing 13. String break up example using the Split method

var phrase = "This is a simple phrase";   

show(phrase.split(" "));

The example of Listing 13 splits a string into several smaller pieces based on the empty space (“ ”) character. We can use the same idea to break new lines (using the special character "\n") and divide the email into paragraphs.

Also, perhaps you do not want your paragraphs staring with the words "The" or "However" and that our program should ignore them. How do we test whether a string starts with a certain word? The "charAt" method can be used to get a particular character from a string. For instance, the "x.charAt (0)" returns the first character, 1 is the second, and so on. One way to check if a string starts with "The" would be as shown in Listing 14.

Listing 14. Checking the string

var paragraph = "The only way to achieve success is not giving up.. ";
show(paragraph.charAt(0) == "T" && 
     paragraph.charAt(1) == "h" && 
     paragraph.charAt(2) == "e"); 

This approach is not very good because it is not convenient for lengthy words. Note that when a line is ridiculously long it can be split into multiple lines. The result can be easier to read by aligning the start of the new row with the first element in the original line. Strings also have a method called "slice", which copies a piece of string beginning at a position given by the first argument and ending before (not including) the character at the position given by the second parameter. This allows the selection to be written in a shorter form:

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

But what happens when "charAt" or "slice" functions are used to get a piece of a string that does not exist? Does the "startsWith" still work when the pattern is larger than the string?:


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

The "charAt" function will return "" when a character does not exist in the given position, since "slice" will simply leave out the part of the new string that does not exist. The code in Listing 15 summarizes the use of methods and functions.

Listing 15. Summary of functions and methods called

var emailSet = getEmails();   
var authros = {"MrBool": true};       

for (var mail = 0; mail < emailSet.length; mail++) 
	var paragraphs = emailSet [mail].split("\n");     

	for (var paragraph = 0; paragraph < paragraphs.length;          paragraph++) 
		if (startsWith(paragraphs [paragraph], "The")) 
			var names = getNames(paragraphs[paragraph]);         

		for (var name = 0; name < names.length; name++)
           		authros[names[name]] = true;       
	if (startsWith(paragraphs[paragraph], "However")) 
		var names = getNames(paragraphs[paragraph]);
         	for (var name = 0; name < names.length; name++)
		           delete authros[names[name]];       


Some pieces of code look like an impenetrable jungle. One way to shed some light is add a few blank lines in strategic places. This technique makes the code better, but does not solve the problem. What is needed here is to break the code above. We have already written two auxiliary functions, startsWith and getNomes, that handle a small part of the problem. Let's keep doing it. See Listing 16.

Listing 16. Creating auxiliary functions

function addToSet (set, values) 
for (var i = 0; i < values.length; i++)       
	set[values[i]] = true;   

function removeFromSet (set, values) 
	for (var i = 0; i < values.length; i++)       
		delete set[values[i]];   

These two functions add and remove names in the set and they avoid the two innermost loops of the solution. Check Listing 17 to see how the code looks like with these to new methods.

Listing 17. Adaption the previous code

var authros = {"MrBool": true};       

for (var mail = 0; mail < emailSet.length; mail++) 
	var paragraphs = emailSet [mail].split("\n");     

	for (var paragraph = 0; paragraph < paragraphs.length;          paragraph++) 
		if (startsWith(paragraphs [paragraph], "The")) 
			var names = getNames(paragraphs[paragraph]);         

		for (var name = 0; name < names.length; name++)
           		authros[names[name]] = true;       
	if (startsWith(paragraphs[paragraph], "However")) 
removeFromSet(authors,          getNames(paragraphs[paragraph]));     

Why the addToSet and removeFromSet methods receive the collection as an argument? They could use the variable "authors" directly if they wanted. The reason is that in this way they are not coupled to our current problem. The way it is now is a more useful solution, in general.

It is useful to write the functions like this because they are "self-sufficient". They can be read and understood on their own without the need to know any external variable.

The functions are not pure: they change the set object passed as an argument. This makes them a bit more complicated than pure functions, yet it's all a lot less confusing than functions that change any value or variable you want.

Microsoft MVP, Bachelor in Science And Technology, Editor and Consultant at DevMedia with more than 7 years of experience in software development.

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