learning-journal

Kyle's Learning Journal


Project maintained by AtkinsonKyle Hosted on GitHub Pages — Theme by mattgraham

Operators and Loops Notes

Comparison Operators Evaluating Conditions

Logical Operators

((5 < 2) && (2 >= 3))

Loops

Loops check a condition. If it returns true, a code block will run. The condition will be checked again and if still true, the code block will run again. It repeats until the condition returns false.

Common Types of Loops

  • For
    • Runs code specific amount of times. The condition is usually a counter which is used to tell how many times the loop should run.
  • While
    • Don’t know how many times loop should run. Condition doesnt have to be a counter, and code will continue to loop for as long as the condition is true.
  • Do While
    • Similar to while loop but it will always run the statements in curly braces at least once, even if condition is false.
for (var i = 0; i < 10; i++) {
    document.write(i);
}

Loop Counters

A “for” loop uses a counter as a condition. This tells the code to run a specified amount of times. Below you’ll see the condition is made up of three statements:

  • Initialization
    • var i = 0;
    • Create a variable and set it to 0. This variable is called i, and acts as the counter.
  • Condition
    • i < 10
    • The will run until it hits a specified number.
  • Update
    • i++
    • Every time the loop runs the content in the curly brackets it adds one to the counter.

While Loops


- var i = 1;     //Set counter to 1
- var msg = '';  //Message
// Store 5x table in a variable
while (i < 10) {
    msg += i + ' x 5 = ' + (i * 5) + '
'; i++; } document.getElementById('answer').innerHTML = msg;