In the last post I’ve told you
everything you need to know about
values and variables.
And I hope you’ve enjoyed it!
Those two concepts are really a fundamental
parts of programming.
Now, let’s move to learning about grouping values.
So, a lot of times in programming there a lot of single
values relate to each other.
The perfect example is latitude and longitude values.
They often are used together ,so it’s logical that we will
group them together.
The most basic way to do that is to use an array.
Array is just a list of single values grouped together in sequence.
Let’s see some examples:
If you look at code examples from our last class (it’s class no.2):
http://kubakonczyk.com/members/introduction-to-web-development-for-gis-professionals/
And specifically example from map_app7.html line 17 you will see something like that:
mymap.setView([51.505, -0.09], 12);
And here’s the bit we’re most interested in:
[51.505, -0.09]
This is our array of latitude and longitude.
Easy, right?
Another way to group values is to create an object also called a dictionary.
When you look at line 26 of our example you will see something like that:
var osm = new L.TileLayer(osmUrl, {minZoom: 8, maxZoom: 13, attribution: osmAttrib});
You can identify the object by curly brackets:
{minZoom: 8, maxZoom: 13, attribution: osmAttrib}
So, this kind of grouping is a little bit different since we’re grouping
values using keys. Here we don’t care about the order of values. As long
as you define your keys and corresponding values to those keys you’re golden:)
Let’s break it down:
Our keys are: minZoom, maxZoom, attribution
Our values are: 8, 13, osmAttrib
An object is just like an index at the back of a book. You have words or phrases
as keys and page numbers as values.
When you should use an array and when an object?
Well, a lot of times an APIs like Leaflet’s API that we’re using in our example will tell you what to
use when.
In our first example Leaflet’s setView requires you to use an array as first argument. If you use an
object you will get an error.
Same goes for L.TileLayer in our second example, the second argument has to be an object with
specific keys. Otherwise you won’t be able to create a raster layer.
Ok, so let’s recap:
There are two most popular way to group single values in programming.
Using an array or an object.
And array is an ordered list of single values.
An object is an unordered dictionary of keys and values.
Different parts of an API will require you to use arrays or object in different situations.
That’s it!
If you have any questions about what we’ve covered so far leave me a comment down below:)
In the next part, we will talk about functions, methods and objects (yes, I know we’ve already
covered objects,but next we will talk about more complex objects).
Stay tuned:)