JavaScript Variables and Operators

Some of the JavaScript example we have treated above does very little, but when it come to doing more important stuff we cannot but mention variables and operator, any one with programming background would not find this terms new.

What is variable and what are they use for?

I will like you to see variable as a container for holding information until they are needed.

Remember in mathematics we do something like a = 1, b = 3 and c = a + b

You can see that a, b and c are use to hold value or expression and to reference the value or expression when it is needed same is applicable in programming.

Just like mathematics, every variable must have a name for example; a, y, country, first_name. However when it come to variable name some rule must be observed.

A variable name must NOT start with a number.


Bad variable name

Acceptable variable name

1car

car1

800

score_value

3street

street3



A variable name must NOT contain an OPERATOR.

Operators are manful symbols use for carrying out operations.
For the example + (plus sign), - (minus sign), = (equal sign) among other we will discuss more about JavaScript operators in the next chapter. 


Bad variable name

Acceptable variable name

toy-name 
(the minus ( - ) sign will cause an error)

toy_name
(better still use the underscore ( _ ) sign)



A variable name should not contain a JavaScript keyword or function.

Remember the Date() we use earlier to display the date and time is a typical example of a JavaScript keyword or function, JavaScript has many keywords we shall dabble into some more keyword later in this book.

Bad variable name

Acceptable variable name

Date() 
(a JavaScript function, will cause an error)

date
(better still just “date” without the brackets)


Use a meaningful variable name
Although this naming rule will not cause error if ignore, but it is observed that a meaningful name will make your program to be easily understood and manage.

In the example below using a variable name y will have an ambiguous meaning compare to variable name   


Poor variable name

Better variable name

y = “ben”       

name = “ben”

value12

total

 

Declaring or creating and using a variable
The programming term use for creating variable is called declaring variable. So in JavaScript you declare a variable using the var keyword.

For example
var name;
var total = 0;

Note that the first variable name was declare without assigning any value to it, while the second variable total is declare and initialize to 0; that is was assign the value of 0 during declaration.

The example below demonstrates another interesting may to declare multiple variables with one var keyword, and also go a step further to carry out some little math operation.

<html>
<head>
<title> JavaScript Sample</title>
</head>
<body>
         <script type="text/javascript">
         <!--        
           var num1, num2, ans;
           num1 = 2;
           num2 = 10;
           ans = num1 * num2;
           document.write("<b>The multiplication  is:</b> " + ans);
  //-->
</script>
</body>
</html>


As you can see the first line declare three variables, the next two lines add values 2 and 10 to both variables num1 and num2 respectively, while fourth line, multiply ( * ) both variables and store it value to variable ans, while the last line document.write("<b>The multiplication is:</b> " + ans); display the result or value of variable ans, with the message The multiplication is: in bold (see the <B> tag), this message is joint  using the concatenation sign ( + ) with the variable ans. The output should be 20, and the screenshot should be like the one below.

 

JavaScript Operators
In the last exercise, we make use of equal or assignment sign ( = ), addition sign ( + ) and even multiplication ( - ) sign, all these are known as operators. We will be discussing more JavaScript operators below:

Arithmetic Operators: arithmetic operators are used to perform arithmetic between variables and/or values.


Sign

Meaning

Example

 

*

Multiplication

a=9*2

a=18

+

Addition

a=9+2

a=11

-

Subtraction

a=9-2

a=7

/

Division

a=9+2

a=4.5

%

Modulus (division remainder)

a=9%2

a= 1
(1 means there is remainder)

 

 

a=10%2

a=0;
(0 means there is no remainder)

++

Increment

b=9;
a = ++b;

a=10
(b was increase by 1 before added to a)

 

 

b=9;
a = b++;

a=9

--

Decrement

b=9;
a = --b;

a=8

 

 

b=9;
a = --b;

a=9



Comparison Operators: comparison operators are used in logical statements to determine equality or difference between variables or values.


Sign

Meaning

Example

==

Equal to

10 == 10 is true
10 == 15 is false

!=

Not equal to (opposite of == )

10 != 15 is true

Greater than

10 > 5 is true

Less than

