JavaScript Functions: Basics and Examples
Published June 15, 2024 at 7:42 pm

JavaScript Functions: Basics and Examples
Understanding JavaScript functions is essential for any developer aiming to write clean, efficient, and reusable code.
Functions allow you to encapsulate code for better readability and reuse.
They also make your code modular, simplifying debugging and testing processes.
In this guide, we will explore basic and advanced examples of JavaScript functions.
Along the way, you will learn about function declarations, function expressions, arrow functions, and some best practices.
Let’s dive in.
What Are JavaScript Functions?
A JavaScript function is a block of code designed to perform a particular task.
It is executed when something invokes (calls) it.
Function Declaration
A function declaration is the most common method of defining a function.
It starts with the function
keyword and is followed by the function name, parameters, and the function body.
// Function Declaration
function greet(name) {
console.log("Hello, " + name);
}
// Calling the function
greet("John");
In this example, the greet
function takes a parameter name
and logs a greeting message to the console.
To invoke the function, we simply call it by its name followed by parentheses.
Function Expression
Function expressions are another way to define functions in JavaScript.
Unlike function declarations, function expressions are not hoisted to the top of the scope.
// Function Expression
const greet = function(name) {
console.log("Hello, " + name);
};
// Calling the function
greet("Jane");
Function expressions are useful when you want to define a function and assign it to a variable.
This can be particularly handy for creating inline functions or passing functions as arguments to other functions.
Arrow Functions
Arrow functions, introduced in ES6, provide a shorter syntax for writing functions.
They are particularly useful when writing concise one-liner functions.
// Arrow Function
const greet = (name) => {
console.log("Hello, " + name);
};
// Calling the function
greet("Alice");
In this example, the arrow function greet
takes a parameter name
and logs a greeting message to the console.
Arrow functions also lexically bind the this
value, making them useful for handling this
in callbacks.
Parameters and Arguments
Functions can take parameters, which are specified within the parentheses in the function definition.
When a function is called, the values passed are known as arguments.
// Function with Parameters
function add(a, b) {
return a + b;
}
// Calling the function with Arguments
console.log(add(5, 3)); // Outputs: 8
In this example, the add
function takes two parameters a
and b
and returns their sum.
We call the function with arguments 5
and 3
, and the function returns 8
.
Default Parameters
JavaScript functions can have default parameter values.
This allows you to define a default value for a parameter if no argument is passed.
// Function with Default Parameters
function greet(name = "Guest") {
console.log("Hello, " + name);
}
// Calling the function without arguments
greet(); // Outputs: Hello, Guest
In this example, the greet
function has a default parameter value of "Guest"
.
If no argument is passed, the function uses the default value.
Rest Parameters
Rest parameters allow a function to accept an indefinite number of arguments as an array.
// Function with Rest Parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// Calling the function
console.log(sum(1, 2, 3, 4)); // Outputs: 10
In this example, the sum
function uses the rest parameter ...numbers
to accept multiple arguments.
The function then uses the reduce
method to calculate the sum of all the numbers.
Returning Values
Functions can return values using the return
statement.
When a function returns a value, you can capture and use that value in your code.
// Function that Returns a Value
function multiply(a, b) {
return a * b;
}
// Capturing the returned value
const result = multiply(2, 4);
console.log(result); // Outputs: 8
In this example, the multiply
function returns the product of two numbers a
and b
.
The returned value is then captured in the variable result
and logged to the console.
Immediately Invoked Function Expressions (IIFE)
An IIFE is a function that runs as soon as it is defined.
This is useful for avoiding variable pollution in the global scope.
// IIFE Syntax
(function() {
console.log("IIFE is running!");
})();
In this example, the IIFE is defined and immediately invoked, logging a message to the console.
Using IIFEs can help keep your code clean and modular.
Naming Conventions and Best Practices
When naming functions, use descriptive names that clearly indicate what the function does.
It improves code readability and maintainability.
Pros
- Encapsulation of code.
- Improved readability.
- Reusable code blocks.
- Modular code structure.
Cons
- Overhead in execution time for calls.
- Poorly named functions can confuse code logic.
- Can lead to too many small functions cluttering the codebase.
Best Practices for Writing Functions
Keep functions short and focused on a single task.
Use meaningful and consistent naming conventions for functions and parameters.
Comment your code where necessary to explain complex logic.
Avoid global variables by using local scopes and function parameters.
Test your functions thoroughly to ensure they handle edge cases and errors gracefully.
Frequently Asked Questions
What is a JavaScript function?
A JavaScript function is a block of code designed to perform a particular task. It is executed when something invokes (calls) it.
How do you declare a function in JavaScript?
You can declare a function using the function
keyword, followed by the function name, parameters in parentheses, and the function body in curly braces.
What are function expressions?
Function expressions are another way to define functions. They are not hoisted to the top of the scope and can be assigned to variables.
What are arrow functions?
Arrow functions provide a shorter syntax for writing functions introduced in ES6. They lexically bind the this
value.
How do I return a value from a function?
You can return a value from a function using the return
statement. Capture and use that value in your code where needed.
What are default parameters in JavaScript functions?
Default parameters allow you to define a default value for a parameter if no argument is passed when the function is called.
What are rest parameters?
Rest parameters allow a function to accept an indefinite number of arguments as an array.
What is an IIFE?
An IIFE or Immediately Invoked Function Expression is a function that runs as soon as it is defined, useful for avoiding variable pollution in the global scope.
Advanced Function Techniques
In addition to basic function concepts, you might encounter advanced function techniques in JavaScript.
These techniques help in writing efficient and elegant code.
Higher-Order Functions
A higher-order function is a function that either takes one or more functions as arguments or returns a function as a result.
They are a powerful feature of JavaScript, enabling many functional programming patterns.
// Higher-Order Function Example
function higherOrderFunction(fn) {
return function(x) {
return fn(x);
};
}
const double = higherOrderFunction(function(x) {
return x * 2;
});
console.log(double(5)); // Outputs: 10
In this example, higherOrderFunction
takes a function fn
and returns a new function.
This new function, when called, executes fn
with the given argument.
Closures
A closure is a function having access to the parent scope, even after the parent function has closed.
Closures are useful for creating private variables and functions.
// Closure Example
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // Outputs: 1
console.log(counter()); // Outputs: 2
In this example, the createCounter
function returns a new function that increments and returns the count
variable.
The count
variable is private to the created function.
Callback Functions
A callback function is a function passed into another function as an argument.
Callbacks are commonly used for handling asynchronous operations.
// Callback Function Example
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 2000)
}
fetchData((data) => {
console.log(data); // Outputs: Data received
});
In this example, the fetchData
function takes a callback function as a parameter.
The callback is called after a delay of 2 seconds, simulating an asynchronous operation.
Promises
Promises are used for handling asynchronous operations in JavaScript.
A promise represents an operation that hasn’t completed yet but is expected in the future.
// Promise Example
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise resolved");
}, 2000)
});
promise.then((message) => {
console.log(message); // Outputs: Promise resolved
});
In this example, a Promise
is created that resolves after 2 seconds.
The then
method is used to handle the resolved value.
Async/Await
Async/Await is a modern way to handle asynchronous operations.
It allows you to write asynchronous code that looks synchronous, improving readability.
// Async/Await Example
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data received");
}, 2000)
});
}
async function getData() {
const data = await fetchData();
console.log(data); // Outputs: Data received
}
getData();
In this example, the fetchData
function returns a promise.
The getData
function uses the await
keyword to wait for the promise to resolve and then logs the data.
Function Currying
Function currying is transforming a function that takes multiple arguments into a sequence of functions, each taking a single argument.
This technique is useful for creating specialized functions from a general-purpose function.
// Function Currying Example
function curry(fn) {
return function(a) {
return function(b) {
return fn(a, b);
};
};
}
const add = curry(function(a, b) {
return a + b;
});
const addFive = add(5);
console.log(addFive(3)); // Outputs: 8
In this example, the curry
function takes a function fn
and returns a curried version of it.
The curried function add
creates a specialized function addFive
that adds 5 to its argument.
FAQs
What is a higher-order function in JavaScript?
A higher-order function is a function that takes one or more functions as arguments or returns a function as a result.
What is a closure in JavaScript?
A closure is a function having access to the parent scope, even after the parent function has closed. It is useful for creating private variables.
How do callback functions work in JavaScript?
Callback functions are functions passed into another function as an argument. They are commonly used for handling asynchronous operations.
What are promises in JavaScript?
Promises are used for handling asynchronous operations. A promise represents an operation that hasn’t completed yet but is expected in the future.
What is the benefit of using async/await in JavaScript?
Async/Await allows you to write asynchronous code that looks synchronous, improving the readability of the code.
What is function currying?
Function currying is transforming a function that takes multiple arguments into a sequence of functions, each taking a single argument.
Shop more on Amazon