JavaScript Basics: Your First Programs
Functions
In this lesson you will
- Declare and call a function
- Use parameters, default values and return
- Write an arrow function
Introduction
If you make tea every morning, you do not rewrite the recipe each day. You just say "make tea". A function is a recipe with a name. You write the steps once and run them whenever you want.
The simple explanation
A function is a named block of code you can run again and again.
Writing the function does nothing by itself. It runs when you call it with brackets: sayHello().
Quick quiz
How do you run (call) a function named sayHello?
Parameters
Parameters let a function work with different inputs. They are like blanks in the recipe.
name is the parameter. "Sam" is the argument you pass in. You can have several parameters, separated by commas.
Return values
Often a function should give back a result. The return keyword does that and ends the function.
A function without return gives back undefined.
Default values
You can give a parameter a default, used when no argument is passed.
Arrow functions
Arrow functions are a shorter way to write a function. You will see them everywhere.
When the body is a single expression, you can leave out the braces and return, and the value is returned automatically.
Scope
Variables created inside a function exist only inside it. Variables created outside can be read from within.
The last line fails because secret only exists inside show.
Quick quiz
What does return do?
Try it yourself
Write a function isEven(n) that returns true if n is even and false otherwise. Then test it with a few numbers.
Summary
- A function is a reusable, named block of code. Call it with
(). - Parameters are inputs, and
returngives a result back. - Arrow functions are a short form:
(a, b) => a + b. - Variables made inside a function are not visible outside.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading