Adding two numbers is one of the first "real" programs beginners write because it introduces variables, the + operator, and how JavaScript reads input. Below you'll find the simplest version using fixed numbers, followed by a version that reads two numbers typed by the user at the command line.

Program to Add Two Numbers in JavaScript

// Two numbers stored in variables
let num1 = 12;
let num2 = 25;

// The + operator adds them
let sum = num1 + num2;

console.log("Sum:", sum);

Output:

Sum: 37

One subtlety worth knowing early: the + operator in JavaScript also concatenates strings, so "12" + 25 would produce the string "1225", not 37. If your numbers might arrive as strings (for example, from a form field or the command line), convert them first with Number() or parseInt().


Reading Two Numbers from the Command Line (Node.js)

// Run with: node add.js 12 25
const num1 = Number(process.argv[2]);
const num2 = Number(process.argv[3]);

const sum = num1 + num2;

console.log(`Sum of ${num1} and ${num2} is ${sum}`);

Output:

Sum of 12 and 25 is 37

This version uses process.argv to read command-line arguments and a template literal (the backtick string with ${} placeholders) to build the output message, both of which you'll see throughout the rest of this series.