Sum of Two Numbers

Program to add two numbers

BeginnerTopic: Basic Programs
Back

JavaScript Sum of Two Numbers Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Adding two numbers
let num1 = 10;
let num2 = 20;
let sum = num1 + num2;

console.log("Sum of", num1, "and", num2, "is:", sum);

// Using template literal
console.log(`Sum of ${num1} and ${num2} is: ${sum}`);
Output
Sum of 10 and 20 is: 30
Sum of 10 and 20 is: 30

Understanding Sum of Two Numbers

This program demonstrates basic arithmetic operations in JavaScript.

Arithmetic Operators

JavaScript supports standard arithmetic operators:

+: Addition
-: Subtraction
*: Multiplication
/: Division
%: Modulus (remainder)
**: Exponentiation (power)

Number Data Type

JavaScript has one number type that handles both integers and floating-point numbers:

let integer = 42;
let decimal = 3.14;
let negative = -10;

Variable Assignment

The = operator assigns a value to a variable:

let result = num1 + num2;

Order of Operations

JavaScript follows standard mathematical order:

1.Parentheses
2.Exponentiation
3.Multiplication/Division
4.Addition/Subtraction

Example:

let result = 2 + 3 * 4; // 14, not 20
let result2 = (2 + 3) * 4; // 20

Type Coercion

JavaScript automatically converts types when needed:

"5" + 3; // "53" (string concatenation)
"5" - 3; // 2 (number subtraction)

Be careful with type coercion - use explicit conversion when needed!

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Sum of Two Numbers

This JavaScript program is part of the "Basic Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents