import line from './assets/straight_line.png'; import conditional from './assets/conditional.png'; import forLoop from './assets/for_loop.png'; import whileLoop from './assets/while_loop.png';
JavaScript executes a program from top to bottom in order.
- We will very often need a program to do things conditionally.
- The
condition
must always evaluate totrue
for the code inside of the{}
to actually run.
if (condition) {
// do something
}
let number = 20;
if (number > 16) {
console.log('Hold');
}
let number = 20;
if (number > 16) {
console.log('Hold');
} else {
console.log('Hit me');
}
Turn the following sentences into valid JavaScript if
statements. Use console.log() to "announce" an action.
// 1. If it rains, I stay home.
let currentWeather = 'rainy';
// 2. If I am hungry, I eat.
let hunger = true;
// 3. If it's 10pm, I go to bed. If not, I write code.
let currentHour = 22;
Here is a program that outputs all even numbers between 0 and 12.
console.log(0);
console.log(2);
console.log(4);
console.log(6);
console.log(8);
console.log(10);
console.log(12);
This is Repetitious, but manageable...
Here is a program that outputs all even numbers between 0 and 1000.
console.log(0);
console.log(2);
// ... on and on and on...
This is where loops come in!
let number = 0;
while (number <= 12) {
console.log(number);
number = number + 2;
}
// let's break that down.
Let's write a function that outputs 2^10 (two to the power of ten).
// Example
Using while
is MUCH better than the repetition that we had before, but it is not great.
We still need to
- define a counter
- define the condition for loop to run
- increment that counter, everytime the
while
loop runs
I wonder if there is a shorthand for
this? 😉
for (let number = 0; number <=12; number = number + 1) {
if (number % 2 === 0) {
console.log(number);
}
}
// let's break that down.
false
.
- If you write a
for
loop that always evaluates totrue
, your loop will continue forever. - This is a bad thing... it will crash your environment (browser window, node env, etc.).
- To fix it, you will need to force-quit the environment.
Write a program that output all of the numbers from 0 to 25
// code here
Write a program that output all of ODD the numbers from 0 to 25
// code here
Write a program that output all of the numbers from 0 to 25, but replaces all multipes of 5
by the phrase five alive!
// code here