Beginning AngularJS

(WallPaper) #1

ChApter 1 ■ JAvASCrIpt You Need to KNow


You might consider the while loop to be a less structured version of the for loop. Indeed, you can happily
program in JavaScript, forever ignoring the while loop by exclusively using the for loop. However, you will come
across many situations in which using a while loop can be very convenient and much more concise.


Conditional Statements

Conditional statements allow you to implement “fork in the road” logic. That is, JavaScript can execute a statement, or
statements, if a specified condition is true. You can also execute a statement, or statements, if this condition is false.
Is this user logged in? Yes? Let him/her see this data. No? Then send him/her to the login page. Listing 1-24
demonstrates how to write this kind of logic in JavaScript.


Listing 1-24. JavaScripts if/else in Action


<!DOCTYPE html>




JavaScript Primer





By assigning false to the userIsLoggedIn variable, we are setting up a pretend user that we can consider to be not
logged in, just so we have something with which to work. Next is the if(userIsLoggedIn) portion of the code. The
if statement expects whatever expression or variable is placed between these parentheses to evaluate to either true
or false. It will only execute the code in the associated code block if it finds a value of true. Should it find a value of
false, it will execute the block of code within the else statement.
I hope the following results will make perfect sense.


Sorry - access denied


You do not have to provide an else statement if your program doesn’t require it. Also, you can nest if and if/
else statements inside of each other. Listing 1-25 demonstrates both of these ideas.

Free download pdf