Introduction to Functions

Every line of javascript we write is called a statement, and when we write multiple statements together, we create a procedure.

An example of a procedure could be if... else statements, which we have covered previously.

javascript
	if (condition) {
	  console.log("Something");
	} else {
	  console.log("Something else");
	}

When we write javascript directly into a file or inside a <script> tag - the entire file counts as one procedure, running from left to right, top to bottom - this is what we call synchronous code.

This is very useful when starting with javascript; however, as the complexity of tasks increases, this becomes unsustainable. We need to define smaller, more manageable procedures, which are what functions are. Functions are groups of useful statements that combine into re-useable procedures to which we assign a name.

Functions are crucial to writing effective javascript, and they exist to make your code make more sense to you and others.

Understanding functions is essential, but it will take time to get used to them - that will happen as you use them more and more.

Here we only introduce them. In the JavaScript 1 course, we will look at them in more depth.


We have already been using functions, console.log() is a function and so are toLowerCase() and toUpperCase().

Our first function

To use a custom function, we first need to declare it.

Declaring a function means creating it. We use the function keyword and a name of our choice to declare it. Remember that a good function name is one that describes that task without someone needing to read the code to understand it.

javascript
	// declare the function
	function logWord() {
	  // the code we want the function to run goes here
	}

Above, we’ve declared a function called logWord.

Like other variables, functions can be called anything. Give your functions meaningful names, though, functions called hi or function1 are not well-named functions.

Don’t be afraid to use long names for functions if you can’t think of a short name. function logWordOneHundredTimes() is fine, as long as that’s what it does!

The contents of a function live between the curly braces { }. We don’t have any code there except a comment, so our function doesn’t do anything at the moment. We will look at the purpose of the parenthesis (round brackets) () a bit later.


Let’s make our function do something, log a string to the console:

javascript
	function logWord() {
	  console.log("one");
	}

The code inside the function won’t run until we call (or execute or invoke *) the function.

\* In programming, similar actions or techniques often have different names, which can be confusing when different names refer to the same thing. When we mention alternative names for things, it’s because that is what they might be called in other learning materials you may read or watch.

Without calling the function, the JavaScript engine knows about it but won’t execute the code inside the function.

We call a function using its name and round brackets ().

javascript
	// declare the function
	function logWord() {
	  console.log("one");
	}
	
	// call the function
	logWord();

Now the logWord function will run, and one will be logged to the console.

Notice that we don’t use the function keyword to call the function. We only use the function keyword when declaring the function.

Arguments

Our logWord function isn’t very useful at the moment, as it will always just console log the word “one”. We may as well have just written the console.log() out directly without declaring and calling a function.

We can make the function far more useful by passing variables into it so that the code inside the function can use them.

The variables that we pass into functions are called arguments. We place them inside the ().

When we call console.log("some value"); the value we want to log is an argument passed to the log() function.

Let’s add an argument called theWord to the logWord function:

javascript
	function logWord(theWord) {
	  console.log("one");
	}
	
	logWord();

The code inside the function is still just logging one, though.

We can use the variables we pass in, the arguments, inside the function just like any other variable. Let’s pass in a value as the theWord argument and then log that value:

javascript
	function logWord(theWord) {
	  console.log(theWord);
	}
	
	logWord("hello");

Run the code above, and you will see hello gets logged.

You will often hear about parameters. Technically, the values passed into the function are called parameters, and the variable names inside the () are called arguments. We will call both arguments for simplicity’s sake.

Change the value you pass in:

javascript
	function logWord(theWord) {
	  console.log(theWord);
	}
	
	logWord(50);

Now 50 will get logged.

Whatever you pass in as the value will get logged as long as you use the argument’s correct name.

javascript
	function logWord(theWord) {
	  console.log(theWord);
	}
	
	logWord(true);

true will get logged.

If we changed the code to this

javascript
	function logWord(theWord) {
	  console.log(word);
	}
	
	logWord("hello");

We will get an error, as the argument (the variable) is called theWord, but we are trying to log the variable word. The variable word doesn’t exist in this function.

Always make sure you are using the correct argument names in your function code.


Mulitple arguments

Functions can have zero, one or more arguments. Let’s write a function with two arguments:

javascript
	// declare a function with two arguments
	function AddTwoNumbers(number1, number2) {
	  let sum = number1 + number2;
	  console.log(sum);
	}
	
	// call the function and pass two arguments in
	AddTwoNumbers(3, 4);
	// 7

Returning from a function

To return a value from inside a function, we use the keyword return.

For example, we can return the sum variable from the AddTwoNumbers above like this:

javascript
	function addTwoNumbers(number1, number2) {
	  let sum = number1 + number2;
	  return sum;
	}

No code after a return keyword will run. As soon as a return keyword is encountered, the function will exit with the value provided.

javascript
	function doubleNumber(number1) {
	  let double = number1 * 2;
	  return double; // Execution stops here
	  console.log("This will never run");
	}

We can assign what is returned from a function to a variable like this:

javascript
	let result = addTwoNumbers(3, 4);

The purpose of calling a function is ultimately to change the state of a webpage or to perform a calculation.

When performing a calculation, the function must respond with the result once it has finished running. Otherwise, it will not be useful.

When changing state, a return value is not always necessary - however, it is a good practice to provide one anyway.

All functions return a value, even if that value is falsy like undefined, null, 0 or "".

javascript
	function pureFunction(input) {
	  let output = input;
	  return output;
	}
	
	function impureFunction(input) {
	  window.output = input;
	}
	
	let testA = pureFunction(1);
	console.log(testA === 1);
	
	let testB = impureFunction(1);
	console.log(testB === undefined);

Functions that do not explicitly set a return value are generally called “convenience methods”.

This video is an introduction to functions and includes a more practical example of using functions than simply logging variable values.

Watch on Vimeo Code from the video

Lesson Task

There are practice questions in the master branch of this repo.

There are example answers in the answers branch.

Try the exercises before checking the solutions.