Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Working with operators

From: JavaScript Essential Training

Video: Working with operators

Just about every statement we will write is going to involve an operation, moving data from one place to another, adding, subtracting. Now to perform a lot of these operations we need operators, and that just means the symbols that we are using to manipulate our values. The most obvious are probably the arithmetic operators. We have addition, we have subtraction, an asterisk for multiplication, forward slash for division. Now you typically see these used along with the equal sign, and the equal sign is formally called the assignment operator.

Working with operators

Just about every statement we will write is going to involve an operation, moving data from one place to another, adding, subtracting. Now to perform a lot of these operations we need operators, and that just means the symbols that we are using to manipulate our values. The most obvious are probably the arithmetic operators. We have addition, we have subtraction, an asterisk for multiplication, forward slash for division. Now you typically see these used along with the equal sign, and the equal sign is formally called the assignment operator.

When we hit the statement we are going to execute whatever's on the right of the equal sign and use it to assign of the value to whatever is on the left of the equal sign. So for those of you who are new to programming, remember that when you see a single equal sign that's not a polite description; that's a command. We are setting a value. We are assigning. Now you will often see the same variable being used on both sides of the equal sign. In this case, we are just adding 10 to the variable called score and storing the result back in score. Now adding to a variable or subtracting to a variable happens so often that there is actually a shorthand for this.

I could write the statement this way. I could also write it this when using the plus equals operator, meaning add this number to this variable. Note that this is a single operator, so there is no spaces between the plus and the equals. And if we have a shorthand for adding to a variable, we also have a shorthand for subtracting a number for a variable and for multiplying or dividing a variable by a particular number. Now as with most languages, there is operator precedence in JavaScript, simply meaning some operator symbols are treated as more important than others.

Particularly multiplication and division are regarded as more important than addition or subtraction. So, if I read the expression on the right-hand side of the equal sign and just read it in order, left to right, I would think 5+5 is 10 times 10 is 100, but no, the multiplication is regarded as more important, so that's done first. 5 multiplied by 10 is 50, then we add 5, and the result is 55. If I want to impose an order on this, I simply take the important pieces that I want to be executed together and surround them with parentheses.

In this case, I would take the 5+5 and that would make sure that that was executed independently. Then we multiply it by 10, and the result is 100. And moving on, we have the comparison operators, back to this idea of equality. Again, if you're checking that variables are equal to each other or equal to other values, you can use the double equals operator. Now a classic mistake of programmers in any C-based language, including JavaScript, is to accidentally use a single equal sign where you meant to use a double equal sign. So here is an example.

I create two variables, variable a=5, variable b=10. If later on in my code I ask if a=b? Well, I am using the wrong operator. What's going to happen here is that the single equal sign is a command. We will hit this, and then we will set a=b. This then returns true, and the code in the if statement will always be executed, even when you think it shouldn't be. This is perfectly legal syntax in JavaScript and in a lot of other languages too, but it can lead to code that just doesn't work the way you expect, and it's difficult to debug because it's easy to miss.

So remember one equal sign is assignment. You are telling. Two equal signs is the equality operator. You're asking. And in JavaScript, there is another equality operator, the three equal signs. Three equal signs is the strict equality operator. Now what on earth does that mean? Let me show you an example. I am going to open up Firefox. I just have my preferences set to open on a blank page, and I'll open up the Firebug panel.

Make sure I am in the Console and that I have the whole right-hand pane activated, so I can type some JavaScript in here. You can also do this in an HTML page or a JavaScript file. So I write some very simple code here. In this code, I have two variables. Variable a starts off with the number 5 and variable b starts off with the value 5 but as a string, using double quotes. Now I am going to go ahead and run this.

So I'm checking if a is equal to b. And if you notice I must be popping up the alert that says, Yes, they're equal. And here's what's happening. If I use the two equal signs as the equality check here, they are regarded as equal. The JavaScript engine is checking them and saying okay, these two variables may not be identical, one is a number and one is actually a string value, but they have the same value, so I am going to say this is true. But if I use the three equal signs here, this is strict equality check.

Run that again and the output here is that they are not equal. The comparison is false. Three equal signs, strict equality, is going to check that they're the same value and that the same type under the hood, that they're not just equal, but identical. Now most of the time the double equal sign and the triple equal sign will behave the same. As an example, if I had created the second variable just to have the number 5, then if we use the three equal signs, we would say, yes, they're equal and if we use two equal signs, yes, they're equaled.

