With this example, we’ll learn how to add two numbers and display their sum using various JavaScript methods.
In order to understand this example, we need to know about the following JavaScript programming topics:
- Variables
- Constants
- Operator
Variables
Variables act as names for values which are used to store strings, numbers, objects, etc which can be changed during program execution.It can be declared using the var
keywords along with variable name.
Declare Variable
var message = "Hello world";
Here we’ve created a variable which holds the value Hello JavaScript with a name of message.
Constants
A constant is the name given to a fixed value that cannot be reassigned or redeclared and that remains unchanged throughout the entire program.We need to use const
keyword to define constant variable.
Example
const message = "Hello world";
Here we have defined constants variable message using const
keyword which contains value Hello world.If we try to change the value of message variable we will get error as we cannot reassign constant
Operators
Operators are symbols or keywords which are used for comparing values, assigning values, performing arithmetic and logical operations.Operators performs some sort of action.
Types of Operators:
- Arithmetic Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Conditional (Ternary) Operator
- typeof Operator
Example of adding two numbers in JavaScript
We need to use +
arithmetic operator to sum two numbers
Define variables
var number1 = 10;
var number2 = 20;
Here we have defined two variables with integer data types and values of 10 and 20
Add two numbers
var sum = number1 + number2;
We define the variable sum, which will be the sum of two variables we defined earlier, number1 and number2.
Show the Results
console.log('The sum is: ' + sum);
Here we have console log the sum variable which will display the result of sum of two variables.
Final Code
var number1 = 10;
var number2 = 20;
var sum = number1 + number2;
console.log('The sum is: ' + sum);
Output
The sum of 10 and 20 is: 30
We have created two variables with static integer values here. Next, we compute the sum of both values and store it in a third variable. The result is then displayed on the console.
Conclusion
In this article, we learned the basics of variables, constants, and operators, as well as how to sum two numbers in Javascript.