Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js Functions

Node.js Functions

A function is a reusable block of code that performs a specific task.

In Node.js, functions are one of the core components of JavaScript and the basic unit for building applications.

Node.js inherits all the function features of JavaScript and plays an important role in its asynchronous programming model.

In JavaScript, a function can be an argument to another function. We can define a function first and then pass it, or define the function directly where the argument is passed.

The importance of functions

Function declaration

Declare a function using the function keyword.

function greet(name) {
    console.log(`Hello, ${name}!`);
}

Function Expressions

Assign a function to a variable.

const greet = function(name) {
    console.log(`Hello, ${name}!`);
};

Arrow Functions

A concise function expression introduced in ES6.

const greet = (name) => {
    console.log(`Hello, ${name}!`);
};

// Single-line arrow function
const greet = name => console.log(`Hello, ${name}!`);

Types of functions

1. Regular functions

The most common form of function, which can have parameters and return values.


function add(a, b) {
    return a + b;
}

2. Anonymous functions

A function without a name, usually passed as an argument to other functions.

setTimeout(function() {
    console.log('This is an anonymous function.');
}, 1000);

3. Callback functions

Passed as an argument to another function and called after an operation completes.


function fetchData(callback) {
    setTimeout(() => {
        const data = 'Some data';
        callback(data);
    }, 1000);
}

fetchData((data) => {
    console.log(data);
});

Asynchronous functions

From callbacks to Promises.

Example

function

readFilePromise

(

path

)

{

 

return

new

Promise

(

(

resolve

,

reject

)

=>

{

    fs.

readFile

(

path

,

'utf8'

,

(

err

,

data

)

=>

{

     

if

(

err

)

reject

(

err

)

;

     

else

resolve

(

data

)

;

   

}

)

;

 

}

)

;

}

Use the async and await keywords to handle asynchronous operations.

Example

async

function

fetchUser

(

id

)

{

   

try

{

       

const

response

=

await fetch

(

`https

:

//api.example.com/users/${id}`);

       

const

user

=

await response.

json

(

)

;

       

return

user

;

   

}

catch

(

error

)

{

        console.

error

(

'Error fetching user:'

,

error

)

;

   

}

}

fetchUser

(

1

)

.

then

(

user

=>

console.

log

(

user

)

)

;

Comparison of calling methods

How to call Example Feature
Directly calling greet('Alice') The most common way
Calling as a method obj.method() this refers to the calling object
Constructor call new Constructor() Create a new instance
Indirect call greet.call(null, 'Bob') Can change what this refers to

Advanced usage

1. Closures

A closure is a function that can remember and access its lexical scope even when it is executed outside that lexical scope.

Example

function

createCounter

(

)

{

    let count

=

0

;

   

return

function

(

)

{

        count

++;

       

return

count

;

   

}

;

}

const

counter

=

createCounter

(

)

;

console.

log

(

counter

(

)

)

;

// 1

console.

log

(

counter

(

)

)

;

// 2

2. Higher-order functions

Functions that accept functions as arguments or return functions.

Example

function

applyOperation

(

a

,

b

,

operation

)

{

   

return

operation

(

a

,

b

)

;

}

const

sum

=

applyOperation

(

5

,

3

,

(

x

,

y

)

=>

x

y

)

;

const

product

=

applyOperation

(

5

,

3

,

(

x

,

y

)

=>

x

y

)

;

console.

log

(

sum

)

;

// 8

console.

log

(

product

)

;

// 15


Function parameter handling

Default arguments

Provide default values for parameters at function declaration.


function greet(name = 'Guest') {
    console.log(`Hello, ${name}!`);
}

greet(); // Hello, Guest!
greet('Alice'); // Hello, Alice!

Rest parameters

Allow an indefinite number of arguments to be represented as an array.

Example

function

sum

(

...

numbers

)

{

   

return

numbers.

reduce

(

(

acc

,

num

)

=>

acc

num

,

0

)

;

}

console.

log

(

sum

(

1

,

2

,

3

,

4

)

)

;

// 10

Destructuring parameters

Extract data from objects or arrays and assign them to variables.

Example

function

getUserInfo

(

{

name

,

age

}

)

{

    console.

log

(

`Name

:

$

{

name

}

,

Age

:

$

{

age

}

`

)

;

}

const

user

=

{

name

:

'Alice'

,

age

:

30

}

;

getUserInfo

(

user

)

;

// Name: Alice, Age: 30


Example

**Single responsibility of functions:** Each function should do only one thing, making it easier to test and maintain.

Example

function

calculateArea

