JavaScript Operators

JavaScript Arithmetic Operators

Arithmetic operators are used to do arithmetic operations on numbers (literals or variables).

	
   Operator Description
	+		Addition
	-		Subtraction
	*		Multiplication
	/		Division
	%		Modulus
	++		Increment
	--		Decrement

Adding

<!DOCTYPE html>
<html>
<body>

<h1>The + Operator</h1>

var score1 = 95;<br />
var score2 = 90;<br />
var total = score1 + score2; <br /><br />
	
Value of total : <span id="element"></span>

<script>
var score1 = 95;
var score2 = 90;
var total = score1 + score2; 
document.getElementById("element").innerHTML = total;
</script>

</body>
</html>

Download the code Run the code

Multiplying

<!DOCTYPE html>
<html>
<body>

<h1>The * Operator</h1>

var length = 15;<br />
var height = 10;<br />
var area = length * height; <br /> <br />
	
Total area : <p id="demo"></p>

<script>
var length = 15;
var height = 10;
var area = length * height;
document.getElementById("demo").innerHTML = area;
</script>

</body>
</html>

Download the code Run the code

JavaScript Assignment Operators

Arithmetic operators are used to do arithmetic operations on numbers (literals or variables).

	Operator	Example  		Operation
	=		Assign			Equals to x = y
	+=		Addition		Equals to x = x + y
	-=		Subtraction		Equals to x = x - y
	*=		Multiplication		Equals to x = x * y
	/=		Division		Equals to x = x / y
	%=		Modulus			Equals to x = x % y

Assignment

<!DOCTYPE html>
<html>
<body>

<h1>The = Operator</h1>

var length = 15;<br />

<span id="demo1"></span> is assigned to variable length<br /><br />
var myname = "Keyur Gohel";<br />
<span id="demo2"></span> is assigned to variable myname

<script>
var length = 15;
var myname = "Kiran Gohel";

document.getElementById("demo1").innerHTML = length;
document.getElementById("demo2").innerHTML = myname;
</script>

</body>
</html>

Download the code Run the code

JavaScript String Operators

The + operator can be also used to add two strings. When + operator is used with strings, it works as concatenation operator

Example

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>

<p>The + operator concatenates (adds) strings.</p>

var string1 = "This is a dog";<br />
var string2 = "and this is a cat.";<br />
var txt = string1 + " " + string2; <br /><br />
txt variable contains : <span id="demo"></span>

<script>
var string1 = "This is a dog";
var string2 = "and this is a cat.";
document.getElementById("demo").innerHTML = string1 + " " + string2;
</script>

</body>
</html>

Download the code Run the code

The result is concatenation of txt1 and txt2 variables

JavaScript Comparison and Logical Operators

	Operator	Description
	==		equal to
	===		equal value and equal type (deep compare)
	!=		not equal
	!==		not equal value or not equal type (deep compare)
	>		greater than
	<               less than 
        >=		greater than or equal to
	<=		less than or equal to
	?		ternary operator
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .