JavaScript if, for and functions
Write a condition, a loop and your own function.
All lessons · JavaScript lessons: learn from scratch
if: a condition
if is a decision. If the condition is true, the lines inside run.
const age = 18;
if (age >= 18) {
console.log("open");
} else {
console.log("closed");
}for: repeat
for repeats the same work a set number of times. This example prints 1, 2 and 3.
for (let n = 1; n <= 3; n++) {
console.log(n);
}function: your own command
function ties a job to a name. Then you call that name.
function add(a, b) {
return a + b;
}
console.log(add(2, 5));Questions
What is the difference between if and else? if runs when the condition is true, else when it is not.
When do I need for? When the same command must run several times.
What does return give back? The result of the function. add(2, 5) returns 7.
const or let? const does not change later, let can change.