How to define arrays inside objects and play around with them

Lately I have posted an article about simple mistake around objects in this link emphasising how important curly braces are. Here in this article I want to show you other mistakes around arrays inside objets that might be useful to you.

I have created a simple pen in codepen ro demonstrate what I mean. My main focus is the array.Inside objects, arrays are defined as objects as well. Unlike a variable, which used assignment operator, in array we use colons to give them vale. And for arrays we use brackets to hold the values. Simple and important. But to give the array an initial value, we need to use braces around an item and then inside it first comes the item property name and after a colon, inside cotations we need to add the value like this:

todoList : [{todoItem : “I am an item”}]

And then we can add items to it with this addItem function:

addItems : function(todoItem){
**    this.todoList.push({**
**    todoItem : todoItem**

The mistake I talked about in this link was if we define the array like this:

todoList : [ “I am an item”]

Obviously in this case, array is not defined as an object and cannot be used as one.So in the addItem function we have to do this instead:

addItems : function(todoItem){

**   this.todoList.push(todoItem);**


So we removed the braces as the todoList is not accepting an object and just adding simple value to the list. In this pen I have shoed how it looks like if we have an array which is defined as an object with initial value. And an array without initial value which they are exactly the same in nature but un the first one we have specified an item to show how items should be added inside object arrays. (this is just an example, so be aware these arrays accept empty input if you just hit the button)

It looks simple and obvious but it is actually a fundamental concept about objects that should be taken care of. How to define an object which arrays are the best to practice ( with for having the same nature) , how to initialise them and make sure about syntax errors that might take aways hours in large and complicated code to be found.

Hope this post was helpful to you.

© 2020
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.