Hi Friends 👋,

Welcome To Infinitbility! ❤️

To add string to array in node js, just use the push() method it will add your data into an array as the last element.

Like the following example, we can add string to array using the push() method.

let arr = ["infinitbility","aguidehub"];

arr.push("sortoutcode");

console.log(arr); // ['infinitbility', 'aguidehub', 'sortoutcode']

Today, I’m going to show you How do i add string to array in node js, as above mentioned here, I’m going to use the push() method for adding new elements into the array.

Let’s start today’s tutorial how do you add string to array in node js?

In this example, we will do

  1. Create a sample array variable with sample data
  2. Add a new element into the array variable using the push() method
  3. ouput return in the response

Let’s write code…

var http = require("http");

//create a server object:
http
  .createServer(function (req, res) {
    let newArr = ["infinitbility","aguidehub"];
    newArr.push("sortoutcode");

    res.write(JSON.stringify(newArr));
    res.end(); //end the response
  })
  .listen(8080); //the server object listens on port 8080

Note: We used JSON.stringify() method only to show output in the response

As mentioned above, we are taken the example of an array of strings, use the push() to add an element, and printed it on the screen.

I hope it helps you, All the best 👍.