Functions
Hey ,
I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.
Please upgrade (use this link) access this content.
I'm super eager to help you learn more!
Hey ,
I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.
Please upgrade (use this link) access this content.
I'm super eager to help you learn more!
Imagine you live in a village without tap water. To get water, someone from your household needs to take an empty bucket, head to the well in the middle of the village, draw water from the well and head back home.
You need to draw water from the well multiple times a day. It’s a hassle to say “I’m going to take an empty bucket, go to the well, draw water and bring it back home” every time you explain what you’re doing.
To shorten it, you can say you’re going to “draw water”.
And my friend, you’ve created a function; “draw water” is the name of the function.
A function is a block of code that executes tasks in a specific order, like take empty bucket, go to well, draw water, head back home.
It can be defined with the following syntax:
function functionName (parameters) {
// Do stuff here
}
function
is a keyword that tells JavaScript you’re defining a function.
functionName
is the name of the function. In the example given above, the function name could be drawWater
.
The name of the function can be anything, as long as it follows the same rules as declaring variables. In other words, it needs to follow these rules:
_
)parameters
is optional. It is a comma-separated list of variables you wish to declare for your function. They can be assigned values when you use the function.
Once you declared your function, you can use (or invoke, or call, or execute) it by writing the name of the function, followed by parenthesis ()
.
Here’s an example where a sayHello
function is declared and used.
// Declaring a function
function sayHello () {
console.log('Hello world!')
}
// using a function
sayHello()
Code within a block (anything within curly braces is a block) gets indented to the right. This is an important practice that helps you make code easier to read. In the following example, you can immediately see that console.log('Hello world')
is part of sayHello
.
function sayHello () {
// This console.log statement is a part of sayHello
console.log('Hello world!')
}
You can choose to indent with 2 spaces or with a tab key. Some people prefer spaces, others prefer tab. Both are fine, as long as you keep it consistent.
Functions can take in parameters, which are simply variables you wish to declare for the function. You can have any number of parameters. Each parameter must be separated by a comma.
function functionName(param1, param2, param3) {
// Do stuff here
}
These variables can then be used later in the function.
function functionName(param1, param2, param3) {
console.log('First Parameter: ' + param1)
console.log('Second Parameter: ' + param2)
console.log('Third Parameter: ' + param3)
}
You pass in arguments to assign values to parameters. Arguments are values you use when you call a function.
functionName('arg1', 'arg2', 'arg3')
You can name your parameters anything you want, but we normally use values that make sense.
Let’s make it clearer with an example.
Let’s say you wish to write a function called sayName
that logs the firstName and lastName of a person.
We can write a function that takes in two parameters, firstName
and lastName
. We use firstname
and lastName
since it makes sense for the function.
// firstName and lastName are parameters, which are simply variables
function sayName(firstName, lastName) {
// These variables can then be used later in the function
console.log('firstName is ' + firstName)
console.log('lastName is ' + lastName)
}
We can then console.log
these two variables (since parameters are variables) later in the function.
function sayName(firstName, lastName) {
// These variables can then be used later in the function
console.log('firstName is ' + firstName)
console.log('lastName is ' + lastName)
}
Zell is my first name, Liew is my last name. To get the function to work correctly, I pass my Zell
, as the first argument, and Liew
as the second argument:
sayName('Zell', 'Liew')
// firstName is Zell
// lastName is Liew
If you declared a parameter, but did not pass an argument to it, your parameter would be undefined
.
sayName()
// firstName is undefined
// lastName is undefined
Note: In the real world, we don’t differentiate between parameters
or arguments
. Everyone calls both of them arguments
all the time. For this course, I’m going to call them arguments too.
Functions can have a return statement that consists of the return
keyword and a value:
function functionName () {
return 'some-value'
}
When JavaScript sees this return statement, it stops executing the rest of the function and “returns” the value (passes the value back to expression that called the function call).
function get2 () {
return 2
console.log('blah') // This is not executed
}
const results = get2()
console.log(results) // 2
// Note: You would not see 'blah' in the console
If the return value is an expression, JavaScript evaluates the expression before returning the value.
function add2(num) {
return num + 2
}
const number = add2(8)
console.log(number) // 10
If there is no return
statment, JavaScript automatically returns undefined
.
JavaScript can only pass around two types of values. They are:
(You’ll learn more about objects in a later lesson).
If you have an expression, they need to be evaluated first before they get passed into functions. (An expression is something like 2 + 3
).
Let’s make it clearer with examples. If you have pass numbers (which are primitives) into functions, they can be used immediately.
function sum(num1, num2) {
return num1 + num2
}
const result = sum(5, 10)
console.log(result) // 15
If you pass expressions (like 2 + 3
), these expressions have to be evaluated first before they are passed into functions.
const result = sum(2 + 3, 10)
console.log(result) // 15
// Here's what happens:
// Step 1: JavaScript evaluates 2 + 3. It becomes 5
// Step 2: JavaScript calls sum(5, 10). It returns 15
If you call a function as an argument to another function, you need to evaluate the function call first. (When you call a function, it’s an expression).
function multiply (num1, num2) {
return num1 * num2
}
const result = sum(multiply(2, 3), 10)
console.log(result) // 16
// Here's what happens:
// Step 1: JavaScript calls multiply(2, 3). It returns 6
// Step 2: JavaScript calls sum(6, 10). It returns 16
Finally, you can pass functions into other functions. A function that’s passed into another function is called a callback
. You can call the callback
anytime within the function.
function three () {
return 3
}
function add2(callback) {
return callback() + 2
}
const result = add2(three)
console.log(result) // 5
Remember, Javascript can only pass around primitives (like String, Numbers, Booleans) and objects (like functions, arrays and objects) as values. Anything else needs to be evaluated.
Functions can be hard for beginners to understand. To make sure you understand functions completely, let’s go through what happens when you declare and use a function again. This time, we’ll take things one step at a time.
Here’s the code we’re dissecting:
function add2 (num) {
return num + 2
}
const number = add2(8)
console.log(number) // 10
First of all, you need to declare a function before you can use it. In the first line, JavaScript sees the function
keyword and knows the function is called add2
.
It skips over the code in the function at this point because the function is not used yet.
Next, JavaScript sees you declare a variable called number
; you also want to assign the result of add2(8)
to it.
Since the right hand side (RHS) is a function call (an expression), JavaScript needs to evaluate add2(8)
before assigning it to number
. Here, it sets the parameter num
to 8
.
In the add2
function, JavaScript sees a return statement that says num + 2
. This is an expression that needs to be evaluated. JavaScript adds 8 and 2 together.
Once num + 2
is evaluated, JavaScript returns the value to the function call. It replaces the function call with the returned value. So, add2(8)
becomes 10.
Finally, once the RHS is evaluated, JavaScript creates the variable, number
and assigns the value 10 to it.
This is how you read the flow of a function.
Protip: whenever you’re confused, slow down and read the flow of your program. Follow what we’ve done above. You’ll clear things up.
When functions are declared with a function declaration (what you learned above), they are hoisted to the top of your scope. More on scope in a later lesson, but this means the following two sets of code are exactly the same.
function sayHello () {
console.log('Hello world!')
}
sayHello()
// This is automatically converted to the above code
sayHello()
function sayHello () {
console.log('Hello world!')
}
Function hoisting gets confusing because JavaScript changes the order of your code. I highly recommend you declare your functions before you use them. Don’t rely on hoisting.
A second way to declare functions is with a function expression. Here, you declare a variable, then assign a function without a name (also called an anonymous function) to it.
const sayHello = function () {
console.log('This is declared with a function expression!')
}
Functions declared with function expressions are not automatically hoisted to the top of your scope.
sayHello () // Error, sayHello is not defined
const sayHello = function () {
console.log(aFunction)
}
At this point, you may wonder if function expressions are important. That’s a common question to have. Why would you use function expressions if you can declare functions with the function declaration syntax?
They are important. You’ll learn why when you use arrow functions in the next lesson (and object methods in the next next lesson).
Four things:
()
to the end of the function name. Example: drawWater()
sayName('Zell', 'Liew')
return
statement that returns a value. If no return
statement is provided, functions return undefined
Practice making functions. You need to use them a lot when you code for real. Do the following:
logger
that console.log
the argument you passed into it.add
that adds two numbers together.multiply
that multiplies two numbers together.console.log
the argument you passed into it.// Creating the function
function logger (arg) {
console.log(arg)
}
// Using the function
logger(`I'm the king of the world!`)
add
that adds two numbers together.// Creating the function
function add (num1, num2) {
return num1 + num2
}
// Using the function
const result = add(56, 44)
console.log(result) // 100
multiply
that multiplies two numbers together.// Creating the function
function multiply (num1, num2) {
return num1 * num2
}
// Using the function
const result = multiply(20, 10)
console.log(result) // 200