JavaScript functions are blocks of code that can be defined and called by a function name. Functions can be used to execute a block of code multiple times or to perform a specific task.
There are two ways to define a function in JavaScript: function declaration and function expression.
Function Declaration
A function declaration consists of the function keyword, followed by the function name, a set of parentheses (), and a pair of curly braces {} that enclose the function’s code block.
Here is an example of a function declaration:
function sayHello() {
console.log("Hello, World!");
}
The function name in this example is “sayHello”. To call the function, you simply need to use the function name followed by a set of parentheses:
sayHello(); // Outputs "Hello, World!"
Function Expression
A function expression is similar to a function declaration, but it is assigned to a variable. This means that the function is not given a name, and it can be anonymous.
Here is an example of a function expression:
const sayHello = function() {
console.log("Hello, World!");
}
To call the function, you need to use the variable name followed by a set of parentheses:
sayHello(); // Outputs "Hello, World!"
Passing Parameters to Functions
Functions can accept arguments, which are values that are passed to the function when it is called. These arguments are placed inside the parentheses of the function definition.
For example, you can modify the “sayHello” function to accept a name as an argument:
function sayHello(name) {
console.log(`Hello, ${name}!`);
}
sayHello("John"); // Outputs "Hello, John!"
You can also pass multiple arguments to a function by separating them with a comma:
function sayHello(firstName, lastName) {
console.log(`Hello, ${firstName} ${lastName}!`);
}
sayHello("John", "Doe"); // Outputs "Hello, John Doe!"
Returning Values from Functions
Functions can also return a value by using the “return” keyword. This allows you to use the output of the function in another part of your code.
For example, you can modify the “sayHello” function to return a greeting message instead of logging it to the console:
function getGreeting(name) {
return `Hello, ${name}!`;
}
const greeting = getGreeting("John");
console.log(greeting); // Outputs "Hello, John!"
Default Arguments
In JavaScript, you can specify default values for function arguments in the function definition. This means that if an argument is not provided when the function is called, the default value will be used instead.
For example, you can modify the “getGreeting” function to have a default name of “World”:
function getGreeting(name = "World") {
return `Hello, ${name}!`;
}
console.log(getGreeting()); // Outputs "Hello, World!"
console.log(getGreeting("John")); // Outputs "Hello, John!"
Inline Functions
Inline functions, also known as anonymous functions, are functions that are defined and called on the same line. They are often used as arguments for other functions or as a way to define a function quickly.
Here is an example of an inline function being used as an argument:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(number) {
return number * 2;
});
console.log(doubledNumbers); // Outputs [2, 4, 6, 8, 10]
In this example, the “map” function calls the inline function for each element in the “numbers” array, and the returned value is added to the “doubledNumbers” array.
If the inline function only has a single statement, you can omit the curly braces and the “return” keyword:
const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map(number => number * 2); console.log(doubledNumbers); // Outputs [2, 4, 6, 8, 10]
The inline functions will be discussed in detail in a later chapter on higher-order functions.
Practice Exercise
Here are some practice questions about correcting code based on this tutorial:
- You are trying to call a function named “
sayHello“, but you are getting an error that the function is not defined. What could be the problem?
sayHello();
function sayHello() {
console.log("Hello, World!");
}
- You are trying to pass a name to the “
sayHello” function, but the output is not showing the correct name. What could be the problem?
sayHello("John");
function sayHello(name) {
console.log(`Hello, ${name}!`);
}
- You are trying to return a value from the “
getGreeting” function, but the returned value is “undefined“. What could be the problem?
function getGreeting(name) {
console.log(`Hello, ${name}!`);
}
const greeting = getGreeting("John");
console.log(greeting);
- You are trying to pass a default value to the “
getGreeting” function, but the default value is not being used when no argument is provided. What could be the problem?
function getGreeting(name = "World") {
return `Hello, ${name}!`;
}
console.log(getGreeting());
- You are trying to use an inline function as an argument, but you are getting an error that the function is not defined. What could be the problem?
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(number) {
return number * 2;
});
console.log(doubledNumbers);
Here are some more practice questions based on real-world scenarios for this tutorial:
- You are building a to-do list app, and you want to create a function that adds a new to-do item to the list. How would you define this function?
- You are building a weather app, and you want to create a function that converts Celsius to Fahrenheit. How would you define this function and pass a temperature in Celsius as an argument?
- You are building a calculator app, and you want to create a function that calculates the total cost of an order including tax. How would you define this function and pass the subtotal and tax rate as arguments?
- You are building a form validation script, and you want to create a function that checks if a string is a valid email address. How would you define this function and pass the email string as an argument?
- You are building a dashboard for a social media platform, and you want to create a function that displays the total number of followers for a user. How would you define this function and pass the user’s id as an argument?
In this tutorial, you learned about declaring and calling functions in JavaScript. You also learned how to pass arguments to functions and return values from them.
I hope this helps! Let me know if you have any questions.
