Sum of Two Numbers
Program to add two numbers
JavaScript Sum of Two Numbers Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// 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}`);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:
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.