Her

Home Web Programming JavaScript Learning JavaScript Basics - Operators, If/Else

Learning JavaScript Basics - Operators, If/Else

Author: allsyntax.com Author's URL: www.allsyntax.com More by this author

Learning JavaScript Basics - Operators, If/Else Operators, If and If/Else

Now is a good time to discuss operators in JavaScript. I am also doing to discuss If and If/Else statements becuase this is when you are going to use many of these operators. There are several types of operators, and they are listed and described below:

Arithmetic Operators: These are they symbols used to calculate values.

  • "+" Addition
  • "-" Subtraction
  • "*" Multiplication
  • "/" Division
  • "%" Modulus (Takes one number and divides it by another number and places the remainder in the variable.)

If you are unfamiliar with Modulus, heres an example of how it works:

0 = 4 % 3; 1 = 5 % 2; 3 = 21 % 6; 0 = 15 % 3;

In arithmetic conditions, JavaScript follows the order of operations. I think in grade school they tauht it as something like, "Please Excuse My Dear Aunt Sally."

  • Parenthesis ()
  • Unary Operations -
  • Mult. and Division (L to R) * and /
  • Add and subtraction (L to R) + and -

It is useful to be aware of the order of operations when working with more than 2 numbers. Here is an example of what I mean:

a = 5; b = 10; c = ((a + b) * 8) / 2; document.write(c);

Relational Operators: These are used when comparing one or more items and will return a boolean expression.

  • "==" Equals
  • "<" Less Than
  • ">" Greater than
  • ">=" Greater than or Equal
  • "<=" Less Than or equal
  • "!=" Not equal

Logical Operators: used to compare two or more simple conditions at the same time.

  • "& &" = and
  • "||" = or

Something to go along with the logical operators are what are called, "Truth Tables." Truth tables show all possibilties for logical operators when looking at conditions.

& &:
||:
X
Y
X& &Y
X
Y
X||Y
F
F
F
F
F
F
F
T
F
F
T
T
T
F
F
T
F
T
T
T
T
T
T
T

Compound Conditions: This is just where you combine two or more simple conditions with a logical operator. example:

a=3; b=4; c=5; d=2; if ((a ==3) & & (b ==4)) //<--the compound condition e = c + d; else e = c - d; document.write("e="+e);

Increment Operator:

To say, x = x + 1:

++x;

x++;

Say you took: y = x++; Whats going to happen?

y will = x

and then x will = x + 1.

Say you took y = ++x; Whats going to happen?

x will = x + 1

then, y = x.

Decrement Operator:

To say, x = x - 1:

--x;

x--;

If you took y = x--; What will happen?

y will = x

and then x will = x - 1.

If you had y = --x; What happens?

x will = x - 1;

then y will = x.

Not as confusing as you migh think. This will help you when using increment and decrement operators to know the value of your variable through the process of the program.