# Lesson 5: Smarter Scripts with Operators

In the previous lesson you already employed an **assignment operator ( = )** and an **arithmetic operator**, specifically the **multiplication operator ( * )**, to write a basic JavaScript shopping cart script.

We can easily see that to do something useful with JavaScript, we need a way to **manipulate** data and variables. We do this with **operators**.

In this lesson you are going to learn how to use:

**arithmetic operators**;**the + sign to concatenate text (concatenation operator)**;**comparison operators**;**logical operators**.

Also, you'll get plenty of opportunities to practice coding with variables. Let's get started!

## Arithmetic operators

As you might have guessed, **arithmetic operators** are used to **perform arithmetic operations between values or variables**. Here's a table for your reference.

If **x = 20, y = 5, and z = result**, we have:

Operator | Java Script Example | Result |
---|---|---|

Addition: + | z = x + y | z = 25 |

Subtraction: - | z = x - y | z = 15 |

Multiplication: * | z = x * y | z = 100 |

Division: / | z = x / y | z = 4 |

Modulus: % | z = x / y | z = 0 |

Increment: ++ | z = ++x | z = 21 |

Decrement -- | z = --x | z = 19 |

I guess you're quite familiar with most arithmetical operators. The odd ones might be the **( % ) modulus**, the **( ++ ) increment**, and the **( -- ) decrement** operators.

**Modulus:** the **remainder** left over after division.

**Increment:** take a number and add 1 to it.

**Decrement:** take a number and subtract 1 from it.

Time to get coding! Get your hands on the text editor and prepare a new HTML document like the one below:

### Try out: add 2 values and print the result

<!DOCTYPE html> <html> <head> <title>Lesson 5: Operators and Comparisons</title> </head> <body> <h1>Lesson 5: Operators and Comparisons</h1> <script type="text/javascript"> //Create and initialize your variables var result = 0; var firstNum = 20; var secondNum = 5; //Addition: result = 25 result = firstNum+secondNum; //write result on the page document.write(result); </script> </body> </html>

Nothing new here except for the JavaScript command **document.write()**. This command is translated by the JavaScript interpreter as saying:

"Hey browser, get the value within brackets and print it on the HTML document!"

In our case the value is a variable, therefore no ( ' ' ) quotes are used to enclose it. If you want to print some text instead, the command must be: **document.write('some text.');**. It's all very similar to the alert() command you've been using so far.

Now **experiment with the code** sample above by trying out all the other arithmetic operators and printing the result on the page.

## Concatenation operator

If you want to add pieces of text together to form one long line of text, use the + sign. In Geeky talk a piece of text is called **string**, and it appears enclosed either in (' ') quotes or (" ") double-quotes (remember the 'Hello World' text you used in the alert() command? That is an instance of string).

### Try out: concatenate strings and print a message on the page

<!DOCTYPE html> <html> <head> <title>Lesson 5: Operators and Comparisons</title> </head> <body> <h1>Lesson 5: Operators and Comparisons</h1> <script type="text/javascript"> //Create and initialize your variables var firstText = "Hello"; var secondText = "World!"; //Resulting value of assignment is Hello World! var message = firstText + ' ' + secondText; //write result on the page document.write(message); </script> </body> </html>

If you typed your code correctly, you should see the famous *Hello World!* text smack on the web page. **Notice: you separate Hello and World! by concatenating quotes (' ') in-between each piece of text or variable.**

Now get some **practice concatenating strings** before moving on.

## Comparison operators

Often you need to compare different values and make your JavaScript program take different directions accordingly.

For example, you're coding a JavaScript script for a shopping cart application. At one point, your script will have a statement saying something along these lines: if the total amount to be paid is **greater than or equal to** $50 apply a 5% discount, if it's **less than or equal to** $50 do not apply 5% discount. Don't be impatient, **you will learn how to code this kind of conditions in the next lesson**.

It's here that **comparison operators**, such as **equal to, less than**, etc. enter the scene. Here below are listed all comparison operators for your reference.

If x = 10 we have:

Operator | What is it? | Example |
---|---|---|

== | equal to | x == 5 is false |

=== | exactly equal to value and type | x === 10 is true x === "10" is false |

!= | not equal | x != 2 is true |

> | greater than | x > 20 is false |

< | less than | x < 20 is true |

>= | greater than or equal to | x >= 20 is false |

<= | less than or equal to | x <= 20 is true |

## Logical operators

You use **logical operators** when you need to determine the logic between certain values.

Going back to the shopping cart script example, you might want your script to apply a 5% discount **if the following 2 conditions are both true**: a given product costs **more than** $20 **and** is purchased before the 31st of December.

Here come **logical operators** to the rescue. Given that x = 10 and y = 5:

Operator | What is it? | Example |
---|---|---|

&& | and | (x < 20 && y > 1) is true both conditions must be satisfied |

|| | or | (x == 5 || y == 5) is true at least 1 condition must be satisfied |

! | not | !(x == y) is true |

## Questions, questions, questions

The tables above are self-explanatory, except for the following 2 questions:

- When you talk about === , what do you mean by equality of
**value**and**type**? - What's the difference between
**( = )**,**( == )**, and**( === )**?

### Answer to question 1.

**Values** are the specific data, either directly in your JavaScript statements or contained in JavaScript variables. For example:

```
var price = 5;
```

In the code snippet above, the variable *price* has value *5*.

What's the **type**?

The type, or more precisely the **data type**, is the way JavaScript classifies data. You've come across 2 data types, that is, **number and string (text)**. A third data type is **Boolean**, that is, **true and false statements**.

Therefore, when you compare 2 values using ( === ), the 2 values are compared on the basis of **both their value and their data type**:

var firstNum = 4; var secondNum = 4; //this is true: both values are 4 //and both values are of type number firstNum === secondNum; //let's use a string data type. A string uses ' '. var stringNum = '4'; //Now === is false: 4 and '4' are different types firstNum === stringNum;

### Answer to question 2.

The ( = ) operator is used to **assign or give** a value to a variable. It is **not a sign for equality**.

The ( == ) and ( === ) operators instead, **do stand for equality**. They **do not assign values to variables**. **( == ) compares only values, ( === ) compares both values and data type**.

## Summary

You've made it all the way through this lesson, congratulations! Now your scripts are not limited to just popping up messages. They start to **be smart**: they can **make calculations, comparisons, and set truth conditions to evaluate their data**.

In the next lesson you keep adding intelligence to your JavaScript with *if ... else* and *switch* statements.

Take a break and get ready for it!

Related topics in the | Replies | Views |
---|---|---|

No related topics yet |