AskHandle

AskHandle Blog

How Do You Write a Function in Node.js?

June 23, 2025Ben Larson3 min read
  • NodeJS
  • Function
  • Coding

How Do You Write a Function in Node.js?

Writing functions in Node.js is a fundamental skill that helps in building efficient and organized code. Functions allow you to reuse code, break complex tasks into smaller parts, and make your scripts easier to understand and maintain. In this article, you will learn how to write functions in Node.js, with clear examples to guide you.

What is a Function in Node.js?

A function is a block of code designed to perform a specific task. Instead of writing the same code multiple times, you can define a function once and call it whenever needed. This makes your code more organized and reduces errors.

In Node.js, functions are written using JavaScript syntax since Node.js runs JavaScript on the server side.

How to Write a Basic Function

Writing a basic function in Node.js is similar to writing in plain JavaScript. Here's a simple example:

js
1function greet(name) {
2  console.log("Hello, " + name + "!");
3}
4
5greet("Alice");

This function, called greet, takes an input called name. When the function runs, it prints a greeting message with the name.

Breakdown:

  • function keyword tells JavaScript you are creating a function.
  • greet is the name of the function.
  • (name) inside parentheses are parameters the function accepts.
  • The code inside the curly braces {} is what the function does.
  • greet("Alice") is calling the function with the argument "Alice".

How to Return Values from Functions

Functions can also return values. Instead of just doing something, they can give back data that you can use later.

js
1function add(a, b) {
2  return a + b;
3}
4
5const result = add(3, 4);
6console.log(result); // Output: 7

In this example:

  • The function add takes two numbers, a and b.
  • It returns their sum with the return statement.
  • When calling the function, store its output in the variable result.
  • Then, log the result to see the output.

Using Arrow Functions

Another way to write functions in Node.js is with arrow functions, introduced in ES6. They are shorter and often used for inline functions.

js
1const multiply = (x, y) => {
2  return x * y;
3};
4
5console.log(multiply(5, 6)); // Output: 30

When the function consists of a single statement, you can even write it more concisely:

js
1const divide = (x, y) => x / y;
2
3console.log(divide(10, 2)); // Output: 5

Arrow functions are popular because of their simplicity and clear syntax.

How to Handle Asynchronous Operations

In Node.js, many tasks such as reading files, querying databases, or making network requests are asynchronous—meaning they don't block the execution of code while waiting for a task to complete. Instead, they run in the background and notify your program when they’re done. This non-blocking behavior is crucial for building fast and scalable applications.

You can handle asynchronous operations using callbacks, promises, or the more modern async/await syntax. Each method has its own use cases and readability advantages.

Using Callbacks

A callback is a function passed as an argument to another function and is executed after the asynchronous task completes.

js
1const fs = require('fs');
2
3function readFileCallback(filename, callback) {
4  fs.readFile(filename, 'utf8', (err, data) => {
5    if (err) {
6      callback(err, null);
7    } else {
8      callback(null, data);
9    }
10  });
11}
12
13readFileCallback('example.txt', (err, data) => {
14  if (err) {
15    console.log('Error reading file:', err);
16  } else {
17    console.log('File contents:', data);
18  }
19});

In this example:

  • fs.readFile reads a file asynchronously.
  • If there's an error (e.g. file not found), it is passed to the callback as the first argument.
  • The file contents, if successfully read, are passed as the second argument.
  • This style can lead to "callback hell" when many asynchronous tasks are nested.

Using Promises and Async/Await

A promise represents the eventual completion (or failure) of an asynchronous operation. Promises allow for a cleaner, more readable syntax, especially when combined with async/await.

js
1const fs = require('fs').promises;
2
3async function readFileAsync(filename) {
4  try {
5    const data = await fs.readFile(filename, 'utf8');
6    console.log('File contents:', data);
7  } catch (err) {
8    console.log('Error reading file:', err);
9  }
10}
11
12readFileAsync('example.txt');

In this version:

  • fs.promises.readFile returns a promise.
  • The async keyword allows the use of await, which pauses the function execution until the promise resolves.
  • try/catch is used to handle errors gracefully.

Advantages of async/await:

  • Synchronous-style syntax makes code easier to follow.
  • Reduces nesting and improves error handling compared to callbacks.

Writing functions in Node.js involves using the function keyword, arrow syntax, or async functions (for asynchronous tasks). Functions help organize your code, reduce repetition, and manage complex operations smoothly.

  • Define functions with function or arrow syntax.
  • Pass parameters to functions for input.
  • Use return to send data back.
  • Handle async operations using callbacks, promises, or async/await.

Starting with simple functions and progressively adopting more advanced techniques makes coding in Node.js manageable and efficient. Practice writing functions for different tasks, and you'll find it becomes an integral part of your development process.