Blog of Jeff A blog about programming and random other things.

16Jun/09link

“Brief” Guide to JavaScript – Part 2

Branching (Conditionals)

Majority of the time we want some logic in our code to figure out things to do. We don't want to attempt to hammer a nail if we don't have a hammer. Conditionals allows our programs to make decisions based the validity of a certain conditions.

If Statement

The simplest of all branching is the if statement.

if (expression){
    // code block
}

expression is a value that resolves to a boolean value: true or false. If false, the code block is skipped (not executed). True will execute the code block. But since JavaScript doesn't have strict data types there are some auto-converting done for you:

  • undefined, null, false, 0, NaN, empty string ('') convert to a false
  • everything else is true.

Here are some examples of various if statement examples:

var myvar = 'hello';
if (myvar){
    // the line below will be executed
    myvar = "truthy";
}

var myotherval = 0;
if (myotherval){
    // the line below will NOT be executed (expression evaluates to false)
    myotherval = 43;
}

More Expressions

Of course usually we want expressions that are more useful than the above. We can compare two values (or variables) using the following comparisons:

  • var1 == var2, compares if var1 equals var2. Returns true if equal and false if not. This auto converts types (so '0' == 0 is true)
  • var1 === var2, compares if var1 equals var2. Returns true if equal and false if not. This does not auto convert types ('0' === 0 is false).
  • var1 != var2, checks if var1 does not equal var2. Returns true if not equal and false if equal. This auto convert types ('0' != 1 is true).
  • var1 !== var2, like !=, but doesn't auto convert types.
  • var1 < var2, checks if var1 is less than var2, true if that's the case, false if otherwise.
  • var1 <= var2, like < operator but is less than or equal.
  • var1 > var2, like < operator but is greater than.
  • var1 >= var2, like < operator but greater than or equal.
  • expr1 || expr2, checks if expr1 or expr2 evaluates to true. If expr1 evaluates to true or expr2 evaluates to true, then || returns true, otherwise false.
  • expr1 && expr2, checks if expr1 and expr2 evalute to true. If expr1 is true and expr2 is true, then && returns true, otherwise false.

For || and &&, it's best to surround the expressions in parenthesizes () for visual clarity and ensure expressions are evaluated as you intended. For example:

a == b && c != d || e < f


Is pretty hard to figure out how the expression evaluates given the values for each variable. Heck, I don't even know. That's because it could be broken down to (expr1 && (expr2 || expr3)) or ((expr1 && expr2) || expr3). So using parenthesizes are good:

(a == b && c != d) || (e < f)


As a side note, since expressions are evaluated to a boolean value, you can assign a variable to an expression:

var var1 = (0 < 5); // true

&& || Oddity

The AND and OR statements (&& ||) behave slightly differently that I explained above (to keep it simple). In reality, values are returned. 2 && 3 is truth-y, but it actually evaluates to (The last value that the JavaScript engine checked). This works similarly to OR.

In comparison to most programming languages, this is an usual behavior.

Here's some more examples and their results:

2 || 3 => Returns 2

0 && undefined => 0

0 || undefined => undefined

0 && 1 => 0

0 || 1 => 1

Single-Statement If

If you only have one statement for the if statement block, you can exclude the curly braces {}:

if (expression)
    statement;


But beware, any other statements won't be in the if statement. It's best to avoid using this if you're new to programming (to prevent you from hours of headaches). Proper spacing helps you figure it out at a glance:

if (expression)
    statement;
statement;
statement;

It's clear from the spacing to see which statement is only executed if the if statement is true.

Elses, Else If's statements

Say you want to do something else if the first IF statement doesn't evaluate to true. That's what else if and else statements are for. They extend if statements, meaning they are appended after the if statement.

if (expression1){
    // codeblock 1
} else if (expression2){
    // codeblock 2
} else {
    // codeblock 3
}

If the expression1 is true then the two else codeblocks (2 & 3) are skipped. If expression1 is false then it moves on to the else if, evaluates to expression2. If expression2 is true, then the codeblock 2 is executed (and the other codeblocks are skipped). If both two expressions are false, then codeblock 3 is executed.

Else and else if statements are always optional (not required for if statements) and you can have multiple else if statements. If you use else and else if statements, else should always be at the end.

Ternary Operator

Sometimes you'll want and extremely concise if-else statement. There's even a shorter one-liner method that is formatted as:

expression ? true_statement : false_statement

Several use cases are for variable assignments:

// Using parenthesis makes it easier to read
(b == c) ? (a = 3) : (a = 2);
// alternatively (also works)
var a = (b == c) ? (3) : (2);
// both above are equivalent to
if(b == c)
    a = 3;
else
    a = 2;

Repetition (Loops)

Sometimes you'll do things that is repetitive or operations that need to repeat until a certain condition is met. That's where we can utilize loops.

While

While loops continuously execute a given code block provided that an expression evaluates to true.

while (expression){
    // codeblock
}


Usually the codeblock modifies a value that affects expression, otherwise you get something like this:

while (true){
    // codeblock
}

Which loops to the end of time. Not so good. Luckily, most browsers will warn you of this after some time.

Firefox dialog when the script runs for awhile. Usually a infinite loop issue.

If the while statement is false, the code block is not executed. This includes if the code block was never executed to begin with.

Do

If you want your while loop to always execute at least once, you can do something like this:

var first = true;
var counter = getSize(); // pretend function
while(first || counter > 10){
    // do stuff
    counter++;
    first = false;
}


But you can use do to simplify your code:

var counter = getSize(); // pretend function
do {
    // do stuff
} while(counter > 10);

Although I'll admit, do is less common as while or the next looping construct we'll talk about.

For

A common use of while loops is a counter-style method.

var i=0;
while(i < 20){
    // code here
    i++; // increments i by 1
}


For brevity, we can use the for loop to do the same thing:

for(var i=0; i<20; i++){
    // code here
}


For loops are basically broken down into this:

for(statement1; expression; statement2){
}


statement1 is executed before the loop begins. expression is checked before every loop (to see whether or not to run the code block. statement2 is executed after the code block finishes executing. It's worth noting that your variable that you use in the for loop overrides any value you set it before the for statement.

var i=22;
for(var i=0; i<5; i++){}
// i = 5

For historical & convenience reasons, i, j, and k are usually used as loop variable names.

Technically, you can have the statement slots empty, effectively making the for loop a while loop:

for(;val == 'loop'; ){/* do stuff */}

Edit: Part 3 is available.


That wraps it up for this week. Next week, we’ll cover some basics of scopes and functions.

  • Share/Bookmark
blog comments powered by Disqus

Recent Posts

Topics

Archives

Following

Links