loops in javascript
TRANSCRIPT
Intro to Loops Continued
Diving Deeper into JavaScript Control Statements (Loops)
- Professor Flo Davis… Mwahaha
Increment/Decrement Operators
i++ is the same as i = i + 1;
i- - is the same as i = i -1;
Increment Operator Syntax x++ or ++x
//PostFix
var x = 3;
y = x++ // y =3, x=4
//PreFix
var a = 2;
b = ++a; // a = 3, b =3
Working Example https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators
Increment Operator Example
var x = 5;
x++;
var z = x;
console.log(z) // z = 6;
Working Example http://www.w3schools.com/js/tryit.asp?filename=tryjs_oper_increment
Decrement OperatorThe decrement operator subtracts
Syntax x - - or - - x
// Postfix
var x = 3;
y = x - - ; y = 3, x = 2
// Prefix
var a = 2;
b = - - a; // a = 1, b = 1
Working Example https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators
Decrement Operator Example
var x = 5;
x- - ;
var z = x; // z = 4
Working Example http://www.w3schools.com/js/tryit.asp?filename=tryjs_oper_decrement
The For Loopfor(initialize; test; increment/decrement) { // Code Block//}
Example Standard For Loop
for(var i = 0; i<10; i++){console.log(i);} // This will print the numbers from 1 through 10.
We use i, because that is short for index
For Loop Example (Decrement)
for(var i=10; i>5; i- - ){ console.log(i);}
REMEMBER: i++ or i - - is the same as i+=1, or i -=1, code what ever works for you best.
Looping Through An Array with For Loop
var Professor = [‘Florence’, ‘Davis’];
for(var i =0; i<Professor.length;i++){console.log(Professor[i]);}
// Let’s refactor code and make it cleaner
var Professor = [‘Florence’, ‘Davis’];
var length = Professor.length;
for(var i = 0; i<length;i++){console.log(Professor[i]);}
Oh…It’s Been AwhileWhile Loops
While Loopswhile(condition) {// statement}
Example var i = 0;
while(i<10){ console.log(i + ‘….. this will go on until we hit 10’);
i += 1; // same as i++ throwing you for a loop making sure your paying attention haha :) , remember they can be used interchangeably whatever you prefer.
If you need further explanations don’t forget our good friends at Mozilla: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while
While Loops IIvar n = 0;
while(n < 3) { console.log(“Looping,”);
n++;}
// Will print looping 3 times
Looping…
looping…
Looping…
–Johnny Appleseed
“Happy Coding.”