How to Add Two Variables in Javascript?

In this blog, we will learn how to add two variables in javascript. Generally, whenever we try to add two numbers in javascript using “+”, we get the result 2+2 = 22. while we expect 4.

So first we have to tell javascript that we want to add integer types value. For this, we can use parseInt().

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

var first_num = parseInt(10);
var second_num = parseInt(10);

alert(first_num + second_num ); 

// should now alert 20


var first_num = 10;
var second_num = 10;

var result = parseInt(first_num) + parseInt(second_num);


Add(concatenate) two strings in Javascript

If you want to concatenate two strings then you can try something like this.

var first_num = "hello";
var second_num = "codermen";

var result = first_num + " " +second_num;


// should now alert hello codermen


let text1 = "Hello";
let text2 = "world!";
let result = text1.concat(" ", text2);

// result should be "Hello world"