homepage Welcome to WebmasterWorld Guest from 54.226.213.228
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Javascript Jumpstart - Operator Basics
Issue #4 - moving beyond copy and paste
tedster




msg:1494410
 8:18 am on Jul 28, 2003 (gmt 0)

Javascript Jumpstart #4
Operator Basics

If you're already writing your own javascript from scratch, or are familiar with programming in almost any language, then this column may not be for you. But if you're mostly a copy and paste type and you wish you could understand more about what those lines of javascript really say -- then learning the operators can be a valuable starting place.

Hope this post helps you make sense out of those lines of js you copy from here and there.

What Is An Operator?
In programming, an operator is an entity that performs some operation on an "operand" -- an element or group of elements of some kind. It is common for an operator to combine two operands to generate a new value - that type of operator is called a binary operator. A simple example of a binary operator in arithmetic is the basic addition operator (+). As we all know, it takes two numbers and generates a third number which is their sum.

In javascript some operators only transform one single element - they are known as unary operators. A simple unary operator is the minus sign, which reverses the sign of any expression it is applied to.

And finally, javascript supports a three-way, or ternary operator -- we'll get around to that one at the end of this post.

Don't assume too much
Javascript makes use of some of some very familiar symbols as operators. But those symbols often have slightly different meanings than what you expect from your familiarity with arithmetic. Without exact knowledge of the operators, a line of javascript can make less sense than a political speech made in Pig Latin.

So here's a list of the most common operators. There are more operators than these, and there are also lots of fine points to grasp when you really get into the nitty gritty of it all. But just this much information will improve your ability to move past the copy and paste stage and give you a fighting chance when you need to make small changes.

Computational Operators
These operators perform a computation, and the basic four are certainly the easiest to understand, since they look just like a line of arithmetic. Note, however, that the
+ operator can also be used even if the variables are not numeric -- it can "add" two character strings together -- concatenating them into a new string.

+
Adds two elements together

Examples:
counter+2 increases the current value of the variable "counter" by 2
"first"+"name" returns the character string "firstname"

-
Subtracts the right hand element
from the left hand element.

Example:
counter-2 decreases the current value of the variable "counter" by 2

*
Multiplies the two elements together.

Example:
counter*2 doubles the current value of the variable "counter"

/
Divides the left hand element by
the right hand element.

Example:
counter/2 divides the current value of the variable "counter" by 2

Shorthand Computation
Next we have a few shorthand computations done with operators.
These are a little less familiar when you first run into them.

++
Adds one to the value of an element.

There are two ways of applying this operator.

1) When an element follows the doubled plus sign,
its value is first increased by one and then the
newly calculated value is returned.

2) When an element precedes the doubled plus sign,
then the current value of that element is returned
BEFORE the addition takes place.

Examples:
++counter increases the current value of the variable "counter" by 1 and returns that new result. If counter is equal to 7 when this line is parsed, the value of counter becomes 8, and 8 is returned.

counter++ first returns the present value of "counter" and then increases the current value by 1. If counter is equal to 7 when this line is parsed, 7 is returned and then the value of counter becomes 8.

--
Subtracts one from the value of an element.

There are also the same two ways of applying
this operator.

1) When an element follows the doubled minus
sign, it's value is first decreased by one and
then the newly calculated value is returned.

2) When an element precedes the doubled minus
sign, then the current value of the element is
returned BEFORE the subtraction takes place.

Examples:
--counter decreases the current value of the variable "counter" by 1 and returns that new result. If counter is equal to 7 when this line is parsed, the value of counter becomes 6, and then 6 is returned.

counter-- first returns the present value of "counter" and then decreases the current value by 1. If counter is equal to 7 when this line is parsed, 7 is returned first, and then the value of counter becomes 6.

Assignment Operators
These operators are used to set an expression equal to a certain value.

=
This familiar symbol sets the element
on its left side to be equal to the value
on its right side.

Javascript is very flexible with data types, so the same operator can be used for assigning numerical values, character string values, or Boolean values.

In fact, a variable can legally be re-assigned to a different data type after it has been declared -- and this is not at all the case at all in many programming languages.

Examples:
counter = 1 sets the variable named "counter" to a numerical value of 1
lastname = "Johnson" sets the variable named "lastname" to a value of "Johnson"
cookie = false sets the variable named "cookie" to a Boolean value of false.

+=
This doubled symbol is a shortcut
for adding to the current value.

Example:
counter += 3 adds 3 to the current value of "counter".
So if counter was equal to 6 before this line of code is executed, afterwards counter is now set equal to 9. That's just a bit weird the first time you see it, isn't it?

-=
This doubled symbol is a shortcut for
substracting from the current value.

Example:
counter -= 2 subtracts 2 from the current value of "counter".
So if counter was equal to 6 before this line of code is executed, afterwards, counter is now assigned a value of 4.

*=
This doubled symbol is a shortcut for
multiplying the current value by some
factor

Example:
counter *= 3 multiplies the current value of "counter" by three.
So if counter was equal to 6 before this line of code is executed, afterwards, counter is now set to 18.

/=
This doubled symbol is a shortcut for
dividing the current value

Example:
counter /= 2 divides the current value of "counter" by 2.
So if counter was equal to 6 before this line of code is executed, afterwards, counter is now set equal to 3.

Comparison Operators
These operators compare the left and right operands and return a Boolean value of "True" if the entire statement evaluates as true. They are commonly used to discover if a certain condition is true (or false), so that a line of code is executed only in that case.

==
The double equal sign is a test
for equality.

Remember that the single equal sign is an assignment operator. It actually gives the left side a new value, dicatated by the expression on the right side. So when javascript wants to test for equality, this doubled sign is used.

Example:
counter == 3 returns a value of "True" if and only if the current value of counter is actually 3.

!=
This doubled sign is a test for
inequality; you can read it as
"is not equal to".

Example:
counter!= 3 returns a value of "True" if and only if the current value of counter is NOT equal to 3.

===
The tripled equal sign is a test for
identity. Identity is a stricter test
than simple equality.

To understand the difference between equality and identity, remember that javascript is very loose about data types. You can have a variable named "t" that stands for the character "2" and without any extra statements, you can use the expression t+3 and javascript will turn "t" into a numeric instead of a character.

This looseness can trip you up at times, generating nasty surprises when you don't keep it in mind. But this freedom with data types does make for very compact code. OK, so back to identity.

Example
expression1 === expression2 will evaluate as true only if the two expressions are identical without going through any data type conversion. There is also a non-identity operator, written as !==. As you have probably guessed by now, the exclamation point means "not" in javascript.

>
This familiar symbol from algebra
is a test for "greater than".

Example:
counter > 3 returns a value of "True" if and only if the current value of counter is greater than 3.

<
This familiar symbol from algebra
is a test for "less than".

Example:
counter < 3 returns a value of "True" if and only if the current value of counter is less than 3.

>= and <=
These two operators check for exactly
what you might think - they test for
"greater than or equal to" and
"less than or equal to".

Example:
counter >= 3 returns a value of "True" if and only if the current value of counter is greater than 3.

Logical Operators
These operators look at expressions and return a Boolean value of "True" or "False".

&&
The doubled ampersand returns a value
of "True" only when both sides of the
expression are True. Think of it as
saying "and"

Example:
day='Friday' && date=13 returns a value of "True" if and only if the day is Friday and the date is 13.


The doubled pipe returns a value of
"True" if either side of the expression
is True. Think of it as saying "or"

Example:
day='friday' date=13 returns a value of "True" if the day is Friday or the Date is the 13th. It could be Friday the 21st, or Tuesday the 13th. Watch out for bad information on this operator -- partly due to a buggy implementation in Netscape 2 and 3.

So some authors claim that my example should evaluate as False if today is both Friday and the 13th -- and that's just not so, they're wrong. If either or both sides of the operator are True, the entire expression evaluates as True.

What the javascript engine actually does is evaluate the left hand side first. If that expression is True, then the whole operation stops and the right side is not even evaluated. A value of True is immediately returned.

---------------------------------

There are many other operators I'm not getting to -- for instance, there's the period . which takes the left hand side and accesses the right side as a "property of". There's [ ] which designates an array and can contain an array element. There's ( ), which designates a javascript function call and may contain arguments for that function. But all of this gets into more complex territory, and I want to stay basic here.

But before I sign off, I promised you the ternary operator, an operator that works with three elements at once.

---------------------------------

?:
This is a very useful shorthand expression.
It can be replaced by a group of "if - then"
statements, but that can get into very bulky
code very fast.

In use, this operator takes the form expression1 ? expression2 : expression 3. Expression1 must be a Boolean - that means it must evaluate to either True or False. If expression1 is True, the ternary operator will return expression2 as a result. If expression1 is False, then the ternary operator will return expression3 as a result.

Example:
(counter>10)? (counter=0) : (counter++) If the value of the variable named "counter" is greater than ten, then counter is reset to zero. If the value of counter is not greater than ten, then its value is increased by one.

If this is your first foray into javascript, I've probably given you more than enough to digest. So until next time, I'm signing off.

[edited by: tedster at 6:41 pm (utc) on Feb. 3, 2006]

 

tedster




msg:1494411
 9:53 pm on Jul 28, 2003 (gmt 0)

By the way, next time I plan on covering some of the odd things that come up when using these basic operators -- sometimes it just doesn't work the way you think it should, and there are common patterns that are helpful to understand.

If anyone has any ideas for future JavaScript JumpStart topics, feel free to let us know.

ytswy




msg:1494412
 9:14 am on Jul 29, 2003 (gmt 0)

Just want to say what a great post this is! Cleared up a number of things I've been wondering about for some time :)

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved