JavaScript

Learning JavaScript: Functions

Learning JavaScript: Functions

I’ve tried to understand how jQuery works in the past and have had little success, not actually knowing the basics of JavaScript. Time for me to bite the bullet and finally learn it! I’ll look at functions first…

Previously, I’ve always needed to create something in a hurry for a project, which therefore doesn’t provide a very good learning experience as I usually just have to grab snippets and run with them. So I’ll take a step back, learn JavaScript first and then hopefully the jQuery library will seem like a breeze. Let the journey commence…

Please note: This article is subject to constantly change as and when I learn more!

Introduction to functions

A function can be thought of as a process which can be run over and over again to save on writing endless amounts of code.

While following the lessons on Codecademy, they gave the analogy that functions are like baking cakes – now this I can understand!

  • Arguments (the ingredients) are passed into a function (the baking process);
  • We can change the ingredients we put into a cake each time we bake it, but the way it is baked always follows the same process (okay, this may not be entirely true in real life!);
  • The function returns a result (a baked cake comes out).

Syntax

This is how a function is constructed, and I shall explain how it works below:

JavaScript

// Create the function
var functionName = function(parameter) {
	// Code that the function runs goes here...
};

// Call the function and pass in parameters
functionName(argument);
  1. On line 1, the function is defined as a variable and given a name (functionName can be changed to what you want to call it);
  2. Still on line 1, a parameter name is added in parentheses ( ) – it can be given any name. This is the ‘ingredient’ I mentioned in the analogy above, and multiple ones can be added here separated by commas ,;
  3. On line 2 within the curly brackets { }, this is where the reusable instruction code goes – it can take up as many lines as needed. Each instruction should be followed by a semi-colon ;;
  4. On line 3, the function is closed with a curly bracket } and followed by another semi-colon ;;
  5. On line 4, this is where the argument(s) is passed into the function. The function name is followed by the parameter value in parentheses ( ).

That description might have been a little abstract, so I’ll try it with a simple example…

Simple example: Function returns a printed phrase

In this example, I want the function to tell me what ingredients I am adding to a mixture so I can bake a cake.

JavaScript

// Create the function
var bakeCake = function(ingredient) {
	console.log("You have added " + ingredient);
};

// Call the function and pass in parameters
bakeCake("chocolate chips");

Result

"You have added chocolate chips"
  1. On line 1, the function is defined as a variable and given the name bakeCake;
  2. Still on line 1, the parameter name ingredient is added within parentheses ( );
  3. I want the function to print a phrase, so inside the curly brackets { } on line 2 I have added console.log and a phrase within the curved brackets ( ). I want the phrase to say “You have added ingredient, where the value for ingredient is fed into the function from elsewhere. The string of text is surrounded by quotes " ", then + is added to indicate that something else will be added to the printed phrase. The parameter name (ingredient) is added, the brackets closed and followed by a semi-colon ;;
  4. On line 4, the argument is passed into the function. In this case I have added chocolate chips;
  5. When the function is run, the phrase "You have added chocolate chips" will be printed.

Function with no parameters

Parameters don’t have to be passed into a function, they can just be created and called as shown in my following example.

This function will return the printed phrase "You have baked a cake!" when called. As there are no parameters, there is no way to personalise it.

JavaScript

// Create the function
var bakeCake = function() {
	console.log("You have baked a cake!");
};

// Call the function with no parameters
bakeCake();

Result

"You have baked a cake!"

Returning a value

In my previous example I was just printing the result that came out of the function. Instead of printing it, the value can be returned and used in other code.

I have created a simple example below of how a value can be extracted from the function and used further. The function I have created finds the length of a person’s first name. The result of the function is returned and saved as a variable, and the variable result is then printed. I have added an explanation of how it works underneath the markup:

JavaScript

// Create the function
var findLength = function(firstname) {
    return firstname.length;
};

// Pass a value into the function and save it as a variable
var nameLength = findLength("Michelle");

// Print the value of the created variable
console.log(nameLength);

Result

8
  1. On line 2, the function is defined as a variable called findLength and a parameter name of firstname is added within the parentheses;
  2. On line 3 within the curly brackets { }, the length of the value of the parameter is returned;
  3. On line 7, a new variable called nameLength is created. This variable calls the function and runs it with the argument (I have put my own name) then saves the result;
  4. On line 10, the value of the variable we just saved will be printed. In this case, the printed result will be 8, which is the length of my name.

Functions with multiple parameters

Multiple arguments can be passed into a function. I found a good example on Codecademy which I shall provide below; it is a function to calculate the perimeter of a rectangle. The perimeter of a rectangle is calculated by adding together the length of each of its four sides, so this calculation is to be carried out by the function when it is called.

The function will take in two arguments: width and length. the function will return the value of length multiplied by two and add that to the value of width multiplied by two. The function is then called and arguments added. The result is printed.

JavaScript

// Create the function
var perimeterBox = function(length,width) {
	return (length*2) + (width*2);
};

// Call the function, pass in parameters and print the result
console.log(perimeterBox(10,20));

Result

60
  1. On line 2, the function is defined as a variable called perimeterBox and two parameter names are added within the parentheses separated by a comma ,: length and width;
  2. On line 3 within the curly brackets { }, the value of the length parameter is multiplied by two and added to the value of the width parameter multiplied by two and the result is returned. Each of the calculations are surrounded by brackets ( ) – this ensures that those calculations are carried out independently first before anything else is done with them;
  3. On line 7, arguments are passed into the function and the result is printed. There needs to be two arguments separated by a comma , added in the order which they are stated in the function, so the value for length is the first number and the value for width is the second.

Using if/else statements with a function

When a value is returned from a function, it can be passed into an if/else statement.

In my simple example below, let’s assume my computer won’t let me access it unless I enter my own name. The function will return the name entered and pass it into an if/else statement. If the name entered is "Michelle", "Correct" will be printed. If anything else is entered, "Try again" will be printed.

Some naughty guy called Dave tried to access my computer, so he was denied in this case.

JavaScript

// Create the function
var logIn = function(username) {
	return username;
};

// Check to see if the username is "Michelle"
if (logIn("Dave") === "Michelle") {
  console.log("Correct");
} 
else {
  console.log("Please try again");
}

Result

"Please try again"
  1. On line 2, the function is defined as a variable called logIn and a parameter name of username is added within the parentheses ( );
  2. On line 3 within the curly brackets { }, the argument passed into the function is returned;
  3. On line 7, an if/else statement is started. On this line within parentheses ( ), the function name is called followed by the parameter value within an additional set of parentheses (Dave has entered his name here) and surrounded by quotes " " as it is a string of text;
  4. Continuing on line 7 are three equals signs === and my name ("Michelle") followed by an open curly bracket {. This whole line is basically saying that if the parameter value is equal to "Michelle", do the following action within the curly brackets { };
  5. On line 8 The text string "Correct" is printed when the argument is equal to "Michelle";
  6. Lines 10-12 show the else statement containing a printed text string "Try again" which will run if the parameter value is not equal to "Michelle".

Functions and scope

Scope refers to variables being either inside or outside of a function:

  • If a variable is within a function, it is said to have local scope, and cannot then be accessed outside of it;
  • If a variable is outside of a function, it is said to have global scope, and can be accessed throughout the code.

I have created an example below that illustrates how a local variable can be made global. I’m going to create a variant of my cake baking function I was using earlier; with this one, I’m going to print out a list of multiple ingredients that go into making my cake.

JavaScript

// Declare the variable with no value
var ingredientsAdded;

// Create the function
var bakeCake = function(ingredient1,ingredient2,ingredient3,ingredient4) {
	ingredientsAdded = "You have added: " + ingredient1 + ", " + ingredient2 + ", " + ingredient3 + " and " + ingredient4;
};
     
// Call the function and pass in parameters
bakeCake("flour","sugar","eggs","chocolate chips");

// Print the value of the variable within the function
console.log(ingredientsAdded);

Result

"You have added: flour, sugar, eggs and chocolate chips"
  1. On line 2, a variable is declared, given the name ingredientsAdded, and no value is added. This line will ensure that this variable will remain global even if it is added into a function and given a value;
  2. On line 5, the function is defined as a variable called bakeCake and four parameter names (which will be the ingredients) are added afterwards within parentheses ( );
  3. On line 6, within the bakeCake function, the ingredientsAdded variable that was declared on line 2 is changed from having no value to having a value. I don’t need to add var before the name, as we already know it is a variable from line 2, so just adding its name is enough, followed by the new value;
  4. Still on line 6, the new value for ingredientsAdded is defined following an equals sign =. The variable will equal the phrase “You have added:” and a list of the parameter values separated by commas;
  5. On line 10, the function is called and arguments to be passed into the function are added within the parentheses ( ). The strings "flour", "sugar", "eggs" and "chocolate chips" are passed in. Each value is followed by a comma ,;
  6. On line 13, the value of the variable ingredientsAdded is instructed to be printed. Because I declared the variable globally, I can call it from here. The string that will be printed is "You have added: flour, sugar, eggs and chocolate chips".

Argument types

Suppose that I want to carry out my cake baking function, and instead of an ingredient name as a string, someone inputs the number 2. 2 isn’t an ingredient and certainly won’t help us to make a cake. So what can be done to stop this?

In the example below, a line of code has been added that checks for the type of agument input into the function. Then if that type of value hasn’t been input, a certain action is carried out. If the correct type of parameter value has been input, the function runs as normal.

In my example, I am checking to see if the input argument is a string. If anything else is put in here, "You can't put that into a cake!" is returned. If a string is input, the function runs as normal and the string "You have added (ingredient)" is returned.

JavaScript

// Create the function
var bakeCake = function(ingredient) {
	// Check if the parameter value is a string
	if (typeof(ingredient) != 'string') return "You can't put that into a cake!";
	// If the parameter value is a string
	return "You have added " + ingredient;
};
     
// Call the function and pass in parameter
console.log(bakeCake(2));

Result

"You can't put that into a cake!"
  1. On line 4 within the function, the parameter name (ingredient) is referenced with an if statement and checked if it is a string. If it isn’t, "You can't put that into a cake!" is returned;
  2. Line 6 states what the function should do if the correct type of parameter value is fed in, which in this case is to return the string "You have added (argument)";
  3. On line 10, the bakeCake function is called and the result printed. 2 has been added in as the argument which obviously isn’t a string, so the function will print out "You can't put that into a cake!".