- About Javascript
- Javascript Basics
- Strings, Arrays and Objects
- Control Structures
- Functions, Scope and Closures
- Object Functions, Constructors and Prototypes
- Javascript Next
Example code based on
LearnXinYminutes
and licensed under
CC Attribution-Share 3
Control Structures
Conditional Statements
As mentioned, Javascript's syntax is similar to Java's, especially their control structures.
// If statement
var count = 1;
if (count == 3){
// evaluated if count is 3
} else if (count == 4){
// evaluated if count is 4
} else {
// evaluated if it's none of the above
}
// switch statement
// checks for equality with ===
// use break after each case or the cases after the correct one will be executed too.
grade = 'B';
switch (grade) {
case 'A':
console.log("Great job");
break;
case 'B':
console.log("OK job");
break;
case 'C':
console.log("You can do better");
break;
default:
console.log("Oy vey");
break;
}
This prints to console:
OK job
Loops
// While(condition) statement
while (true){
// An infinite loop. Don't do this!
}
// Do-while loops are like while loops, except they always run at least once.
// Here's an example usage:
var input;
do {
input = getInput();
} while (!isValid(input))
// Javascript has a messy for-each loop situation, so for now, you can just use for loops:
// For loops
// initialization; continue condition; iteration.
for (var i = 0; i < 5; i++){
console.log("Number " + i);
}
The for loop will print to the console:
Number 0 Number 1 Number 2 Number 3 Number 4
Challenge
What will the above Switch case output if grade
was 'a'?
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Challenge
Try some FizzBuzz, the classic basic programming challenge.
Write a program that prints the numbers from 1 to 50, but for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
Note: Use print()
to print output with a newline. Make sure you print "FizzBuzz" together.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.