They are both equal and they are identical. Now most of the time you will find that the double equals and triple equals could be used interchangeably, though some JavaScript experts recommend using the triple equal sign all the time and just never using double equals. I wouldn't go that far, so when I see a double equal sign in someone else's JavaScript I don't consider it wrong. But if you were to get into the habit of using triple equals all the time, that's certainly not a bad habit to get into. So when we are writing, say, an if statement and we're checking if we have equality, double equals. If we want to check that something is not equal to, it's the exclamation mark equals, or we have the triple equals and its counterpart exclamation mark equals equals, not strictly equal to.

We then have the classic greater than operator, less than operator, greater than or equal to, less than or equal to. And again, all of these must respond with either true or false. Something is equal or it is not; something is greater than or it is not; something is strictly equal to or it is not. Now what happens if you have a few questions to ask? If in a situation that we are comparing several things, I want to know if a is strictly equal to b and c is strictly equal to d, how do I write that? Well, what we will use here is the double ampersand.

This means "and," a logical "and." And I say logical "and" there because some people take "and" as meaning addition. The flip side of this is what if we are interested in one or the other situation? If the variable a is strictly equal to the variable b or the variable c is strictly equal to the variable d, we use the double vertical bar, or pipe symbol. This is the logical or. Now you will often see these kind of split up with multiple sets of parentheses to make it a bit more explicit about what you're looking at, in this case, if a is greater than b and c is less than d. But as ever, the entire condition, the wider set of parentheses must evaluate as either true or false.

If you have several things to check, you may even split it across multiple lines if you want to make it more readable. It's one of the benefits of white space being insignificant. Now, a couple of roundabout operators here. We have the modulus, or remainder operator in JavaScript. This one's a little different. Probably the classic example here is using it to do something like calculating a leap year. So in this case I create a variable called year, and it's equal to 2003, and then I create a variable called remainder.

I set that equal to year % 4. The % here is the modulus, or remainder operator. What it means is divide the variable year, 2003, by 4, but don't give me the result, give me the remainder, which in this case 4 would go into year 500 times and the remainder would be 3, and you will run into this one now and then. Next, we have shorthand for adding to a variable. Now we have already seen this a little bit. If we have a variable called a and we want to add 1 to it, I could do it the long way, which would be this.

I could do it the shorter way, a+=1. But if I am just interested in adding 1 to a variable, I can also use another operator, which is ++. If you want to get geeky about this, this is what's called a unary operator, meaning it only needs one thing to act on. Now the plus plus operator, which increments by 1, can be used either after the variable name or before the variable name, so a++ or ++a. And the flip side is true.

We have a=a-1, or a-=1, or a--, or --a, they all do the same thing. Now by themselves on lines like this, great. But there is actually a tricky difference. So the plus plus and the minus minus can be used either before the variable name or after. Technically, if you want to get geeky about it, it's what's called the prefix and postfix versions of those operators. And while they end up doing the same thing, they do it in a different way, and there is an impact to which one you choose.

Let me show you what I mean. Let's say we start off with creating a variable a and setting it equal to 5. What I am then going to do is write a statement that says alert(++a). So I want to pop up a message box with the contents of the variable a, and I'm going to add 1 to it. What happens is using the prefix version where the plus plus is before the variable we will actually execute that, and we will increment a before we run this line.

So the value of a will be changed to 6 and then the alert message will pop up saying 6. However, if I go back and do this a slightly different way, doing an alert with a++, what happens is we will first do the alert and only then, at the end of the line, will we cause 1 to be added to a. The end result is the same, that the variable a=6, but the message that we popped up was different, and this is one of those little things that can cause bugs.

So I tend to only use the plus plus and minus minus on their own statements by themselves. Then it doesn't matter. I know that when I have executed that line of code it's been incremented or decremented. And finally, the last one that I am going to talk about is a great little useful one called the ternary operator. That's not a great name, but there is no better name for it. See, most of our operators are what are called binary operators. Now it doesn't mean they work on binary code. It just means they work on two elements; there is something on the left and something on the right, a+b, amount divided by year.

They work on two pieces. The unary operator, plus plus, minus minus, works on one, and ternary works on three. So it actually has two symbols to it, the question mark and the colon. Now the general format of using this is that you have a condition. You're asking something. Then you say what happens if this is true and what happens if this is false. You can actually think of it as a mini if/else statement. So let me show you an example here. So let's say I define two variables: var playerOne=500, var playerTwo =600.

Now some time later in my code I want to create a high-score variable and I want to set this equal to whatever the larger of the first two are. Well, I could write this using an if statement. If playerOne>playerTwo, we will set highScore=playerOne; otherwise, we will set highScore=playerTwo. So I have got about six lines here just to set the value of highScore. With the ternary operator, it would let me take it from six or seven lines to one.

What we do is we specify three things: the condition, question mark, what if it's true, colon, what if it's false. So my condition is playerOne>playerTwo. Like all conditions, this has to be either true or false. I put the question mark. Then I say if it's true, I want to return the value of playerOne colon, if it's false, I am returning the value of playerTwo, semicolon to end the statement. This would allow me to get rid of that if statement and have the whole thing just on one line.

Now we probably won't use this much in this course, but you will see it from time to time, so I want to be able to recognize it when you do see it. And this has given us plenty of operators and definitely will be enough to get us moving and building some useful logic in our code.

Show transcript

This video is part of

Image for JavaScript Essential Training
JavaScript Essential Training

56 video lessons · 101780 viewers

Simon Allardice
Author

 
Expand all | Collapse all
  1. 3m 28s
    1. Welcome
      1m 1s
    2. What you should know
      1m 44s
    3. Using the exercise files
      43s
  2. 15m 41s
    1. Introduction to JavaScript
      8m 6s
    2. Creating your first JavaScript
      2m 13s
    3. Getting to know the tools and applications
      5m 22s
  3. 56m 8s
    1. Understanding the structure of JavaScript code
      7m 9s
    2. Where to write your JavaScript
      3m 56s
    3. Creating variables
      6m 21s
    4. Working with conditional code
      5m 44s
    5. Working with operators
      13m 28s
    6. Sending messages to the console
      2m 59s
    7. Working with loops
      8m 1s
    8. Creating functions
      8m 30s
  4. 36m 13s
    1. Working with arrays
      7m 57s
    2. Working with numbers
      6m 13s
    3. Working with strings
      8m 27s
    4. Working with dates
      5m 38s
    5. Working with objects
      7m 58s
  5. 9m 6s
    1. What is the DOM?
      5m 49s
    2. Working with nodes and elements
      3m 17s
  6. 25m 17s
    1. Accessing DOM elements
      11m 3s
    2. Changing DOM elements
      5m 42s
    3. Creating DOM elements
      8m 32s
  7. 24m 45s
    1. Introduction to JavaScript event handling
      8m 16s
    2. Working with onClick and onLoad events
      7m 36s
    3. Working with onBlur and onFocus events
      2m 36s
    4. Working with timers
      6m 17s
  8. 21m 41s
    1. Common JavaScript errors
      7m 14s
    2. Using Firebug
      4m 7s
    3. Going through a debugging session
      10m 20s
  9. 10m 13s
    1. Accessing form elements
      4m 20s
    2. Preventing a form from being submitted
      2m 36s
    3. Hiding and showing form sections
      3m 17s
  10. 9m 49s
    1. CSS and JavaScript
      3m 46s
    2. Removing and applying CSS classes
      2m 16s
    3. Changing inline styles
      3m 47s
  11. 19m 44s
    1. Understanding JavaScript style
      7m 39s
    2. Minifying your code
      4m 28s
    3. Using JavaScript code checkers
      7m 37s
  12. 22m 24s
    1. Introduction to JavaScript libraries
      3m 17s
    2. Linking to multiple JavaScript files
      2m 11s
    3. Introduction to jQuery
      12m 7s
    4. Using a content distribution network to deliver JavaScript files
      4m 49s
  13. 17m 35s
    1. JavaScript in HTML5
      9m 37s
    2. Using Modernizr
      3m 2s
    3. Using Strict Mode
      4m 56s
  14. 33m 3s
    1. Knowing the JavaScript to avoid
      6m 35s
    2. Introduction to regular expressions
      6m 56s
    3. Working with AJAX
      10m 44s
    4. Working with objects and prototypes
      8m 48s
  15. 21m 10s
    1. Example: Countdown
      8m 3s
    2. Example: Resize
      5m 47s
    3. Example: Accordion
      7m 20s
  16. 4m 58s
    1. Where to go from here
      4m 0s
    2. Goodbye
      58s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed JavaScript Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.