(

width

,

height

)

{

   

return

width

height

;

}

**Avoid global variables:** Minimize the use of global variables; use local variables and function parameters.

Example

function

calculateTotal

(

items

)

{

    let total

=

0

;

   

for

(

const

item of items

)

{

        total

+=

item.

price

item.

quantity

;

   

}

   

return

total

;

}

**Use arrow functions:** Arrow functions are concise and clear, especially when working with callback functions.

Example

const

users

=

[

   

{

id

:

1

,

name

:

'Alice'

}

,

   

{

id

:

2

,

name

:

'Bob'

}

]

;

const

names

=

users.

map

(

user

=>

user.

name

)

;

console.

log

(

names

)

;

// ['Alice', 'Bob']

Error Handling: Use try...catch statements to handle errors that may be thrown.

Example

async

function

fetchUser

(

id

)

{

   

try

{

       

const

response

=

await fetch

(

`https

:

//api.example.com/users/${id}`);

       

if

(

!

response.

ok

)

{

           

throw

new

Error

(

'Network response was not ok'

)

;

       

}

       

const

user

=

await response.

json

(

)

;

       

return

user

;

   

}

catch

(

error

)

{

        console.

error

(

'Error fetching user:'

,

error

)

;

   

}

}

Functions as arguments: Using a function as an argument.

Example

function

say

(

word

)

{

  console.

log

(

word

)

;

}

function

execute

(

someFunction

,

value

)

{

  someFunction

(

value

)

;

}

execute

(

say

,

"Hello"

)

;

In the code above, we passed the say function as the first argument to the execute function. What is passed here is not the return value of say, but say itself!

In this way, say becomes the local variable someFunction inside execute, and execute can use the say function by calling someFunction() (with parentheses).

Of course, since say has a variable, execute can pass such a variable when calling someFunction.

**Anonymous functions:** We can pass a function as a variable. But we don't have to go through the "define first, then pass" cycle; we can define and pass the function directly in the parentheses of another function:

Example

function

execute

(

someFunction

,

value

)

{

  someFunction

(

value

)

;

}

execute

(

function

(

word

)

{

console.

log

(

word

)

}

,

"Hello"

)

;

We defined the function we are about to pass to execute right where execute accepts its first argument.

This way, we don't even need to give the function a name, which is why it is called an anonymous function.


How function passing makes an HTTP server work

With this knowledge, let's take another look at our simple yet not-so-simple HTTP server:

Example

var

http

=

require

(

"http"

)

;

http.

createServer

(

function

(

request

,

response

)

{

  response.

writeHead

(

200

,

{

"Content-Type"

:

"text/plain"

}

)

;

  response.

write

(

"Hello World"

)

;

  response.

end

(

)

;

}

)

.

listen

(

8888

)

;

Now it should look much clearer: we passed an anonymous function to the createServer function.

The same goal can be achieved with code like this:

Example

var

http

=

require

(

"http"

)

;

function

onRequest

(

request

,

response

)

{

  response.

writeHead

(

200

,

{

"Content-Type"

:

"text/plain"

}

)

;

  response.

write

(

"Hello World"

)

;

  response.

end

(

)

;

}

http.

createServer

(

onRequest

)

.

listen

(

8888

)

;


Function best practices

Function design principles

  1. Single Responsibility: A function does only one thing
  2. Reasonable naming: Use the verb + noun form (e.g. getUserInfo)
  3. Control length: It is recommended not to exceed 20 lines of code
  4. Avoid side effects: Pure functions are easier to test and maintain

Performance optimization tips

Example

// Use a closure to cache results

function

memoize

(

fn

)

{

 

const

cache

=

new

Map

(

)

;

 

return

(

...

args

)

=>

{

   

const

key

=

JSON.

stringify

(

args

)

;

   

if

(

cache.

has

(

key

)

)

return

cache.

get

(

key

)

;

   

const

result

=

fn

(

...

args

)

;

    cache.

set

(

key

,

result

)

;

   

return

result

;

 

}

;

}


Hands-on exercises

Exercise 1: Create a temperature conversion function

Example

/**
 * Implement conversion between Celsius and Fahrenheit
 * @param {number} temp - temperature value
 * @param {string} unit - original unit ('C' or 'F')
 * @returns {number} the converted temperature
 */

function

convertTemperature

(

temp

,

unit

)

{

 

// Your code...

}

Exercise 2: Implement a simple event emitter

Example

class

EventEmitter

{

  constructor

(

)

{

   

this

.

events

=

{

}

;

 

}

 

 

// Implement the on/emit/off methods

}