Skip to content

Instantly share code, notes, and snippets.

@raineorshine
Last active December 15, 2015 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raineorshine/5183475 to your computer and use it in GitHub Desktop.
Save raineorshine/5183475 to your computer and use it in GitHub Desktop.
Looping over Objects vs Arrays in Javascript (Beginner)
// 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