Empowering you to understand your world

Passing Objects As Parameters In Node.js

How to pass an object to another function in Node.js.

Getting Started With Node.js –  Passing Objects As Parameters

Due to the fact that you cannot access objects declared inside another function, you may need to grant other functions access to it. One way to do this in Node.js is by passing the object as a parameter to the function you’d like to use it in. As is indicated by line 1, you will need the http module for this exercise, but don’t worry, it already comes with Node.js.

How to pass an object to another function in Node.js.
How to pass an object to another function in Node.js.

The syntax for that procedure in Node.js is as follows:

sampleFunc(objectToPass);

function sampleFunc(objectToPass) {}

Here’s a working example of that function passing technique:

var http = require('http');

function OnRequest(request, response) {
    sendPage(request, response); //This is where the request and response objects are passed as parameters.
}

function sendPage(request, response) { //Call 'request' and 'response' anything you'd like at this point.
    console.log("Request received.");
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.write('<html>');
    response.write('<head>');
    response.write('<title>My Site</title>');
    response.write('<meta name="viewport" content="width=device-width, initial-scale=1">');
    response.write('</head>');
    response.write('<body>');
    response.write('Hello world!');
    response.write('</body>');
    response.write('</html>');
    response.end();
}

http.createServer(OnRequest).listen(8080); //See what I did there with OnRequest? Functions can be passed like variables too!

In the example code above, the request and response objects are declared in the OnRequest function. This means that they are accessible only from within the OnRequest function. They are passed as parameters to the sendPage function, making them accessible from that function as well. At this point, request and response are local variables, and they are accessible only within those two functions. This technique is an easy way to make your variables/objects accessible wherever you need them, but without declaring them globally. Global variables are not recommended unless necessary.

Further Reading

Learn How JavaScript Functions Work

Learn How JavaScript Variables Work

Official Node.js Docs


Code Successfully Tested Using Node.js Version:

  • 4.2.6.

Leave a Reply

Subscribe to our newsletter
Get notified when new content is published