1. Technology

JavaScript By Example

7. Operators

By

Operators are what defines the operations to be performed on the variables in your script.

The = operator is the assignment operator and the value from whatever is on the right of this operator is assigned as the value to be contained in the variable to its left.

The + - * / and % operators work with numbers to add, subtract, multiply, divide, and take the remainder respectively.

The + operator also works with text strings to concatenate (join) them together. If either side of the + is a string then the operator will concatenate rather than add.

So this example shows how we can get JavaScript to add 1 and 2 together and concatenate the result to the end of our text giving us "hello world3".

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example 07</title>
</head>
<body>
<div id="ex"></div>
<script type="text/javascript" src="example07.js"></script>
</body>
</html>

JavaScript


var hello, world, count;
count = 1;
count = count + 2;
hello = 'hello';
world = 'world';
document.getElementById('ex').innerHTML =
hello + ' ' + world + count;

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. JavaScript By Example - Operators

©2014 About.com. All rights reserved.