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:
function greet() { console.log("Hello, World"); }
This is the general form of a function:
function functionName() { statement; statement; etc. }
To execute the function (also known as calling the function, or invoking the function), you write a statement that calls it.
greet();
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:
function greet(name) { console.log("Hello, " + name); } greet("Alberta"); //Hello Alberta
With JavaScript ES6, you can define functions using arrow syntax. Here is our greet function defined using arrow syntax:
let greet = () => console.log("Hello, World");
A function with one parameter:
let greet = name => console.log("Hello, " + name);
A function with more than one parameter:
let greet = (fname, lname) => console.log("Hello, " + fname + " " + name);
A function with multiple statements:
let greet = (fname, lname) => { let name = fname + " " + name; console.log("Hello, " + name); }
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.
function add(x, y) { return x + y; }
This is the general form defining a value returning function:
function functionName() { statement; statement; etc. return expression; }
The value of expression is what gets output by the function. This kind of function is useful when it is stored in a variable.
let variableName = functionName();
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:
{ let a = 2; }
The variable a
is local to the block it is in. A block can also be a loop or an if statement. Example:
let a = 1; if (5 >4){ let a = 2; } console.log(a); //1
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:
let a = 1; if (5 >4) { let a = 2; console.log(a); //2 }
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:
let a = 1; function foo () { a = 2; } console.log(a); //1 foo(); console.log(a); //2
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:
function greet (name="world") { console.log("Hello, " + name); } greet(); //Hello World
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:
function foo(...args) { console.log(args); } foo( 1, 2, 3, 4, 5); //[1, 2, 3, 4, 5]
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:
export function foo() { console.log(“Hello World”); } export let bar = 82; export let baz = [1,2,3];
Alternatively, all properties can be exported with one export statement:
function foo() { console.log("Hello World"); } let bar = 82; let baz = [1,2,3]; export { foo, bar, baz };
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:
import { foo, bar, baz } from "foo";
You can also rename your import:
import { foo as Foo } from "foo"; Foo();
Or you can import all of the properties of the module:
import * as myModule from "foo"; myModule.foo();
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.
No comments:
Post a Comment