Imagine you live in a village without tap water.
To get water, you need to take an empty bucket, head to the well in the middle of the village, draw water from the well and head back home.
Since 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 just created a function — “draw water” is the name of the function.
Declaring functions
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.
When you declare a function, you’re essentially assigning a sequence of actions to a variable, so you can name the function anything you want — as long as it follows the same rules as declaring variables:
- It must be one word
- It must consist only of letters, numbers or underscores (
a-z,A-Z,0-9, or_). - It cannot begin with a number
- It cannot be any of these reserved keywords
parameters is optional. It is a comma-separated list of variables you wish to declare for your function. You can give them values when you use the function — don’t worry about this now because you’ll learn about it in a bit.
Using functions
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 functionfunction sayHello() { console.log('Hello world!')}
// using a functionsayHello()
The indentation
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.
Parameters and Arguments
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)}Arguments
Parameters must be given a value before they can be used. So when you call a function, you can pass in values which are also known as arguments.
You don’t need to remember the words “parameters” or “arguments” when you code — just know what they are when you’re reading about it. Professional programmers get these two mixed up all the time.
The sequence of arguments (values) passed to the function determines which the value of the parameter.
- The first parameter gets assigned to the first argument.
- The second parameter gets assigned to the second argument.
- And so on.
functionName('arg1', 'arg2', 'arg3')
Naming Parameters
Parameters are just variables so you can name them anything you want — as long as you follow the rules for naming variables listed above.
Normally, we use values that make sense.
For example, let’s say you want to have a function called sayName. And sayName should log the first name and last name of a person.
In this case, we cas use firstName for the person’s first name and lastName for the person’s last name since these variable names make sense.
// firstName and lastName are parameters, which are simply variablesfunction sayName(firstName, lastName) { // These variables can then be used later in the function console.log('firstName is ' + firstName) console.log('lastName is ' + lastName)}Using Parameters and Arguments
Zell is my first name, Liew is my last name.
To get the sayName to work correctly, I pass the arguments in order where the parameters are declared — so in this case, I’ll pass Zell as the first argument and Liew as the second argument:
sayName('Zell', 'Liew')// firstName is Zell// lastName is LiewIf you declared a parameter, but did not pass an argument to it, your parameter would be undefined.
sayName()// firstName is undefined// lastName is undefinedThe return statement
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 substitutes the expression with the given value.
Now, the expression is simply where you called the function.
function get2() { return 2 console.log('blah') // This is not executed}
const results = get2() // get2() is an expressionconsole.log(results) // 2If 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) // 10If there is no return statment, JavaScript automatically returns undefined.
Understanding Expressions
Expressions are simply defined as values that need to be evaluated before they can be passed around by JavaScript.
2 + 3is an expressionsayName()is an expression
Let’s make it clearer with examples.
If you 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) // 15If 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 15If you call a function and pass that value to another function, the function needs to be evaluated first before the value can be used.
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 16Remember, 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.
Hoisting
When you declare functions with the function keyword, the function will be hoisted to the top of the scope…
We’ll talk more about scope later, but to simplify things, you can visualize this by moving all functions to the top of the file.
sayHello()
// This function will be hoisted above sayHello()function sayHello() { console.log('Hello world!')}// So in reality, JavaScript executes the above code like this:function sayHello() { console.log('Hello world!')}
sayHello()Function Hoisting may be a bit confusing at first because JavaScript changes the order of your code. But it’s extremely useful.
Use function hoisting when you declare functions — because it allows you to write code that’s easy to read and understand (since you can park all functions at the end of the code).
Another way to declare functions
There are two ways to declare functions:
- With a function declaration
- With a function expression
Function declaration is what you just learned so far in the lesson. You write a function keyword, followed by its name, and the (), and the rest of the stuff.
// Function Declarationfunction functionName() { /* Stuff goes here */}A function expression is when you declare a function and manually assign the value of that function to a variable immediately.
Since the function is assigned to a variable immediately, you can create the function without naming it (because you can still use the function through the variable).
// Function Expressionconst sayHello = function () { console.log('This is declared with a function expression!')}Note: Functions that are not named are called anonymous functions.
Don’t declare functions with function expressions because they’re not automatically hoisted to the top of the scope.
sayHello() // Error, sayHello is not defined
// Function is not hoisted// So you can't use the function before it's declared.const sayHello = function () { console.log(aFunction)}Now, function expressions are still important because they’re used heavily in arrow functions — more on this in a later lesson.
Wrapping up
Four things:
- A function is a block of code that executes tasks in a specific order.
- You use (or invoke, or call) functions by adding a
()to the end of the function name. Example:drawWater() - You can add arguments when calling functions. Example:
sayName('Zell', 'Liew') - Functions have a
returnstatement that returns a value. If noreturnstatement is provided, functions returnundefined - Use hoisting when you can.
Exercise
Practice making functions. You need to use them a lot when you code for real. Do the following:
- Make a function named
loggerthatconsole.logthe argument you passed into it. - Make a function called
addthat adds two numbers together. - Make a function called
multiplythat multiplies two numbers together.
Make a function named logger that console.log the argument you passed into it.
// Creating the functionfunction logger(arg) { console.log(arg)}
// Using the functionlogger(`I'm the king of the world!`) // I'm the king of the world!Make a function called add that adds two numbers together.
// Creating the functionfunction add(num1, num2) { return num1 + num2}
// Using the functionconst result = add(56, 44)console.log(result) // 100Make a function called multiply that multiplies two numbers together.
// Creating the functionfunction multiply(num1, num2) { return num1 * num2}
// Using the functionconst result = add(20, 10)console.log(result) // 200Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson