Most programming languages have data types, such as arrays and objects, that are designed to hold sets of data. JavaScript is no different! In this lesson we will learn about JavaScript index arrays and objects.
For more information on sets, watch my freeCodeCamp video:
Logic for Programmers - Set Theory.
A key points to a particular value in a set. We use it to access the value it points to.
If you do not specify the names of your keys, they will automatically be indexed using numbers. The first value in the set with have an index of 0.
Say we have an array that stores metal bands. Out of that set, we want to access "Slipknot". To access "Slipknot", we can reference it's key.
Let's declare an index array called soMetal.
// declare soMetal array
var soMetal = ["Metallica","Megadeth","Slipknot","Korn"];
In the example above, we did not specify keys. The elements contained in soMetal are indexed. That means the keys are {0,1,2,3}
var soMetal = ["Metallica","Megadeth","Slipknot","Korn"];
var slipknot = soMetal[2];
"Slipknot" is the third element in soMetal, so it is indexed at 2.
We can access it's value with: soMetal[2]
0: Metallica
1: Megadeth
2: Slipknot
3 - Korn
Another variable that stores sets of data is called an object. An object's keys are often refered to as "properties".
var band = {name:"Slipknot", type:"new metal", bestSong:"Custer"};
The object band has 3 properties: name, type, and bestSong.
var band = {name:"Slipknot", type:"new metal", bestSong:"Custer"};
var type = band.type;
The variable type points to the value "new metal".
A constructor is used to define a certain type of object and usually starts with a capital letter.
function Band (name,type,bestSong){
this.name = name;
this.type = type;
this.bestSong = bestSong;
}
// Band Constructor
function Band (name,type,bestSong){
this.name = name;
this.type = type;
this.bestSong = bestSong;
}
// Declare a Band type object
var megadeth = new Band("Megadeth","Heavy Metal","Peace Sells");
var megadeth = new Band("megadeth","Heavy Metal","Peace Sells");
var keys = Object.keys(megadeth);
console.log(keys);
Object.keys will return an array of keys.
function Band (name,type,bestSong){
this.name = name;
this.type = type;
this.bestSong = bestSong;
}
var metallica = new Band("Metallica","Heavy Metal","Master of the Puppets");
var megadeth = new Band("megadeth","Heavy Metal","Peace Sells");
var slipknot = new Band("Slipknot","New Metal","Custer");
var korn = new Band("Korn","New Metal","Falling Away");
var bands = [metallica, megadeth, slipknot, korn];
console.log(bands);
candy@cc:~/ccProjects$node bands.js
[ Band {
name: 'Metallica',
type: 'Heavy Metal',
bestSong: 'Master of the Puppets' },
Band {
name: 'megadeth',
type: 'Heavy Metal',
bestSong: 'Peace Sells' },
Band {
name: 'Slipknot',
type: 'New Metal',
bestSong: 'Custer' },
Band {
name: 'Korn',
type: 'New Metal',
bestSong: 'Falling Away' } ]