Learn Create Your Own Split Screen

Next Page

Why do we bother with such complexity ?

Consider our structured array example:

var fruits= [ {name: 'banana', colour: 'yellow', price: 1.99}, {name: 'apple', colour: 'green', price: 1.49}, {name: 'mandarin', colour: 'orange', price: 3.12}, {name: 'orange', colour: 'orange', price: 2.05} ]; alert(fruits[1].name + ' ' + fruits[1].price);
And think about how we might achieve it with just plain-old simple arrays:
var fruit_names= ['banana', 'apple', 'mandarin', 'orange']; var fruit_colours= ['yellow', 'green', 'orange', 'orange']; var fruit_prices= [1.99, 1.49, 3.12, 2.05]; alert(fruits_names[1] + ' ' + fruits_prices[1]);

They achieve the same result, but the first better expresses the intent, and is less error-prone when we possibly add more fruits in the future, or more properties such as 'nutrition'.

It also lets us assign an element of the array to a 'breakfast' variable and automatically take all the properties with it:

var breakfast= fruits[3];
Whereas the second form would need three separate breakfast variables and three separate assignments:
var breakfast_name = fruit_names[3]; var breakfast_colour = fruit_colours[3]; var breakfast_price = fruit_prices[3];

Structured arrays are a great way to keep lists of related things together.