Sponsored Ad

Sunday, December 27, 2009

JavaScript Operators

Operators in JavaScript are very similar to the operators appearing in other programming languages. The definition of an operator is a symbol that is used to perform an operation. Very often these arithmetic operations (addition, subtraction, etc.), but not always.

JavaScript Arithmetic Operator Chart

       Operator                English                    Example
       +        Addition               2+4
       -        Subtraction               6-2
       *        Multiplication               2*2
       /        Division               15/3
       %        Modulas               43%10

% Module may be a new venture for you, but is a special way of saying "find the rest." When run as a division 15 / 3 gets 5, exactly. However, if you get a 43/10 answer to one decimal, 4.3. 10 passes to 40 in five times and then there is a surplus. This is what is left over is returned by the operator module. 43% 10 would be 3.

 

How to JavaScript Operator Example with Variables

Performing operations on variables that contain values is very common and easy to do. Below is a simple script that performs all basic arithmetic operations.

HTML & JavaScript Code:

<body>

<script type="text/JavaScript">

<!--

var two = 2

var ten = 10

var linebreak = "<br />"

document.write("two plus ten = ")

var result = two + ten

document.write(result)

document.write(linebreak)

document.write("ten * ten = ")

result = ten * ten

document.write(result)

document.write(linebreak)

document.write("ten / two = ")

result = ten / two

document.write(result)

//-->

</script>

</body>

Display:

two plus ten = 12
ten * ten = 100
ten / two = 5

Comparison Operators

The comparisons are used to verify the relationship between variables and / or values. A single equal sign sets a value, while a double equals sign (= =) compares three values. Comparison operators are used inside conditional statements and evaluate to true or false. Will talk more about conditional statements in the upcoming lessons.

   Operator      English        Example         Result
     = =     Equal To    x = = y     false
     !=     Not equal to    X!=y     true
     <     Less then    X<y      true
     >    Grater then    x>y      false
    <= Less Than or Equal To    x <= y      true
    >= Greater Than or Equal To    x >= y      false

0 comments:

Post a Comment

Sponsored Ad

More Related Articles

Website Update

Followers