- Function declaration
- Function calls
- Function arguments (input to functions)
- Return (output from functions)
As your programs grow, you'll often want to reuse pieces of code.
That’s what functions are for: they let you group some code together, give it a name, and run it whenever you want.
Function declaration
To declare a function, we can use the
function keyword. Then we give it a name, a pair of parentheses () with the arguments it takes, and a block of code {} to be executed. Let's start with a function that takes no arguments:function sayHello () {console.log(`Hello!`) }
This code declares the function, but does not run it yet.
Function calls
To run (or "call") the function, you write its name followed by parentheses:
function sayHello () {console.log(`Hello!`) } sayHello()
This prints:
Hello!
You can call the function as many times as you want:
function sayHello() { console.log("Hello!") } sayHello() sayHello()
This prints:
Hello! Hello!
The code inside the function only runs when you call it.
Function arguments (input to functions)
Sometimes, you want a function to work with some input. You can do that by adding arguments inside the parentheses.
For example:
function sayHelloTo (friend) { console.log(`Hello ${friend}!`) }
Now this function takes one argument called
friend.When you call the function, you can pass a value:
sayHelloTo("Tommy")
This prints:
Hello Tommy!
You can call the function again with a different name:
sayHelloTo("Sam")
This prints:
Hello Sam!
The value you pass in replaces the
friend variable inside the function.You can also use more than one argument:
function greetTwoPeople(person1, person2) { console.log(`Hello ${person1} and ${person2}!`) } greetTwoPeople("Lina", "Marco")
This prints:
Hello Lina and Marco!
return (output from functions)
Functions can also return values. This means they send a value back to wherever the function was called.
Here’s a simple example:
function getNumber() { return 42 } const result = getNumber() console.log(result)
This prints:
42
The function
getNumber() returns 42, and we store it in result, then print it.You can also return something you calculate:
function add(a, b) { return a + b } const result = add(2, 3) console.log(result)
This prints:
5
Once a value is
returned, the function stops. Anything after return in that block doesn’t happen.function saySomething() { return "hi" console.log("this never runs") } const message = saySomething() console.log(message)
This prints only:
hi
because only
"hi" gets returned. The console.log("this never runs") line is skipped.You can think of functions as small sub-programs. Each function can take some input, work on it, and give you back some output.
What happens if we try to use the return value of a function, but that function didn't return anything?
function doesNothing () {} const x = doesNothing() console.log(x)
This will print
undefined. The return value of a function that didn't return anything is undefined.