Skip to content

Instantly share code, notes, and snippets.

@gonewayword
Forked from anonymous/index.html
Created August 29, 2016 00:43
Show Gist options
  • Save gonewayword/38fe2ea0a148ae56d2c95b2712e26152 to your computer and use it in GitHub Desktop.
Save gonewayword/38fe2ea0a148ae56d2c95b2712e26152 to your computer and use it in GitHub Desktop.
Loop de LoopsHere we go round the prickly pear// source http://jsbin.com/tipiga
//Loops: While, for, for-in
//Loops are a great way to access, manipulate, output or otherwise deal with
//a set of information in different ways. There are different types of loops
//that are ideal for accessing different things.
//A for loop loops through a block of code a certain number of times.
for(i = 0; i <= 5; i++) {
console.log(i);
}
for(i = 5; i >= 0; i--) {
console.log(i);
}
//The above code loops through the numbers 0 through 5, inclusive. The first for loop
//does it 0 through 5, and the second does it backwards. As is, this code simply loops
//through numbers, but this index (i) number can become a stand-in for other parts of your
//code, allowing your loop to manipulate or handle other aspects of your program. For an example,
//here's a loop over a populated array:
var favoriteMovies = ["2001: A Space Odyssey", "Come and See", "Through a Glass Darkly", "Antichrist", "Irreversible"];
for(i = 0; i < 5; i++) {
console.log("One of my top five favorite movies is" + " " + favoriteMovies[i]);
}
var favoriteMovies = ["2001: A Space Odyssey", "Come and See", "Through a Glass Darkly", "Antichrist", "Irreversible"];
for(i = 4; i > -1; i--) {
console.log("One of my top five favorite movies is" + " " + favoriteMovies[i]);
}
//Loop over an Object, forwards and backwards ( hint: keys = Object.keys(myObject); )
var Jeremy = {
type: "psychiatry grad student",
mood: "Reserved and thoughtful",
age: "30 something",
}
for (var prop in Jeremy){
console.log(Jeremy[prop])
};
for (var prop in Jeremy){
console.log(Jeremy[prop])
};
for (var prop in Jeremy){
console.log(Object.keys(Jeremy).reverse());
};
//There is also the while loop, which is essentially a loop combined with a conditional.
//It says to the interpreter: while x is true, do y.
while (i < 11) {
console.log("Soon we shall reach 10!!!!!!!!!")
i++;
}
//Finally, there is the do/while loop. This is essentially the while loop, but with
//the command placed before the while--this means that the command in the do block will always
//be executed at least once, as it occurs first. This is a useful way to ensure that your loop
//command will execute at least once, if you need it to, and then may either continue or stop
//depending on the conditional.
do {
console.log("The number is " + i);
i++;
}
while (i < 10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment