Functions and Conditionals

Tue, Oct 13, 2015

Functions

A function is another data type, just like numbers, strings, booleans, arrays and objects. You can assign functions to variables, just like the other data types.

//example of an empty function assigned to a variable. This does nothing,
//it's just an example.
var someVariable = function(){ };

But what exactly is a function? It’s 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 executed immediately. Rather, it waits until we tell it to.

//A function that when called, will return a string with "Hello there"
var sayGreeting = function(){ return "Hello there"; }

This might seem confusing at first, especially when compared to other static data types like strings. It’s important to note that when we assign a function to a variable, we basically just make a special variable that has the ability to call the code in the curly braces. You call the function by using the parentheses characters.

var sayGreeting = function(){ return "Hello there"; }

//now run the function. This will output the string.
console.log(sayGreeting()); 

When the function is run, it returns some information — typically as a different data type. (This is the part that can be confusing). But this only happens when the function is run. For example:

var sayGreeting = function(){ return "Hello there"; }

var anotherVariable = sayGreeting();

//value of anotherVariable is the string "Hello there", 
//because that is what was returned.

Arguments

The parentheses have a special purpose, which is to include a variable called an argument. function(argument). This argument is passed into the function, and can be used as part of the return. Let’ take the following example:

var calculateTip = function(bill){ return bill * 0.20; }

calculateTip(10); //this will return 10 * 20%, or 2 dollars

We can see we have the argument bill which we can use in the function. This argument acts like a temporary variable whose value is determined when the function is run. This allows us to reuse the function numerous times to make multiple calculations.

var calculateTip = function(bill){ 
    return bill * 0.20; 
}

calculateTip(10);   //this will return 10 * 20%, or 2 dollars
calculateTip(100);  //this will return 20
calculateTip(1000); //this will return 200

Multiple Arguments

You can also specify multiple arguments, which can be passed into the function. We do this by separating them with commas.

var calculateTip = function(bill, tip){ 
    return bill * tip; 
}

calculateTip(10, 0.15);  //calculate a $10 bill with 15% tip
calculateTip(100, 0.10); //calculate a $100 bill with 10% tip
calculateTip(1000, 0);   //calculate a $1000 bill with 0% tip

It’s important to note that in the example above, the calculateTip() isn’t displaying the output anywhere. Normally we would do something with the returned result, like assign it to another variable, or output it onto the page.

Here is an example of writing a greeting onto the page:

var greeting = function(name, location){
    return "Hello " + name + " from " + location;
}

document.write( greeting("Jeremy", "Berkeley") );

//output to the page:
//Hello Jeremy from Berkeley

Above we’re using document.write(), which is a built-in function in the browser that allows us to output some text to the page. (Note: this is an archaic method of writing text to the page, typically we would use a JS library like jQuery or d3).

var makeBold = function(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.

Another way to write functions

On a rare occasion, you might see functions written in a different way where they are not assigned to a variable. These are called function declarations. They differ slightly in a fairly technical way. When a function is declared (not assigned to a variable) then it is read into memory before all other code. This means you can technically call a function before you even declare it! This isn’t possible with variables, where everything needs to be in order.

var functionOne = function() {
    // Some code
};
function functionTwo() {
    // Some code
}

//they both do the same thing
functionOne(); 
functionTwo(); 

In the above example, both methods are identical. We can specify function someName() to declare it, or we can assign an anonymous function to a variable var someVar = function().

Here is where they differ:

functionOne(); //gives an error, because it doesn't exist yet!
functionTwo(); //This is fine, because declared functions are read first

var functionOne = function() {
    // Some code
};
function functionTwo() {
    // Some code
}

If you’re curious about more ways to write functions, check out this StackOverflow article or this comprehensive article about named functions.

Variable Scope

There is another unique quality of functions, and that is an issue called variable scope. This is where variables you declare (create with var) within a function, only exist within that function.

var myCoolFunction = function(){
    var data = [1, 2, 3, 4]; //created an array variable
}

console.log(data); //ERROR! data variable doesn't exist outside the function!

Also, any argument variables only exist within that function.

var calculateTip = function(bill){
    return bill * .20;
}

console.log(bill); //ERROR! bill doesn't exist outside the function

Variable scope will become important later.

Functions as values inside objects

Remember that an object literal can store any data type. This includes functions.

var person = {
    name     : "Joe",
    age      : 25,
    greeting : function(){ return "Hello!"; }
}

person.name       //value is Joe as a string
person.age        //value is Joe as a number
person.greeting() //this runs the function, and returns the string "Hello!"

“this” keyword

One of the most confusing aspects of JavaScript function is the use of this keyword. Basically, there is a special variable called “this” which automatically exists inside every function. So, what is it’s value? The value of this is the object that called the function.

This makes the most sense when the function is a value of an object, like in the earlier example.

var person = {
    name     : "Joe",
    age      : 25,
    greeting : function(){
        console.log(this.name); 
        //this will output "Joe", because this refers to the parent object
    }
}

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.

Conditional 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.");
}