Defining functions
- Node.js course
- Beginner
- Lesson 71/116
- 4 min
Learn to define functions with function and arrow function.
Defining functions
A function is a reusable block of code. JavaScript has two common forms: the function declaration and the function expression.
Function declaration: function greet(name) { return 'Hello ' + name; }. The name comes first; the function can be called before its definition (hoisting).
Function expression: const greet = function (name) { return 'Hello ' + name; };. Here the function is assigned to a variable; it cannot be called before the definition. Both are valid; this lesson uses the declaration form.
Parameter and argument
The names in a function definition are parameters; the values passed at call time are arguments. The two are often confused but are different concepts.
Example: in function greet(name) { ... }, name is a parameter. In the call greet('Ayşe'), 'Ayşe' is an argument. A parameter is a placeholder; an argument is the real value put in that place.
In JavaScript, if an argument is not given for a parameter, its value is undefined. This lets incomplete calls continue silently, so it is important to pass all the arguments you need.
Practice Greet function
Define a function greet(name). Its body should return the string 'Hello ' + name. Print the result of greet('Ayşe') with console.log.
Starter code
// Define the greet function and print the call resultSample solution
function greet(name) {
return 'Hello ' + name;
}
console.log(greet('Ayşe'));Expected output
Hello Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a function declaration?
- const add = (a, b) => a + b;
- const add = function (a, b) { return a + b; };
- function add(a, b) { return a + b; } Correct answer
- add(a, b) => { return a + b; }
Explanation: the form starting with the function keyword is a declaration.
2 Two-parameter function
function add(a, ____) { return a + b; }
function add(a, b) { return a + b; }
Explanation: the second parameter is b and is added in the body.
3 Match the function parts
| Term | Meaning |
|---|---|
function |
Keyword |
greet |
Function name |
name |
Parameter |
'Ayşe' |
Argument |