IN THIS LESSON
What are is a function?
When it comes to actually doing something with programming, you're going to need a Function
. A function is simply a reusable chunk of code that carries out some action [performs a task].
The label is helpful because if a value is ever undefined
, console.log may not print anything. Adding a label makes sure something is always printed. Plus, the labels keep things organized.
Defining Functions
Ok now that we know how to call existing functions, let's learn how to write our own. There are basically 4 parts to any function:
Name: How we call the function
Parameters: The Argument definitions
Body: The code that gets run with each call
Return Value: The data we get out of a function
Let's take a closer look at each part of the function.
The Name
Notice that I'm using const
instead of let
. Since our variables might need to change, we just stick with let
for simplicity. But a function assignment should never change. Think of it like easing into using let
and const
like the pros.
The Parameters
If we pass values into our called function, we refer to them as Arguments, but when we're dealing with those values in our function's definition, we call them Parameters. Think of Parameters like mini variables that we only use in our function.
The Function Body
Anything within the {}
is the body of the function. When we call a function, it's the code that runs. On the flip side, it won't do anything until you call it.
The Return Value
Sometimes we want to use a function to create a value and, instead of logging it, save it to a variable. In order to get values out of our functions, we need to use the return
keyword. Look how we use add()
to set the value of the oneHundred
variable (or replace with a different example reference + example).
Spacing for functions
To tell what is or isn't inside a function, always indent one level (that means hit the tab key on your keyboard once). Most editors will automatically do this for you when you press enter.
// First, we define it
const square = (number) => {
return number * number
}
// then we call it!
square(4)
// This gives us 16
Calling Functions
Before learning how to define our own functions, let's go over how to use some of the built in JS functions. In order to call
(or "run") a function, you add a pair of ()
onto the end of the function's name. If the function needs extra pieces of information, called Arguments
, you put them in between the ()
.
console.log in depth
The console.log function takes any number of arguments
and then logs each one to the screen.
The ability to log multiple things makes debugging, or fixing, your programs a lot easier. By using a string argument as a label, you can pass in a variable as a second argument to make sure it is what you think it's supposed to be.
let city = undefined
console.log('City:', city)
// Thanks to our log, we can easily see
// that variable is wrong
// can you please fix it?
Breaking it all down
As you can see, the name is a lot like our last lesson. That's on purpose. A variable name can point that line to anything. It could be a piece of data, but it could also be a function. If a variable points to a function, we just call it a function. You don't have to say "my function variable" or anything.
function oldFunction (myParam) {
return myParam
}
// Which is the same as this
const newFunction = (myParam) => {
return myParam
}
Fun fact, it's called an arrow function because we use a little arrow (=>) to define them.
Parameters go inside the ()
. When there's more than one you separate them out with commas. If there are no parameters, you still need to use ()
when defining and calling the function.
const greet = () => {
console.log("Hey!")
}
greet()
Parameters can be any data type, but they only exist inside the function.
const add = (num1, num2) => {
return num1, num2
}
num1
NO! BAD! THAT WILL BREAK!
Put it all together!
Try defining a function that returns the "cube" of a number (meaning multiply that number by itself 3 times). Then save that value into a variable called cubed
and log it to the screen.
Common Errors
One last thing before we move on, I just want to mention some common errors that you should watch out for.
Call the function
Don't forget the ()
to call a function!
const sayHi = () => {
return "Hello there!"
}
let greeting = sayHi // WRONG
That code will just set the value of greeting
as the function definition. If you log it, it looks like "[Function: sayHi] native code". Always call your function with ()
!
Missing arguments
You would think that if you forget an argument when calling a function JavaScript would automatically break. It doesn't. Instead, it treats any missing arguments as if they had a value of undefined
.
🎉 Congratulations! You've successfully grasped the basic fundamentals of variables. Now, let's reinforce your learnings with some hands-on practice. Below are prompts to help you strengthen your skills. Feel free to use the CodePen link provided to write and test your code, press Run Pen to activate the terminal:
Challenge 1: Write a function called sum that takes in two numbers, find the sum of the numbers and then return the sum.
Challenge 2: Write a function that logs how you are feeling today
Challenge 3: Can you figure out why the repeat function isn’t logging a message to the screen?