Selected topic
Functions
Prefer practical output? Use related tools below while reading.
In JavaScript, a function is a block of code that can be executed multiple times from different parts of your program. It's a way to encapsulate a specific task or set of instructions that you want to repeat.
### Function Declaration
A function is declared using the function keyword followed by the name of the function and its parameters in parentheses.
javascript
function add(x, y) {
return x + y;
}add that takes two parameters, x and y.### Function Invocation
To execute a function, you call it by its name followed by the required arguments in parentheses.
javascript
console.log(add(5, 7)); // Output: 12add function with arguments 5 and 7, and logging the result to the console.### Function Arguments
Functions can take multiple arguments, which are passed in when the function is called.
javascript
function greet(name, age) {
return Hello, ${name}! You are ${age} years old.;
}console.log(greet('John Doe', 30)); // Output: Hello, John Doe! You are 30 years old.
greet that takes two arguments, name and age.### Function Return Values
Functions can return values using the return statement.
javascript
function getFullName(first, last) {
return ${first} ${last};
}const fullName = getFullName('John', 'Doe');
console.log(fullName); // Output: John Doe
getFullName that returns a concatenated string of the first and last names.### Function Expressions
Functions can also be defined using function expressions.
javascript
const add = function(x, y) {
return x + y;
};console.log(add(5, 7)); // Output: 12
add function.### Arrow Functions
Functions can also be defined using arrow functions.
javascript
const add = (x, y) => {
return x + y;
};console.log(add(5, 7)); // Output: 12
add function.### Function Properties
Functions can also have properties attached to them.
javascript
function add(x, y) {
this.message = 'Added successfully!';
}const result = add(5, 7);
console.log(result.message); // Output: Added successfully!
add that has a property called message.