Functions and Conditionals

Thu, Sep 18, 2014

Conditionals

One of the hallmarks of programming is the conditional operator. It gives the programs the ability to logically assess a variable, and decide a course of action depending on the result.

We use these operators to find out if a particular condition is true, and to pick a course of action depending on the result.

Conditinal operators use the keyword if to find out if a certain condition—which is surrounded in parenthesis—is true or false. If the condition is true, then code that is surrounded by curly brackets is executed. Here is an example:

var score = 5;

if(score == 10){
    document.write("Congratulations! you won");
}

In the above example, we are assessing the condition x == 10 to see if this is true. The double-equals symbols is the equivalency operator, and checks to see if both sides of the equation are equal. This is different than the single-equals symbol, which is the assignment operator, and performs a different action of assigning a value to a variable.

In the above example, the code within the curly brackets would not execute, because the value score is not 10, and the condition was not true. So, our program would skip over the code in the curly brackets.

Here are some possible operators that can be used to establish conditions:

Operator   Description
== Equivalency Operator. Checks whether both sides are equal.
!= Bang Operator. Checks whether both sides are not equal.
> Greater than. Checks whether the left side is larger, but not equal to, the right side.
< Less than. Checks whether the left side is smaller, but not equal to, the right side.
>= Greater than or equal to. Checks whether the left side is greater or equal to right side.
<= Less than or equal to. Checks whether the left side is less than or equal to the right side.

Checking if value is more than or less than

In these examples, we check to see if the value is more than or less than another value. It’s important to note that all of these conditions will have either true or false result. If the condition is true, the code within the curly braces will be executed.

var x = 7;
var y = 10;

if(x > y){
    document.write("You win!");
}

In the above example, the value of x is not more than y, therefore, the code in the curly braces will not execute.

var age = 12;
var requirement = 12;

if(age >= requirement){
    document.write("You can ride the ferris wheel!");
}

In the above example, the code would be executed because the condition is true, age is more than or equal to the requirement variable. Else Statement

Sometimes you want some code to execute on when a condition is not met. We can optionally provide an alternative action using the else keyword, and a second set of curly brackets. Observe the following example:

var age = 20;

if(age >= 21){
    document.write("Have a beer!");
} else {
    document.write("Sorry, have a juice box instead.");
}

In the example above, the age variable is 20, which does not meet the condition of being more than or equal to 21. So the code inside the first set of curly brackets will not execute. The else statment provides an alterative when the condition fails, or is false. Negated Conditions

It’s important to remember that the program assesses the expression inside the parenthesis, to determine if it’s a true or false statement. This can be tricky at times, especially when using negated conditions. There is an operator called the not operator (also called a bang) that means “not equal to.” This is sometimes useful when you want to ensure the value can be anything but an equavalency. Observe the example below:

var answer = 3;

if(answer != 3.14){
    document.write("This is not pi");
}

In the above example, the expression evaluates to a true statement, answer is not equal 3.14, so the program will execute the code between the curly brackets. Evaluating multiple conditions

There are times when you want to check if multiple conditions exist. JavaScript, and many other programming languages, offer two operators for determining if multiple conditions exist, the AND operator, and the OR operator. The AND operator is signified by two ampersands, like so &&. The OR operator is sigified by two bar or pipe keys, like so ||. Symbol Description

Symbol  Description
&& AND operator. Checks if all conditions are true.
|| OR operator. Checks if either condition is true.

In the example below, we use the AND operator to check if two conditions are true.

var minimumHeight = 48;
var maximumHeight = 78;
var rider = 40;

if(rider > minimumHeight && rider < maximumHeight){
    document.write("you're tall enough to ride the ferris wheel");
}

In the example above, the code between the curly brackets will only execute if—and only if—both conditions are true. If one of them is false, the entire statement evaluates to false. The above example would not run, since the rider variable is not more than the minimumHeight, even through it is less than the maximumHeight.

The figure below shows and example using the OR operator:

var userResponse = "Maybe";

if(userReponse == "yes" || userResponse == "no"){
    document.write("Thanks for answering the question");
} else {
    document.write("Only yes or no responses are accepted");
}

In the example above, either condition can be true for the whole statement to be true. In situations where both conditions are true, the entire statement evaluates to true.

Below are some additional examples using the OR and AND operators:

if(x == 1 && y == 2 && z == 3){
    document.write("All three conditions must be true to see this text.");
}

if(x == 1 || y == 2 || z == 3){
    document.write("Any of the conditions can be true to see this text.");
}

Using Additional Parenthesis To Combine AND and OR operators

In situations where you want to use both AND and OR operators, you will need to specify the order of operations with additional parenthesis, like so:

if((x == 1 || x == 10) && (y == 1 || y == 6)){
    document.write("For this to be seen, x needs to be 1 or 10 and y needs to be 1 or 6.");
}

Empty Strings and Zero-value Numbers

There are a couple of idiosyncrasies to JavaScript and the way it assesses certain variables. If a string is empty, the variable it is assigned to will assess as false. Also, any number that has a zero value, will also result in a false condition when assessed. Consider the following example:

var emptyString = "";

if(emptyString == true){
    document.write("This text would only appear if the string had content.");
} else {
    document.write("Empty strings are false.");
}

The same is true of zero-value numbers, which will result as a false statement. It should also be noted that it is possible to assess a variable without using the equivalency operator. Putting a variable in the parenthesis will assess whether the variable is true or false. This is also a great method to check if a variable has a value.

var num = 10;
num = num - 10; //num is now zero

if(num){
    document.write("This text won't display since
            num is zero, and false");
} else {
    document.write("This text will display, since 
            num is zero, and thus false.");
}

Functions

A function is a block of code that is stored into memory to await execution at a time when the function is run. When we place code in a function, it is read by the program, but the code is not run immediately, but rather until we tell it to.

Functions in the examples below are given names that follow the same rules as variable names; no spaces or special characters (except underscores) and they are case-sensitive.

function myGreatFunction(){
    document.write("This will only be seen when the function is run");
}

In the above example, myGreatFunction stores some code that is setup to be run at a later time. A function is written starting with the keyword function in lowercase, followed by the function’s name. It is then proceeded by an opening and closing parenthesis. The body of the function, were the code is kept is surrounded by curly brackets.

You can run—or “call”— a function by referencing its name followed by parenthesis.

function myGreatFunction(){
    document.write("This will only be seen when the function is run");
}

myGreatFunction();

//output:
//This will only be seen when the function is run

One of the more common uses of functions is attaching them to events, like a mouse click. This way, we can run a block of code whenever a specific event occurs. Below is the <button> tag with a special attribute called onclick which will execute some JavaScript:

<button id="myButton" onclick="displayMessage()">Test this button</button>

<script>
function displayMessage(){
    document.write("You clicked the button!");
}
</script>

In the example above, you can see we’ve created a function called displayMessage. When the button is clicked, we execute the displayMessage function, displaying some text on the screen. Passing Data into a Function

The parenthesis in a function play an optional, but important role in the power functions have in JavaScript. We can optionally put a variable in the parenthesis, which allows us to pass data into the function when it’s called. This allows us to reuse functions for many different purposes, and have them operate differently depending on what data is pass in.

function displayMessage(message){
    document.write(message);
}

displayMessage("Hello World" + "<br />");
displayMessage("Show me the money!");

//output:
//Hello World
//Show me the money!

In the example above, we’ve called the displayMessage function twice, but each time we sent the function a different string of data. That data was passed in the message variable, and made available to us within the function. The variable used to pass in data is called the argument. Arguments do not need to be declared with the VAR keyword. It is also worth noting that arguments are not available outside the function, and only exist within the function call. (More on this later.)

We also have the ability to send multiple arguments of data to a function. We do this by separating them with acomma.

function greeting(name, location){
    document.write("Hello " + name + " from " + location);
}

greeting("Jeremy", "Berkeley");

//output:
//Hello Jeremy from Berkeley

Functions can also return data back to the place they were called. This is ideal in situations where we want to modify data quickly, and have it sent back. Observe the following example:

function addNumbers(num1, num2){
    var total = num1 + num2;
    return total;
}

document.write("7 plus 4 is " + addNumbers(7, 4));

//output:
//11

In the above example, we called the function addNumbers and sent it two piece of data: 7 and 4. The function added the numbers, then sent back the total using the return keyword. It’s important to note that we created a new variable, total, inside this function using the VAR keyword. This variable only exists within the scope of this function. If we tried to reference it elsewhere, we would get an error message or an undefined.

Below is another working example of passing data into a function, and returning the message:

function makeBold(str){
    return "<strong>" + str + "</strong>";
}

document.write("Some " + makeBold("text") + " where parts are " + makeBold("bold"));

//output:
//Some text where parts are bold

In the above example, we’ve designed a function that takes a string, and adds some <strong> tags around them, then returns the new text. We can reuse the function over and over by sending new data, each time it would convert it to bold.