10 < 5 is false

>=

Greater than or equal to

10 >= 15 is false

<=

Less than or equal to

10 <= 15 is true

The comparison operators is often use with conditional statements to compare values and take action depending on the result, see the example below.

if (scrore <= 20) {
     document.write("Sorry you have failed this course");
}else{
document.write("Congratulations! You have passed");
}


The IF …. ELSE statement is a typical example of a conditional statement, that uses a comparison operator <= to compare or check if the value of the variable “score” is less than or equal to 20, if the condition resulted to TRUE that if, IF score is LESS THAN or EQUAL to 20 then the message “Sorry you have failed this course” should displayed ELSE the message “Congratulations! You have passed”.

Logical Operators: I love to relate logical operator to what goes on in human mind when making decision, as a logical being for example, should I remain in Lagos OR return to Anambra (that’s my state of origin). Another example is that if I could not pass the WAEC exam AND I could not get that job, then I should consider going to acquire more training or skill.

Logical operators are used to determine the logic between values, expressions or variables.

Let’s assume that variable a=10 and b=5 then:


Sign

Meaning

Description

&&

AND

TRUE RESULT: both operands must be TRUE for the result can be TRUE
Example:
(a > 5) && (b == 5)  TRUE   :     (TRUE and  TRUE = TRUE)

FALSE RESULT: If either of or both operands is FALSE then the result will be FALSE
Example
(a > 5) && (b > 5)  FALSE    :    (TRUE and    FALSE = FALSE)
(a > 10) && (b > 5) FALSE   :    (FALSE  and  FALSE = FALSE)

||

OR

TRUE RESULT: If either or both operand are TRUE then the result will be TRUE
Example:
(a > 5) || (b == 5)  TRUE        (TRUE or  TRUE = TRUE)
(a > 5) || (b > 5)  TRUE        (TRUE or  FALSE = TRUE)

FALSE RESULT: If both operands are FALSE, then the result would be FALSE
Example:
(a > 10) || (b > 5) FALSE       (FALSE or FALSE = FALSE)

!

NOT (negation)

NOT operator only takes one operand and negate its result
Example:
(a>50)  FALSE
The example above would result to FALSE because 10, which is the value of a, is not greater than 50; but when we introduce the NOT or Negation operator the result would be changes to the opposite TRUE. Example below.
!(a > 50) TRUE

More example
!(b < 7) FALSE
!(a == b) TRUE


Just like the comparison operators, the logical operator is use in conditional statements; this is simply because the logical operator is use along with the comparison operator to carry out more complex operations. See some examples below.

var waec = “pass”;
var jamb = “pass”;
If ((waec == “pass”) && (jamb == “pass”)) {
        document.write("Congratulation, you have gained admission to the higher institution ");
}else {
       document.write("No problem! Go acquire some skills and take the exam next time");
}


In the example above, I try to do away with the normal use of mathematics and number, because not all of us like this subject, but instead I use what most of us are use to, The program declare two variables and assign string (a text) “pass”, not number now!. And    compare them using == (equal or same as) operator to check is their value is “pass” if both operand a TRUE, as a result of the AND && operator then the message ("Congratulation, you have gained admission to the higher institution " will be displayed on the screen, else the message ("No problem! Go acquire some skills and take the exam next time" will be displayed on the screen.

Sometime we programmer adopt a style and examples that has to do with our personal experience or what we see around us. That’s why I consider programming more as an art than science, (this must have been because I had the opportunity to be in both field)
The sample program about WAEC, JAMB, admission and skill is from my personal experience. I had to write WAEC three times before passing it and JAMB once; this is the hurdle that any one aspiring to go into University, polytechnic or colleges in Nigeria must go through, while doing this I made a decision earlier to acquire a computer skill, while I go through the process; so that I don’t get too frustrated by the exam experience and at the same pursue my dream, is been more than 10 years and it all feels good!


Next »


Adding interaction using JavaScript »

Integrating JavaScript to your webpage »

Showing something on the screen »

Variables and Operators »

Decision »

Form Handling »

Looping »

Function »

Events »

Handling error »

Using Objects »