Ads Top

Node Basics: Add Numbers Provided From Command Line

I was recently browsing around for some resources to practice some basic(and not so basic) practice examples/courses. I came across More specifically, this section, the workshoppers section. Basically, these are npm modules you can install globally and they each have individual sections that you can solve and move on.

During downtime, and because you don't do challenges like this everyday, I will work on one or two and post solutions that I find interesting enough to post. The first one I am going to do is the learnyounode track.
All of these challenges can be solved by installing node on your machine and running node from the command line.

The Problem
Write a program that accepts numbers from the command line when calling your script. These numbers should be added and display the sum of the numbers given.

Run the program like this from the command line

node program.js 1 2 3

Get the arguments like this


Keep in mind that the arguments are presented as an array, and the list of numbers to be added do not start until array element 2. Also, they are stored as strings.

For example - when running node program.js 1 2 3 and getting the arguments via console.log(process.argv)
It will actually look like this
[ 'node', '/path/to/addarguments.js', '1', '2', '3' ]

Notice the numbers are strings. We need to be able to add those as numbers so we need to account for that.

Walking through a solution
1: Get the arguments padded in
2: Slice the array so that it starts at element 2 and then get the length
3: Use forEach to loop over the arguments and add them to a sum variable
4: Print the answer

Calling this with the example from above
node program.js 1 2 3
The result would read
The sum = 6


  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai

  2. I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much.
    WordPress development company in Chennai


Powered by Blogger.