Advertisement
  1. Code
  2. JavaScript
Code

Learn Computer Science With JavaScript: Part 4, Functions

by
Difficulty:BeginnerLength:MediumLanguages:
This post is part of a series called Learn Computer Science with JavaScript.
Learn Computer Science With JavaScript: Part 2, Conditionals
Learn Computer Science With JavaScript: Part 3, Loops

Introduction

Suppose you have a file that is 82 lines long and consists only of a series of statements. (I hope this is isn’t true, but anything is possible.) How would you understand what the program does? How would you modify it or use it? It would be kind of hard to do anything with this code because there is no structure to it.  

To solve this problem, you could use functions. A function is a group of statements that perform a specific task. Functions allow us to break up a program into smaller programs, making our code more readable, reusable, and testable.

Contents

  • Void functions
  • Value returning function
  • Scope
  • Parameters
  • Modules

Void Functions

This kind of function lists steps for the program to perform. Consider we are writing a program to log a user into a website. The program might consist of the following tasks:

  • Get the username
  • Get the password
  • Check if the username and password exist
  • Redirect the user to their dashboard

Each of these steps might be contained inside a login function. This is an example function:

This is the general form of a function:

To execute the function (also known as calling the function, or invoking the function), you write a statement that calls it.

The () is where we pass input to the function. When we are defining the function, the input is called a parameter. When we call the function, the input will be the actual value and is called the argument. Example:

With JavaScript ES6, you can define functions using arrow syntax. Here is our greet function defined using arrow syntax:

A function with one parameter:

A function with more than one parameter:

A function with multiple statements:

Because an arrow function is an anonymous function, we give our function a name by assigning it to a variable. Arrow functions can be useful when your function body only has one statement.

Value Returning Function

This kind of function returns a value. The function must end with a return statement. This example returns the sum of two numbers.

This is the general form defining a value returning function:

The value of expression is what gets output by the function. This kind of function is useful when it is stored in a variable. 

Scope

A variable’s scope is the part of the program where a variable can be accessed. A variable can be local or global. A local variable’s scope is inside the function it was created in. No code outside of the function can access its local variables. 

Also, when you use let or const to declare a variable, they have block scope. A block is a set of statements that belong together as a group. A block could be as simple as wrapping our code in curly braces:

The variable a is local to the block it is in. A block can also be a loop or an if statement. Example:  

Because our console statement is in the same scope as our first variable a, it displays that value, which is 1. It does not have access to the variables inside the if block. Now, consider this example:

Now 2 will be displayed because the scope of variables that our console statement has access to is within the if block. A function’s parameters are also local variables and can only be accessed by code inside the function. Global variables, on the other hand, can be accessed by all the statements in a program’s file. Example:

In this example, a is a global variable, and we have access to it inside the foo function. The first console statement will display 1. After calling foo, the value of a is set to 2, making the second console statement display 2. 

Global variables should be used very little, ideally not at all. Because global variables can be accessed by any part of a program, they run the risk of being changed in unpredictable ways. In a large program with thousands of lines of code, it makes the program harder to understand because you can’t easily see how the variable is being used. It is better to create and use local variables.

However, if you need to use a variable in multiple places in your program, it is OK to use a global constant. Declaring a variable with the const keyword prevents it from being changed, making it safer to use. You only need to worry about updating the value of the constant in the place it was declared.

Parameters

Recall that a parameter is a variable a function uses to accept data. The parameter is assigned the value of a function’s arguments when the function is called. As of ES6, parameters may also be given default values with the format parameterName=value. In this case, you can call a function without arguments, and it will use default values. Example:

The spread/rest operator is new to ES6 and can be used to either expand an array or object into individual values or gather the parameters of a function into an array. This is an example of using a rest parameter:

Modules

Suppose now you have a file that has 1,082 lines. (I have seen this, and you should run if you encounter such a thing.) The file is organized into functions, but it is difficult to see how they relate to each other. 

To group together related behavior, we should put our code in modules. A module in ES6 is a file that contains related functions and variables. Modules let us hide private properties and expose public properties that we want to use in other files. The filename would be the name of the module. Modules also have their own scope. To use variables outside of the module’s scope, they have to be exported. Variables that aren’t exported will be private and can only be accessed within the module.  

Individual properties can be exported like this:

Alternatively, all properties can be exported with one export statement:

To use a module’s variables, you import it into the file. You can specify what you want to import from the module like this:

You can also rename your import:

Or you can import all of the properties of the module:

Review

Functions allow us to divide our programs into smaller programs that we can easily manage. This practice is known as modularizing. There are two kinds of functions: void functions and value returning functions. A void function executes the statements inside of it. A value returning function gives us back a value.  

Scope is the part of the program where a variable can be accessed. Variables declared inside a function, including the function’s parameters, are local. Blocks also have scope, and local variables can be created inside of them. 

Variables not enclosed in a block or module will be global. If you need a global variable, it is acceptable to have a global constant. Otherwise, try to contain your code to modules because modules have their own scope. But even better, modules give your code structure and organization.  

Resources

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.