JavaScript functions are reusable blocks of code that perform specific tasks. They help you organize your code, avoid repetition, and make programs easier to understand and maintain.
For example, if you need to calculate the total price of products several times, you can create a function once and call it whenever you need the calculation.
In this tutorial, you will learn what functions are, how to declare and call functions, the difference between function declarations and function expressions, how parameters and arguments work, how to return values, and how to use default parameters.
What Is a Function in JavaScript?
A function is a reusable block of code designed to perform a particular task. You can define a function once and execute its code whenever you call it.
JavaScript provides built-in functions, such as console.log() and Number(), and allows you to create your own functions.
Example of a JavaScript Function
function greet() {
console.log("Hello, World!");
}
greet();
Output:
Hello, World!
In this example:
functionis the keyword used to declare a function.greetis the function name.()contains the function’s parameters, if any.{}contains the function body.console.log()displays a message.greet()calls the function and executes its code.
The function does not run when you simply declare it. It runs when you call it.
If you are new to JavaScript variables and values, read our JavaScript Variables tutorial.
Function Declaration in JavaScript
A function declaration defines a named function using the function keyword. It is one of the most common ways to create a function in JavaScript.
Syntax of a Function Declaration
function functionName() {
// Code to execute
}
Here, functionName represents the name you choose for your function. The code inside the function body executes when the function is called.
Example of a Function Declaration
function welcome() {
console.log("Welcome to Web4Learners!");
}
welcome();
Output:
Welcome to Web4Learners!
The welcome() function displays a welcome message when called.
Calling a Function Before Its Declaration
Function declarations are hoisted in JavaScript. This means you can generally call a function declaration before the declaration appears in the code.
welcome();
function welcome() {
console.log("Welcome to JavaScript!");
}
Output:
Welcome to JavaScript!
JavaScript allows this because function declarations are initialized during the relevant scope’s setup.
Function declarations are useful when you want to create named, reusable operations that can be called from different parts of your program.
Function Expression in JavaScript
A function expression creates a function as part of an expression. The function can be assigned to a variable, passed to another function, or used in other expressions.
Syntax of a Function Expression
const functionName = function() {
// Code to execute
};
Unlike a function declaration, a function expression can be anonymous, meaning the function itself does not have a name.
Example of a Function Expression
const greet = function() {
console.log("Hello from a function expression!");
};
greet();
Output:
Hello from a function expression!
In this example, the function is assigned to the greet variable. Calling greet() executes the function.
Named Function Expression
A function expression can also have its own name.
const calculate = function multiply() {
console.log(5 * 4);
};
calculate();
Output:
20
Here, multiply is the function’s internal name, while calculate is the variable used to access it from outside the function.
Function Declaration vs Function Expression
| Feature | Function Declaration | Function Expression |
|---|---|---|
| Syntax | function greet() {} | const greet = function() {}; |
| Function name | Normally required | Can be anonymous or named |
| Hoisting | Can generally be called before its declaration | Cannot be accessed through a const or let variable before initialization |
| Assignment to a variable | Not required | Commonly assigned to a variable |
| Common use | Defining reusable named functions | Assigning functions to variables and passing them as values |
Important: A function expression assigned to a const or let variable cannot be called before that variable has been initialized.
greet();
const greet = function() {
console.log("Hello!");
};
This produces a ReferenceError because greet is accessed before its initialization.
Calling Functions in JavaScript
Calling a function means executing the code inside it. To call a function, write its name followed by parentheses.
Example of Calling a Function
function showMessage() {
console.log("Learning JavaScript is easy!");
}
showMessage();
showMessage();
showMessage();
Output:
Learning JavaScript is easy!
Learning JavaScript is easy!
Learning JavaScript is easy!
The function is declared once but called three times. Each call executes the same code.
Calling a Function with Different Values
You can also pass different values to a function each time you call it.
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Karim");
greetUser("Rahul");
greetUser("Priya");
Output:
Hello, Karim!
Hello, Rahul!
Hello, Priya!
The function receives a different name with each call and uses it to create the message.
Functions become especially useful when combined with JavaScript Conditional Statements to execute different actions based on a condition.
Function Parameters in JavaScript
Parameters are variable names written inside a function’s parentheses when the function is defined. They act as placeholders for values the function receives when it is called.
Example of Function Parameters
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Karim");
Output:
Hello, Karim!
In this example, name is a parameter. When the function is called, the supplied value is made available through that parameter.
Functions with Multiple Parameters
A function can have multiple parameters separated by commas.
function addNumbers(a, b) {
console.log(a + b);
}
addNumbers(10, 20);
Output:
30
Here, a and b are parameters. The function adds their values and displays the result.
Parameters with Different Data Types
Parameters can receive strings, numbers, Boolean values, arrays, objects, and other JavaScript values.
function displayDetails(name, age) {
console.log("Name: " + name);
console.log("Age: " + age);
}
displayDetails("Karim", 22);
Output:
Name: Karim
Age: 22
The function uses two parameters to receive a name and an age.
JavaScript does not require you to specify parameter types in a function definition. The values you pass determine the types available during execution.
Function Arguments in JavaScript
Arguments are the values or expressions supplied when a function is called. They provide the actual data that the function uses.
Example of Function Arguments
function multiply(a, b) {
console.log(a * b);
}
multiply(5, 4);
Output:
20
In this example:
aandbare parameters.5and4are arguments.- The function multiplies the supplied values and displays
20.
Passing Different Arguments
function greetUser(name) {
console.log("Welcome, " + name);
}
greetUser("Karim");
greetUser("Anil");
Output:
Welcome, Karim
Welcome, Anil
The same function works with different arguments without requiring a new function for each user.
Difference Between Parameters and Arguments
| Parameters | Arguments |
|---|---|
| Defined in the function definition | Supplied when the function is called |
| Act as placeholders | Provide actual values or expressions |
Example: a, b | Example: 10, 20 |
Consider this statement:
function add(a, b) {
console.log(a + b);
}
add(10, 20);
Here, a and b are parameters, while 10 and 20 are arguments.
If a function is called with fewer arguments than it has parameters, the missing parameters normally receive the value undefined, unless default parameters or other logic provide a different result.
Return Values in JavaScript Functions
A return value is the result a function sends back to the code that called it. JavaScript uses the return statement to send a value back.
A function can return a number, string, Boolean value, object, array, or another value.
Example of a Return Value
function addNumbers(a, b) {
return a + b;
}
let result = addNumbers(10, 20);
console.log(result);
Output:
30
In this example, the function calculates a + b and returns the result. The returned value is stored in the result variable.
Displaying a Return Value
You can also pass the function call directly to console.log().
function square(number) {
return number * number;
}
console.log(square(5));
Output:
25
The square() function returns the square of the supplied number.
Difference Between return and console.log()
The return statement and console.log() have different purposes.
returnsends a value back to the caller.console.log()displays a value in the console.
Consider this example:
function add(a, b) {
return a + b;
}
let total = add(5, 10);
console.log(total);
Output:
15
The returned result can be stored, compared, or used in another calculation.
For comparison, consider a function that only displays the result:
function add(a, b) {
console.log(a + b);
}
let total = add(5, 10);
console.log(total);
Output:
15
undefined
The first line displays 15 from inside the function. The second displays undefined because the function does not explicitly return a value.
Returning a Value Stops Function Execution
When JavaScript executes a return statement, the function finishes immediately. Statements after that return statement in the same execution path do not run.
function checkNumber() {
return 100;
console.log("This message will not appear.");
}
console.log(checkNumber());
Output:
100
The function returns 100 and exits before reaching the console.log() statement inside it.
Default Parameters in JavaScript
Default parameters allow you to specify fallback values for function parameters. If an argument is omitted or its value is undefined, JavaScript uses the default value.
Default parameters are useful when a function should work even if the caller does not provide every argument.
Example of Default Parameters
function greetUser(name = "Guest") {
console.log("Hello, " + name + "!");
}
greetUser("Karim");
greetUser();
Output:
Hello, Karim!
Hello, Guest!
In this example, "Guest" is the default value for name. When the function is called without an argument, JavaScript uses that default.
Default Parameters with Multiple Values
You can define default values for multiple parameters.
function calculateTotal(price, quantity = 1) {
return price * quantity;
}
console.log(calculateTotal(100, 3));
console.log(calculateTotal(100));
Output:
300
100
In the first call, price is 100 and quantity is 3, so the result is 300.
In the second call, the quantity argument is omitted. JavaScript uses the default quantity of 1, so the result is 100.
Passing undefined to a Default Parameter
Default parameters also apply when the corresponding argument is explicitly undefined.
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet(undefined);
greet(null);
Output:
Hello, Guest
Hello, null
The first call uses "Guest" because the argument is undefined. The second call uses null because null is an explicitly supplied value, not undefined.
Important: Default parameters apply to omitted arguments and arguments whose value is undefined. They do not automatically replace null, 0, false, or an empty string.
Complete Example of JavaScript Function Fundamentals
The following example combines function declarations, parameters, arguments, return values, and default parameters in a simple shopping calculation.
function calculatePrice(price, quantity = 1) {
return price * quantity;
}
function displayBill(name, total) {
console.log("Customer: " + name);
console.log("Total price: ₹" + total);
}
const total = calculatePrice(200, 3);
displayBill("Karim", total);
Output:
Customer: Karim
Total price: ₹600
How the Program Works
calculatePrice()is a function declaration with two parameters.pricereceives200, whilequantityreceives3.- The function returns
200 * 3, which is600. - The returned value is stored in the
totalvariable. displayBill()receives the customer’s name and the calculated total.- The function displays the customer’s name and the total price.
If you call calculatePrice(200) without supplying the quantity, the function uses the default quantity of 1 and returns 200.
This example shows how small, reusable functions can work together to perform a larger task.
Frequently Asked Questions
What is a function in JavaScript?
A function is a reusable block of code that performs a specific task. You can define it once and call it whenever you need that functionality.
What is the difference between a function declaration and a function expression?
A function declaration defines a named function using the function keyword. A function expression creates a function as part of an expression, commonly assigning it to a variable.
What is the difference between function parameters and arguments?
Parameters are placeholders declared in the function definition. Arguments are the actual values or expressions supplied when calling the function.
What does the return statement do in JavaScript?
The return statement sends a value back to the caller and ends the function’s current execution. If a function does not return a value explicitly, its result is undefined.
What happens if a JavaScript function is called without an argument?
If an argument is omitted, the corresponding parameter receives undefined unless a default parameter or other function logic supplies a value.
What are default parameters in JavaScript?
Default parameters specify fallback values for parameters when the corresponding argument is omitted or evaluates to undefined.
Can a JavaScript function return multiple values?
A function returns one value directly. However, you can return an array or object containing multiple values.
function getDetails() {
return {
name: "Karim",
age: 22
};
}
console.log(getDetails());
Output:
{ name: 'Karim', age: 22 }
Can a JavaScript function be called multiple times?
Yes. A function can be called multiple times, with the same or different arguments, as long as it is accessible in the current scope.
Why are functions important in JavaScript?
Functions help organize code, reduce repetition, improve readability, and make programs easier to test, reuse, and maintain.
4 thoughts on “JavaScript Functions”
Comments are closed.