Conditionals

Sometimes we want to only execute some code given some conditions. We can do this using a conditional statement. The most common form of this is the if/else statement:

if (expression) statement

This will only execute "statement" if the expression inside of the ()'s evaluates to "true". "statement" can be a compound statement (statements enclosed in {}'s, like:

if (expression) { statement1; statement2; etc; }

Sometimes we want to two (or more) different code paths depending on the result of the initial expression. We can do this with an "else" part to the if:

if (expr) statement1; else statement2;

This will execute statement1 if expr is true, or it will execute statement2 if expr is false. Either or both of statement1 or 2 can be compound statements:

if (expr) { statements; } else { statements; }

example:

// Make an "alias" for console.log() called "print" var print=console.log; // Make an "alias" for process.argv: var argv = process.argv; // Get a and b from the command line and convert them into integers: var a = parseInt(argv[2]); var b = parseInt(argv[3]); if (a < b) { print(a + " is less than " + b); } else if (a > b) { print(a + " is greater than " + b); } else { print(a + " is equal to " + b); }