This document discusses JavaScript control statements (loops). It covers the increment and decrement operators, for loops, while loops, and examples of each. The increment operator (i++) increments a variable by 1, and the decrement operator (i--) decrements a variable by 1. A for loop allows initializing a counter variable, testing a condition, and incrementing/decrementing on each iteration. A while loop runs a code block repeatedly as long as a condition is true. Examples demonstrate looping through arrays and incrementing/decrementing variables with for and while loops.
3. 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
4. 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
5. Decrement Operator
The 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
6. 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
7. The For Loop
for(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
8. 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.
9. 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]);}
11. While Loops
while(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
12. While Loops II
var n = 0;
while(n < 3) { console.log(“Looping,”);
n++;}
// Will print looping 3 times
Looping…
looping…
Looping…