Last active
December 15, 2015 01:58
-
-
Save raineorshine/5183475 to your computer and use it in GitHub Desktop.
Looping over Objects vs Arrays in Javascript (Beginner)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// looping over an array | |
var fruit = ["Mango", "Guanabana", "Mamoncino", "Piña"]; | |
for(var i=0; i<fruit.length; i++) { | |
console.log(fruit[i]); | |
} | |
// looping over an object | |
var students = { | |
// key : value | |
// access a value with object[key] | |
"raine": "A+", | |
"kristina": "A-", | |
"francis": "B", | |
"gene": "F" | |
}; | |
for(name in students) { | |
console.log(name + " has a grade of " + students[name]); | |
} | |
// What if you wanted to just check the existence of a single key in the object? | |
// Solution A: iterate through the object, check each one: not necessary! | |
// when you ask for a value of a key that doesn't exist in the object, you get | |
// undefined (which is actually a type in Javascript!) | |
students["samuel"] === undefined | |
// Solution B1: | |
if(students["samuel"] !== undefined) { | |
console.log("samuel exists!"); | |
} | |
// Solution B2: | |
if("samuel" in students) { | |
console.log("samuel exists!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment