JavaScript if Statements 1

[Pages:2]JavaScript if Statements 1

One of the things that make JavaScript and programming languages useful in general is the ability to have an if statement or conditional statement. A conditional statement is something that evaluates to true or false. This allows a program to branch or take a "fork" in the road. You can also have an if statement part of an if-else statement. With that, you execute the if part if the condition is true and the else part if the condition is false.

As an example I've created a function called evaluateAge (see below). The user is asked to enter their age, and if they are 21 or older, it will tell them that they can drink. If they aren't, it tells them they can't drink. You should be careful that all your names for everything in your page are unique. You don't want to have a function with the same name as a form or button. This can cause very hard to locate problems when you are trying to debug your code.

If you look at the function below, you should note that the variable userAge is a local variable. What this means is that this variable only exists within the body of the function. Once the function is done executing, this variable is discarded and is no longer accessible. A global variable is the opposite of a local variable. It's accessible from anywhere inside the function and exists as long is your page is loaded in the web browser.

With the function below, we are asking the user for their age, storing it in the variable userAge, then using the if statement to check if the age input is greater than or equal to 21. In order to call the function, I have a button (b0) that calls the function for onclick.

Source code

var counter //global variable

function evaluateAge ( ) {

var userAge //local variable userAge = prompt ("Please enter your age", "") /* > -greater than

< -less than == -equivalent >= -greater than or equal to = 21) { alert ("You can drink") } else { alert ("No beer for you") } }

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download