Be aware when playing around inside objects : a simple example explained

So it might look pretty simple and straight forward especially for JavaScript experts but it worth to mention and explain what I came across today once more with an example that I used to myself.

Here is the case. There is an object in the code and we want to add some arrays and values inside it. We simply want to create an array inside object using a method to add array values.

This is our object with the array inside it:

var todoListObject = {
    todoList : [‘One’,’Two’,’Three’]
};

Next step is to create a method inside the object that add a new value to the array. A method is basically a function. The important thing about methods is that we could use or manipulate the array for example using “this” keyword that refers to the object itself, here being todoListObject.

So the method will look like:

var todoListObject = {
    todoList :[‘One’,’Two’,’Three’],
    addNewValue : function(todoItem){
        this.todoList.push(todoItem);
    }
};

the todoItem is the item to be added to the array as methods can take parameters, todoItem will be pushed to the end of todoList using “this” keyword which refers to todoListObject object itself. So addNewValue is a method and it is actually the function’s name.

If we add a value by calling the method like this:

todoListObject.addNewValue(‘Four’);

We have this result:

console.log(todoListObject.todoList);

[‘One’,’Two’,’Three’,’Four’]

So far looks normal.

The interesting part that I wanted to point out is if we change the method to this:

var todoListObject = {
    todoList :[‘One’,’Two’,’Three’],
    addNewValue : function(todoItem){
        this.todoList.push({todoItem});
    }
};

Did you notice the difference?

Looks the same but the result is not because we have added braces around the todoItem to be pushed and now it considers as an object to be added to the array. If we call the method again:

todoListObject.addNewValue(‘Four’);

The result is :

console.log(todoListObject.todoList);

[‘One’,’Two’,’Three’,Object{

todoItem : ‘Four’

}]

Good Ha! The braces do all the job. They specify that an object with property of todoItem and value of Four will be added to the array. 

This is one of those things that when you found out about why your code is not working as expected or does not give error, you will go Ahhha that’s it. Love you JavaScript. 

© 2019
Azadeh Faramarzi

This site is created and maintined by Azadeh Faramarzi , A passionate developer, sport and code lover who loves to share and write when she has some time.