JavaScript Operators

previous next


Arithmetic Operators

The initial values of x and y used in the examples of the following table are: x=7 and y=3.

Operator

Description

Example

Result

+ Addition x+y 10
- Subtraction x-y 4
* Multiplication x*y 21
/ Division x/y 2.3333
% Modulus (division remainder) x%y 1
++ Increment x++ x=8
-- Decrement y-- y=2

 

Assignment Operators

Operator

Example

Is The Same As

= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y

 

Comparison Operators

The initial values of x, y, and z used in the examples of the following table are: x=7, y=3, and z="7".

Operator

Description

Example

== is equal to x==y returns false
=== is equal to (checks for both value and type) x==z returns true
x===z returns false
!= is not equal x!=y returns true
> is greater than x>y returns true
< is less than x<y returns false
>= is greater than or equal to x>=y returns true
<= is less than or equal to x<=y returns false

 

Logical Operators

The initial values of x and y used in the examples of the following table are: x=7 and y=3.

Operator

Description

Example

&& and (x==7 && y>2) returns true
|| or (x<5 || y>10) returns false
! not !(x<y) returns true

 

String Operator

A string is most often text, for example "Hello World!". To stick two or more string variables together, use the + operator.

one="Imagination is very important"
two="than knowledge."
three=one+" "+two

The variable three now contains "Imagination is very important than knowledge.".

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax

variableName=(condition)?value1:value2

Example

sign=(x<0)?"Minus (-)":"Plus (+)"

If the variable x is less than 0, then put the string "Minus (-)" in the variable named sign. If the variable x is not less than 0, then put the string "Plus (+)" into the variable named sign.


Try it

To see how HTML and JavaScript work, you can only push the submit button, or you can make your own HTML and JavaScript code.

           

 


previous next