Function Basics
Functions are a fundamental concept in JavaScript. They are used to encapsulate code that can be reused. Functions are defined using the function
keyword. The syntax of a function is as follows:
function functionName(parameters) {
// code to be executed
}
In modern JavaScript, you can also use arrow functions to define functions. The syntax of an arrow function is as follows:
const functionName = (parameters) => {
// code to be executed
}
You will see both of these syntaxes throughout your training and career, but neither is more correct than the other.
Parameters and Arguments
Let’s discuss parameters and arguments in the context of the following example function:
function favoriteAnimal(animal) {
return animal + " is my favorite animal!"
}
console.log(favoriteAnimal('Goat'));
In JavaScript, parameters are the items listed between the parentheses ()
in the function declaration. Function arguments are the actual values you decide to pass to the function when you use it.
In the example above, the function definition is written on the first line: function favoriteAnimal(animal)
. The parameter, animal
, is found inside the parentheses. You could just as easily replace animal
with pet
, x
, or blah
. But in this case, naming the parameter animal
gives someone reading your code a bit of context so that they don’t have to guess what animal
may eventually contain.
By putting animal
inside the parentheses of the favoriteAnimal()
function, you are telling JavaScript that you will send some value to your favoriteAnimal
function. This means that animal is just a placeholder for some future value. But what value are you sending?
The last line, favoriteAnimal('Goat')
, is where you are calling your favoriteAnimal
function and passing the value 'Goat'
inside that function. Here, 'Goat'
is your argument. You are telling the favoriteAnimal
function, “Please send 'Goat'
to the favoriteAnimal
function and use 'Goat'
wherever the 'animal'
placeholder is.” Because of the flexibility that using a parameter provides, you can declare any animal to be your favorite.
Here is a diagram to help you visualize how parameters are passed to a function, and how values get returned from it.
Make note of the fact that by calling favoriteAnimal()
inside of console.log()
with the argument 'Goat'
, you get the return value of the function, string of "Goat is my favorite animal!"
, printed to the console. You are passing in a function call favoriteAnimal('Goat')
as an argument in a different function call - console.log()
.
Scope
A variable declared inside a function is only visible inside a function. This is called the scope of the variable, this particular scope is called the local scope. Variables declared outside of a function are called global variables and are visible throughout the program. For example, the following code will raise an error:
function myFunction() {
let x = 10;
}
console.log(x);
The variable x
is declared inside the function myFunction
and is not visible outside of the function. The code will raise a ReferenceError
because x
is not defined.
If you declare a variable outside of a function, it is called a global variable and is visible throughout the program. For example, the following code will work:
let x = 10;
function myFunction() {
console.log(x);
}
myFunction();
If a same-named variable is declared inside the function then it shadows the outer one. This code, for example, will output 20
:
let x = 10;
function myFunction() {
let x = 20;
console.log(x);
}
myFunction();
Default Parameters and Undefined Arguments
If a function is called, but an argument is not provided, then the parameter will be assigned the value of undefined
. This can lead to unexpected results if the function is not designed to handle this case.
function favoriteAnimal(animal) {
return animal + " is my favorite animal!"
}
console.log(favoriteAnimal()); // Output: undefined is my favorite animal!
In the example above, the function favoriteAnimal
is called without an argument. The parameter animal
is assigned the value of undefined
, which is then concatenated with the string ” is my favorite animal!”.
If a value is not provided you can make use of default parameters. Default parameters allow you to assign a default value to a parameter if no value is provided when the function is called.
function favoriteAnimal(animal = 'Red Panda') {
return animal + " is my favorite animal!"
}
In the example above, the default value of the parameter animal
is set to 'Red Panda'
. If the function favoriteAnimal
is called without an argument, the parameter animal
will be assigned the value 'Red Panda'
.
The Return Statement
As you have seen before, functions can return a value using the return
keyword. The return
keyword is used to return a value from a function. When the return
keyword is used, the function will stop executing and return the value specified after the return keyword
.
function add(a, b) {
return a + b
}
console.log(add(2, 3)); // Output: 5
But what happens if the return
keyword is used before the end of the function? To answer this question, consider the following example:
function add(a, b) {
if(a > 2){
return b;
}
return a + b;
}
console.log(add(3, 7)); // Output: 7
In the example above, the function add
has a conditional statement that checks if the value of a
is greater than 2
. If the condition is met, the function will return the value of b
and stop executing. If the condition is not met, the function will return the sum of a
and b
.
Critical Thinking
What is the output of the following code snippet?
function add(a, b = 12) {
if(b > 11){
return b * 2;
} else if(a > 3){
return b;
}
return a + b;
}
console.log(add(3));
Arrow Functions
Arrow functions are a more modern way to write functions in JavaScript. They provide a more compact syntax compared to traditional function expressions. Arrow functions are defined using the =>
syntax.
const add = (a, b) => {
return a + b;
}
In the example above, the arrow function add
takes two parameters a
and b
and returns their sum. The return
keyword is used to return the result of the addition operation.
If the arrow function has only one expression, the curly braces {}
and the return
keyword can be omitted. The expression will be implicitly returned.
const add = (a, b) => a + b;
In the example above, the arrow function add
takes two parameters a
and b
and returns their sum. The return
keyword and curly braces {}
are omitted, and the result of the addition operation is implicitly returned.
Function Exercises
Exercise 1
Create a function that takes in an integer. This function should return the given integer + 7
if the integer is less than 10
. If the integer is greater than or equal to 10
, it should return the given integer - 3
.
The name of the function should be addOrSubtract
.
Exercise 2
Write a function, named multiply
, that takes two parameters and returns their product. Use arrow function syntax to implicitly return the result.
Exercise 3
Write a function, named capitalize
, that takes a string as a parameter and returns a new string with the first letter capitalized. Use string methods to accomplish this.
Exercise 4
Write a function, named lastLetter
, that takes a string as a parameter and returns the last letter of the string. Use string methods to accomplish this.