Tip:
Highlight text to annotate it
X
hello everyone
and in this episode we are going to be talking about javascript operators
now previously we've discussed that
any line of code we write in javascript
can be considered either a statement or an expression
some examples of each
some statements we have could be something like declaring a variable
called first name using the bar keyword
and doing a document dot write line for the string literal hello
both of those statements are statements because they do not
produce a value, they simply do whatever action it is that they're
asked to do
some expressions on the other hand things like
x equals 9 or tax rate times price are both considered expressions because
both of them would be
representative of some particular value.
for example x equals 9 the entire expression would have the value of nine
the value it's been assigned and the tax rate times price
expression would have whatever value was produced by multiplying the value of the
tax rate variable times the value of the price variable.
Now, something we haven't discussed before is why is it that some statements are
statements and others are expressions
there's actually a few different rules that can kind of determine
what becomes an expression or not but certainly one thing that you can
always look for is the use of things called operators. Whenever we use an
operator in an expression like the equals sign or the multiply sign
that pretty much guarantees that the line of code in which that
operator is used will be an expression, will produce a value.
So let's talk a little bit more about these magic little symbols called operators.
Operators are something that we've seen throughout javascript. probably I
would say a good majority of the different lines of code that will write javascript
will involve operators in one way or another
this is a collection of a handful of different statements I threw together or
expressions I guess I should say that I threw together that all involve different
operators
and
probably at this point in learning javascript a lot of the statements look
a little bit complicated to you
but a big part of the key of understanding these
expressions is understanding the operators, recognizing them, and knowing
what exactly it is that they do so that you can figure out what each one of
these expressions is going to
do for us, be able to take a good guess at what the result
of that particular expression will be.
To simplify this a little bit let's cut down
all those different expressions and just look at these three
and let's take two of those
different expressions and simplify them a little bit so that we can see a little bit
more clearly exactly what's going on
the first one negative twelve second one x equals nine and the third one which
is a bit longer are of course all javascript expressions involving
operators.
I've highlighted the operators here in red
but something I want to point out before we talk about the operators themselves
is that each one of these expressions involves something more than just the operator
itself
the negative twelve statement for example has a negative sign which is an
operator but it also has the number twelve in there
these things that are around involved with the operators are called operands
every operator has a certain number of operands that it works with basically
the operands provide sort of the material that the operators are going to
actually operate on.
Now every operator based on the number of operands that it needs has what's
called an arity.
The negative sign for example would be called a unary operator it's unary because
it only takes one operand
The equal sign which we called the assignment operator is called a binary
operator because it takes two operands
and here in the last line I have an example of the one and only
ternary operator, the comparison operator that we have available in java
script.
So with those out of our way,
moving forward to talking about the operators themselves
javascript has a lot of different operators involved, a lot of different
operators available so I'd like to take these different operators and break them
up into some different groups
logical, arithmetic, comparison, and assignment. I think it makes them a little bit
easier to tackle that way
looking first of all then at the arithmetic operators: arithmetic operators basic
purpose is simply to do math.
A lot of these you're probably familiar with. The first four on the list here: plus,
minus, multiply, and divide are things that I'm sure that you've seen before.
the only difference maybe
that in javascript we use the asterisk sometimes called the splat to
do multiplication and use the slash to do division
all four of those are binary operators and they basically work just the way you'd
probably imagine that they would work but we'll take a look at some
examples of them here in a minute.
The next one the percent sign is called the modulus operator. It's a little
bit different probably the most of you 've seen before. It does sort of third-grade
division more or less for it does the division but instead of giving back the
quotient it actually returns to the remainder from the division
so it can be handy in a number of different aspects and we will look at it here in a little
bit.
It also by the way if I forgot to mention is a binary operator.
The last three: plus plus, the minus minus, and a single minus sign are unary
operators, they only take one operand.
the plus plus is the increment operator, it basically adds one to whatever
its operand is
the minus minus is the decrement operators it subtracts one from whatever
its operand is and of course the very last one single minus sign is the
negative operator, it simply changes the sign of whatever its operand is.
so let's go on to look at some different examples of some of the arithmetic
operators now
okay let's go ahead and start off here looking at some of the basics of using
are arithmetic operators as you can see I've started a default
xhtml page just as I have done previously
and I have the content of that page currently up my browser so that I can just quickly
shift or command tab between them
so just to give us a place to play what I am going to do is put some
script tags here in the body of my web page.
and let's start off here taking a look quckly, using a
document write line no quote in there needed.
at uh....
at uh... some arithmetic operators we could do something very simply for example
like say thirty-four plus eighty- nine
save those changes, jump over to my browser and it quickly and easily gives me
the answer one-hundred twenty-three
uh... we could certainly also do quite a number of other things uh... doing
a document dot write line with two numeric literals is not very realistic.
If there were always the two literals being added together than why
why not just add them together and display that out put all the time.
what put javascript through the work?
so something that would be much more likely
would be that I'd have a couple of variables uh... maybe variables whose
values i know or don't know
so just to kind of show you I mean I might have a couple variables num-one
and num-two... each of them with a different value in it
and what would be much more common then would be for me to actually take the
values of thsoe two variables and perform some type of mathematical operation
like add the two of them together
seventy-seven you can see is the
sum of fifty four and twenty three
it of course doesn't have to be plus that we work with we can subtract them or
multiply them just as easily multiply the two together and we get one thousand
two hundred and forty-two
divide the two of them
two point three four seven eight so on and so forth
so anyway out that's a very simple basic way that we often use our
arithmetic operators you can see that they are all binary about operand one,
the operator, and operant two, that i've been using pretty much all of these that we
have been looking at.
okay so keeping some of those basics in mind, what kind of things could we
actually do here
with our arithmetic operators. let's say for example that we
wanted to write a program that would allow the user to specify a number of
days
and then what we want the javascript to do is to calculate how far light will travel
in that number of days.
Let me go ahead and start
a new page here
looking for a template, html transitional
there we go.
I am going to call this one
speed of light
and I am going to save it as "speed" on my desktop
I could go ahead and open it here in my web browser
double clicking on it, there is my speed page in my web browser
and uh...
maybe what I will do down here in the body for starters is to put in a set of script tags.
now there's a number of different things that this script will need to do
first of all it is gpoing to need to work with the speed of light so maybe i'm gonna make
myself a variable called speed of light with underscores between words
and set it to the speed of light one hundred
and an eighty six thousand
and that is in miles per second. I put that in as a comment to help myself remember
the units that i'm actually dealing with here.
now with that little bit of sort of housekeeping out of the way the fact that
I am going to need that value I am going ahead and get it and put it in the variable
I suppose the first thing the script really needs to do is
is to ask the user about the number of days they are interested in.
so let me go ahead and use a prompt statement and the prompt statement of course
is going to return the number of days the user enters so I am going to say
var days equals prompt
enter a number
oops
a number of days, see my typing hasn't improved any
All right at that point the user will enter a number of days hopefully
and whatever they enter will be returned and stored in var days variable.
What I need to do then since my speed of light is in miles per second is I'll
need to change that number of days into some number of seconds.
so let me make another variable I will call it seconds
And what I am going to do to get the number of seconds is I am going to take the value of the days
variable, the value that the user entered I am going to multiply it by twenty-four
then I will multiply that value by sixty and then multiply that value by sixty.
so taking the number of days multiplying by twenty four will give me the number of hours
multiplying the hours by sixty will give me the number of minutes, multiplying the minutes by sixty
should give me the number of seconds in that number of days
once I have that value calculated the next calculation I can perform
would be to figure out how many
miles that people actually travel in that number of seconds. So I'm going to
make another variable, this one I am going to call "distance" and to get this one I
am going to multiply the seconds times the speed of light
There we go.
so whatever distance I'm left with there should be how far light travels
how many miles light travels in that number
of seconds.
so let me just go ahead and display that to the user, maybe I will put it in an alert.
I'll say flight will travel
uh... then i'm going to put in
the value of my "distance" variable
uh... miles in
then I will display the value of the "days" variable
and then the word "days."
so my output should come out light will travel
a hundred billion miles
in four days, something along those lines.
so let me jump back over to my browser and let's see how it works.
enter number of days, let's say four days.
light will travel wow that's a big number
miles in four days. let's travel one more time
let's say one day
Light will travel that many miles in one day.
so it looks like that works just fine
all right for our next little example, let's take a look at an operator that
a lot of you may not be familiar with the modulus operator.
I mentioned before that the modulus operator is sort of like doing division
except it's like third grade division in that it doesn't give you back any
decimal point, any fractional part of the quotient. Instead what it always does is it
simply returns just the remainder of doing division.
so for example if we were to do a document oops some script tags would help.
let's put in some script tags and inside those that put a document dot write line
let's put in here something like nine modulus two.
now from what we know about basic arithmetic we know that if we divide
nine by two the answer's not going to come out even.
since we're using the modulus operator basically what we're saying is if we try
to put two into nine
how many will be left over after division is done.
so two will go into nine four times for a total of eight which means one will be
leftover.
so the value of nine modulus two we will see comes up as one
one simply being the remainder.
if we were to do the remainder of three and two again the answer would be
one. That was not a very interesting example.
how about if we do something like eight and three
how many time will three go into eight? Well, it will go into it two times and there will be 2 left over.
so if we take a look at the ouput, the ouput is two. It always gives us the remainder.
Now you might be wondering, what in the world is something like that good for?
well in my experience the thing that I tend to use modulus for the most is for limiting
the range of numbers. Let me show you what I mean here.
there is a function available to us in javascript and we will discuss
functions more later but really no harm in going ahead and talking about this one now I guess
uh... called the random function you get it by doing math dot random
along with about a thousand typos in here. Anytime we do math dot random, call that particular function
what it gives us back is a random number every time I hit the refresh my
browser re-executes and you can see that math dot random comes back and gives
me a different number.
the numbers that it returns,
the random numbers that it returns is always a value between zero and one
so if i wanted to do something like say simulate the rolling of a regular old
six-sided die
i could do that using this random number but i would need to do a little bit of arithmetic on
it first to get it to come out the way that I want it.
the very first thing I might do is I might take the value of math dot random
and mulitply it by 100.
just for example
but that of course is going to do is basically have the effect of moving the
decimal point two places so every time I
refresh my browser now you can see them coming up with a number of
somewhere between zero and one hundred
instead of between zero and one
so that sort of pulls the numbers up into a slightly more manageable range
now I don't really need any of the fractional parts of those numbers so maybe
the next thing I'll do is I am going to take everything that I already have there
put it into a parse int statement.
which I believe we've talked about before
that will take that floating point number of that number with the decimal
point in it and turn it into an integer for us.
so now we're getting just plain old
integer numbers between zero and one hundred.
random number, new one coming up every time I hit refresh on the browser.
and now that's still not exactly what I want if I am going to simulate
the rolling of the dice.
what I would really need to do next is I would need to limit that number
so that it's always between
one and six
now I can't exactly get one in six with modulus but what I can do as I can take
that number
and I can do modulus six.
the way that modulus is always going to work is if we do something like
modulus six it's going to mean that we can never get back a value
greater than or equal to
the second member of the modulus expression
so if I do modulus six it means the biggest number I will ever be able to
get back out of that statement is going to be five which is of course
less than six. I probably did not mean to mention that, did I?
uh... if you think about it the way that that works kinda makes sense uh...
if there
was a remainder of six
then that would be another full division so the remainder
would actually go back to zero we can't get six or greater, only less than six
the value that actually comes back.
so if i go take a look at it now you can see every time i refresh the numbers are
all being confined and constrained to that particular range. Everything is coming up
between zero and five
now zero and five of course isn't the way that dice usually work but what I
can do to get it just exactly the right range is to simply take that number and
add one to and that's it
now I will always get back numbers between one and six by using the modulus operator
and I have a little of expression there
that in essence sort of simulates the rolling of the die. So I can write a game
with it or do all kinds of other things. I am sure it will be lots and lots of fun.
alright that's next go on to take a look at our increment and decrement operators
Like I have done before I am going to go ahead and put a set of script tags
inside the body where we can play
now the increment and decrement operators are both unary operators as I mentioned
previously; they are the plus plus and minus minus operators and on the surface they're
both fairly simple. If I were to make for example a variable called
num which I'll assign the value of nine to
if I then came down and did a document dot write line and printed out the value of num
we would of course see 9 come up
and uh... let me go ahead and add a break on here.
if we were to then come down and do something like
num plus plus
and then print out the value of that variable again we would see that the
value of that variable has now become
ten.
so by using the plus plus operator on my num variable there
I have incriminated the value of that variable by one
if I had decremented instead minus minus instead of plus plus then of course
the value comes out as eight. The decrement operator simply subtracts one
instead of adds one
so really on the surface that's about all there is
to the increment and decrement operators but they do get a little bit more
confusing than that.
sorry if I were to put in another document dot write line and I were to say
num plus plus right there inside the document dot write line statement you
might think okay it's being incremented so it will surely come out as eleven
but if we take a look we see that it actually comes out as ten again
and it almost appears as if the increment operator didn't work at all. if we do
one more document dot write line with the num variable after the one where we did
the increment, we see that at that point it actually is eleven.
what actually happens here is that when we use the increment operator after
it's operand
basically the operand followed by plus plus like we did in that statement and this statement,
javascript actually waits to do the increment until everything else in the
expression is done. so up here on this line
it was the only thing that happened in the expression so it didn't make any
difference, the javascript was trying to wait till the end before it incremented that value.
but down here in the the document dot write line when we did num plus plus what
javascript actually did in that situation
was it first did the document dot write line and only after the document dot write
line was complete did it then come back and actually increment the variable
and so we ended up with
num being nine here,
this changed num to ten
so here, num printed out its ten;
this changed num to eleven but only after it printed out ten,
so when we printed it out here that's when we actually got eleven.
uh... nine ten ten
and eleven is what we end up with in our output browser.
now the plus plus and the minus minus operators can actually be used in a
slightly different way if we want to.
instead of doing num plus plus we could actually do plus plus num
which as you can imagine is sort of the opposite order from num plus plus
when we do num plus plus we call that a post increment
when we do plus plus num we call that a pre- increment
so
in situations where we want to incriminate a variable as part of a larger
expression or statement
and we want the incrementing to happen first,
then we make sure that we put the plus plus before the variable that we are incrementing.
we do a pre increment
in situations where we want the increment
to happen last in the expression
we always do a post increment, making sure the plus plus comes after the variable. So it can be a
little bit confusing what I always tell people when you're first getting started
with it is that if you're in doubt
just don't include the increment or decrement operators in larger
expressions.
if I was concerned about what would happen if I did this right here
then don't do that basically just keep num out here by itself
it makes the code a little bit longer, a little bit sloppier and there're certainly sometimes
that it might cost you a little bit but
you certainly don't want to be messing with something you don't completely
understand so experiment with it
and when you feel comfortable with it, use it anyway that you would like,
but as long as you're not comfortable with it or that you suspect
that it's causing problems then simplify your expressions
keep your increments and decrements out of the overall expression and make life a little
bit easier.
now all of this time in here I have been talking about incrementing. All of these exact
same rules apply for decrementing. the same way. You can pre-decrement and post-decrement. Other than the
fact that it's subtracting one instead of adding one
everything works the same way.
The next group of operators we want to take a look at then
are the assignment operators they're fairly simple they all basically have to
do with assigning the value
uh... generally to a variable uh...
which is which will be placed on the operators left
all of these are binary they're all going to have something on their left
something on their right
the very first one is the one will probably see most often the single
equals sign
we actually used it a number of times in this class already it simply takes
whatever values to the right of the equals sign and assigns it to whatever's on the left
which is why we call it the assignment operator not generally the equal sign. It
doesn't really have anything at this point to do with things being equal to one
another
the next five are all sometimes referred to as being short cut operators because
they simply give us some shorter more concise way of writing
longer statements we've got the plus equals, minus equals, multiply equals,
slash equals or divide equals and modulus equals or percent equals. All of those
will let us do that particular arithmetic operation combined with
an assignment
that's probably easiest at this point to go and just do some examples of those
so you can kind of see how they are used.
working with the assignment operators in javascript is fairly simple so simple
in fact that we've actually ...ooops...
we've actually already done quite a bit of it
oops
like before I am going to put some script tags in the body here so we can look a little bit
the place that we've mostly seen the regular old assignment operators the single equals sign
used is when we're creating initializing variables if I for example create a
variable called x and I assign it the value of hello then of course what I'm doing
is using the equals sign, the assignment operator right here to take the value on
its right that string literal "hello" and assigned to the variable on the left
variable x. I can of course do that multiple times as we've discussed previously
I could uh... assign after variable x has been created and initialized a
different value to it
goodbye
for example which then replaced the string literal hello
really not much to it
the variation of course on the single assignments operator, the assignment
operator is to uh... used to short cut operators
there are times in java script will do things like create a variable called
answer. the variable "answer" is going to be the
result of adding actually that is not a very good example.
let's uh...
Let's just assign a value to answer let's give it nine ok? and then let's say that I
wanted to uh...
add two to the current value of answer. I could do something like say answer
equals the current value of answer plus two that's easy enough
but that's a little bit longer than really needs to be and that's where the
shortcut operators come in. I could just as easily do that
in the first expression
near the one that's highlighted
what i'm doing it and taking the current value of "answer" i'm adding two to that
value and whatever the sum of that is would be assigned to "answer"
replacing its old value.
here in the second statement, the one that is now highlighted
i'm actually doing the exact same thing but you can see that it doesn't require
that i repeat the name of variable that is to the left of the assignment operator
so it can save me a little bit of typing which means probably save me a few typos
that's basically how the short cut operators work uh... besides the plus-equals you might
remember there was also the minus- equal, there's the multiply-equals, there's the
divide-equals and there is the
modulus equals. any of those can be used in those kinds of situations. they're not any
situations in javascript that ever require any of these operators the shortcut
operators be used.
but they do occasionally come in handy. less typing usually means less mistakes.
our next group operators are called comparison operators
all of the operators here in this group are interesting because all of these
produce boolean values true or false basically anytime any of these
operators are used the results of the uh... expression that thye're used in
is always going to end up being true or false
the very first of the comparison operators here the double equal sign is called the equality
operator
uh... what it does is it looks at what's on the left what's on the right
and determines whether they are equal to one another
when javascript checks for equality this way, using the double equal sign
using equality operator
it ignores data types for the most part
so if we were to check if
the
uh... numeric literal nine was equal to the string literal nine basically
a nine without quotes checking to see if it's equal to a nine with quotes the
answer with the regular equal sign would be true the double equal sign would
result in true.
it does that because javascript will coerce, basically sort of massage the
datatype to see if it could make the two operands that that operator equal
the next operator the triple equal sign is called a strict equality operator what it
will do
is it will again check to see if what's on the left is equal to what's on the
right but it will not try to coerce datatypes
so if the data types are not the same it will return false it will say these two things
are not equal to one another.
the next two operators after that are the not equal to and the strict not equal to,
they're basically the exact opposite of the first two equality and strict
equality operators
they simply return
false where the other would return true uh... just the opposite.
after that we have a greater than in less than signs, greater than or equal
to, less than or equal to all of which are probably familiar with. again
all these uh... all of these except the very last one in this list are binary
and most of them you're probably pretty familiar with the greater than and less than
combinations especially.
the very last one, though,
that question mark colon is the conditional operator. it's the only ternery
operator in javascript, the only operator that takes three operands.
it's a very special one we'll take a look at it here in some examples
alright next let's take a look at our comparison operators. when I described
these to you before i wouldn't all be surprised if you weren't left wondering
what the purpose of these things is
what we're gonna find thought is that at the moment they aren't going to do a whole lot
for us. but here very shortly we're gonna talk about another operator , the ternery
operator called the comparison operator
and uh... in later
episode we will talk about control structures
with both the uh... conditional operator and the control structures that will
talk about later
excuse me.
these comparison operators will become invaluable to us but for now let's just
take a look at the basics of how they worked so again a set of script tags
inside the body section of what i'm going todo here is start by
creating a variable i'm going to call it num
like I've done previously it's just one of my favorite variable names i guess
and I'm going to assign it the value of
lucky number nine.
now if i'm going to uh...
uh... let's say i'm going to put in a document dot write line so we can actually
see the output.
and what i'm going to do is maybe just do
the display the output of saying is num
equal to nine.
something simple like that. i'll take a look at my browser
and it comes back true so what's happened here is that I used the equality operative
the double equal sign and i've asked javascript is the value of the num variable
equal to
the value of nine
and it of course has come back and told me true it certainly is
let me add a break in here
and oops, that messed everything up.
interesting
what's actually happening now
is that
javascript is actually adding the value of nine and the break together
and saying is that equal to nine. and of course the answer at that point is false.
let me put some parentheses around num equals nine, at that point
the value goes back to being true. the answer, the
output from the equality operator goes back to being true. Let me
copy that statement I'm going to do something like that a number of other
times. so anyway that's the basic quality operator.
let me make another variable here i'm gonna call this one s uh... s for string.
what I'm going to do is i'm going to put the uh... string value of nine here
inside the variable s, basically nine with quotes around it.
now if i were to come back and i would say is
num equal to s and javascript in that case it actually come back and tell
true . the reason it is true, like i mentioned before
is that javascript will happily
coerce datatypes
here in this particular expression num equal to
s
what javascript does is it says oh look this
is a number and this is a string. unless I do something there's no way those two
will be equal
so what it
does is it takes the number and turns it into a string because it's a very easy
kind of full proof conversion
so then at that point there are two strings, both of them with the number nine in it, it kind
of checks to see if they're equal to one another. and the naser comes back yes. they certainly are.
if i were to try basically that same thing again but instead of using the
double equal sign i used the triple which is the strict equality operator at that
point javascript tells me
yeah true. boy I am having a rough day today. because i have the actual number nine in there.
if instead of nine i compared it to s in that case the answer is false just as it
should be.
when we use the strict equality operator of the three equal signs that tells javascript
not to perform any datatype coercion
so in this case it's looking at the numeric literal or the numeric variable
nine versus the string variable that has nine since it's not allow with the strict
equality operator to change the data types around it knows immediately there's no
way in the world that these two things will be equal but like you saw a moment ago sort of on
accident if i compare
the numeric variable nine versus the actual numeric literal nine in that case
javascript comes back and says true. those two are equal to one another.
most all of our different
comparison operators work basically the same sort of way uh... i have to say for
example is the value of num variable greater than ten , the answer of course will
be false because nine is not greater than ten.
i could say is the value of the num variable
uh... less than or equal to nine
the answer in that case of course would be true
it is less than or equal to nine stress on the equal to part. so most all of
our comparison operators work that same sort of way they're always going to return a
boolean value true or false
and uh... that true or false value is something that's going to become very
very important to us later when we talk about the conditional operator and control
structures. next let's take a look at our conditional operator
it is uh... kind of a strange one in javascript because it's the only
operator we have that is ternery, it actually takes three operands
let me throw some script tags here in the body and show you what i mean
the conditional operator itself is the question mark and colon symbols used in
combination with one another the way these two are actually used is you
start off before the question mark with something that produces a boolean value
so maybe to represent that here I will just put boolean inside some parentheses
that boolean value or that expression that produces a boolean value is then
followed by a question mark
following that we then have some statement or operation that we want to
take place if the boolean value is true
that true value is then followed by a colon and after that we thenhave
some
condition or operation we want to occur whenever the boolean value is false so
it's kind of an interesting one a little bit more complicated than a lot of our
other operators but it does open up a lot of very interesting possibilities
for what we could do with it
uh... for starters let's say we create a variable and call it answer
then we could say something like answer equals
and then we could do some type operation some kind of statement or expression
that produces a boolean value so maybe just for simplicity sake nine is
greater than seven
i'm gonna follow that then with a question mark. if nine is greater
than seven whatever it is that follows this question mark
that is what will actually end up being the value of this expression so let's put
bigger there.
i'm going to follow that by a colon. This of course then is the false section, so if
nine is not greater than seven
this will be the value returned by the expression. so let me put in the string literal
smaller there. if we do a document dot write line and print out the value
of answer
what's actually going to happen is the script is of course we start off by
creating the answer variable we then execute this expression
when we execute this expression javascript is gonna check to see if this
expression that's highlighted now produces a true or false value.
now of course you and i know that nine is greater than seven so that's gonna
come back as true because it's true what's going to happen is this value is
what's actually going to be
that's actually going to become the value of the overall conditional
expression
so bigger is what we then actually be sort of returned I guess you could say and
assigned to the answer variable
if we were to have swapped thisaround for example instead if nine is less than
seven then, when javascript checked
this it would of course find it to be false
which means that we then take the value of smaller and that would become
the value of this expression; the thing that would be assigned then to answer
let me put it back to it was initially where I checked to see if nine is greater
than seven so answer should come out bigger. if we take a look at that in our
browser sure enough, that's exactly what we get, "bigger."
so that's basically way the way that the conditional operator works a little bit
more complicated like i said but
could be potentially useful
um... i will mention that i'm not a super big fan of this conditional operator i
think it's kind of cryptic and difficult to read
some people call it concise uh... but i think it's just a little bit more
complicated than it really needs to be in the way it's actually written. plus
I burned my hand once on a conditional operator when I was a small
child but i've never really forgive them for that.
and anyway there's a number of other things of course that we could be with
them we could uh...
take the value of some variables so maybe i got some variables called num 1
and maybe give it a value of fifty-six and we could pretend for example
that that value would actually come from a user maybe they would be entering it to a
prompt or that of a
form or something along those lines well we could then maybe do something like say
if um...
the value of the num-one variable is greater than one hundred
then what i want to do is i want to do a document dot write line and printout
uh... let's say
uh... that's a great number
or uh... if that
condition is not true then what I will have it do instead is do a document dot write
line
and printout uh...
uh... your number is lacking
something along those lines. so more or less we uh... like I've done
here instead of actually getting the conditional operator to produce a value
which has been assigned to a variable
we could actually have the conditional operator based on its true or false
value decide which of two statements actually execute if i come over and
actually run this , it comes back of course and tells me your number is lacking. I neglected to
put a break in here which is why it showed up on the same line as bigger but they did
function just fine so uh... we can use the conditional operator for doing those
sorts of things as well
okay i have reopened our uh...
lightspeed program that we wrote a litle bit ago
and i wanted to show you how we can potentially use the conditional operator
in this litle program to improve it a little bit. before we actually improve
though, we need to actually understand what's wrong with it. If you remember let's
switch over to my browser and hit refresh
it let's us enter the number of days I say 12 days for example then it comes
back and tells me approximately how far light will travel in that number of days
but what happens if i hit refresh run the program again and instead of
typing in a number what if i just hit ok without entering anything at all
what the script actually does right now
is it will take the nothing that i entered basically
run through all of our calculations and actually come back with the value of
zero for the number of miles
really not disastrous the program doesn't crash but the output is
likely to maybe confuse some people make them wonder hey,what went wrong
so let's see if we can fix that. first of all
what i could start off by doing here in the code is maybe here after the
prompt statement where I actually get the number of days
i could put in a conditional operator that looks for that empty string that's
actually returned whenever the user just it's ok without entering anything.
and if it finds it maybe put a more appropriate value in its place
so what i'm going to do is I'm going to take my days variable and i'm going to
assign to it a value that i will then returned from a conditional operator
statement so i'm going to say if the current value of the day's variable is
equal to the double equals sign equality operator it's equal to an empty string
just two quotes right next to each other with nothing between them
then i'm going to say return the value of zero instead.
if the value of the day's variable is not an empty string then we don't want to lose
what the user actually typed in so if days is not an empty string i'm just gonna say
return the current value of the days variable.
so if the user enters an empty string basically doesn't put any useful value
at all we'll get zero otherwise we'll just keep the current value of the days variable
so let's see how that works
back to my browser refresh
enter the number of dates twelve
and in our big case with good input it still works just the way it should
if I run it again though and just press okay
then it comes back and it says light will travel zero miles in zero days.
so it makes it make a little bit more sense to the user\. hopefully they will understand that
since they didn't enter anything,
we just took that to mean zero
It could be better maybe we'll fix it up more here in just a little bit
but there's another problem along those same lines that we might also want
to fix. if i hit refresh and it asks me for the number of days and instead of
typing in something or hitting ok at all what if I click cancel
Then it comes back and tells me that light will travel zero miles in null days.
what actually happens with the prompt statement is that if we get out of it by
clicking the cancel button the null statment, or the prompt statement actually returns
the value of null so we test for that again, take a more appropriate value
just like we had with the empty string.
so back over to the code again what i can do here is just like before
assign to the day's variable a value based on whether days is equal to null
remember null is sort of a value
datatype thing all to itself we'll run into occasionally in other places. now if
days is equal to null, let's do the same thing where we take the value of zero
otherwise we'll take the value of days. let's see how that works
alright enter number of days type in twelve everything works fine.
running again if i put in nothing and just hit okay
we get zero like you would expect if we run it again and hit cancel
we again get zero so there we go we fixed it up the same way
and now there's one other thing that we could do
to maybe make this program a little bit more friendly using the conditional
operator
and that is that if we end up with the value of zero in the days variable which could
happen if the user actually enters zero
if the user enters nothing and presses ok, or if the user hits cancel, then what we
can do in that situation where we have zero days is maybe we could decide
to display a different statement instead of the light will travel so many
miles in so many days statement
so what I am going to do for this then is i'm going to declare a new variable
down here towards the bottom of my script before I do the alert. i'm going to call it
output
and what i'm going to do then we are again going to put together a conditional
statement and this conditional statement is going to help us decide what the value of
output is going to be so basically what i'm gonna say is that the value of the
day's variable is equal to zero
then what i want it to do is to make the value of the output variable you should
enter a more interesting number
and if the user doesn't enter zero if we actually do have another value
then i will stick with the same basic output line that i had before
I will just copy it out of the alert statement and paste in here instead
then down in the alert statement i'm going to instead now just display the output
uh... displayed the value of the output there
so we work our way down through the script we creat our light speed variable we ask
the user for the number of days we might get a number, we might get
a null
we might get an empty string.
if we get a null or an empty string we set the days to zero
we then go through and we do all of our calculations we create our output
variable and then we say
if the number of days is equal to zero
right here
then you should enter a more interesting number otherwise we display the output
from our calculation
or assign that to our output variable anyway and then actually display
the value of that output variable here in this alert.
so let's see how that works
if i type in a number of days
everything works just the way it should if i just click ok without entering
anything it says you should enter a more interesting number
If I click
cancel you should enter more interesting number
so everything seems to be a little bit better at this point about the script
everything's a little friendlier and working a little bit smoother
because of the use of the conditional operator. now there are of course other little
problems in the script as well like what happens if it asks me to enter the
number of days and I put in victrola
then it comes back with light will travel NaN miles in
victorla days which certainly doesn't make any sense
but maybe will save fixing that until later when we talk about functions.
The last set of operators then we have to take a look at are the double
ampersand and the double pipe and the single exclamation point.
The first two the doubling ampersand and the double pipe are called the default
and guard operators
they're also sometimes referred to
as the and or the or operators
they're both binary they both do logical operations uh... producing some
value which is usually seen as a value or as true and false. we'll need
to come back here maybe in an addendum this uh...
to this particular episode and talk about truthiness and falseyness
but we will take a look at those here just a second they're very useful and in
the last one the exclamation point is unary operator
it takes a boolean value true or false as its operaand and simply reverses it
so of course if we were to say not true the answer would be false. and if we say
not false the answer would be true
so let's look at some examples of these.
Next let's take a look at our logical operators. there's only three so this
won't take too terribly long.
uh... as before script tags inside the body section. now our logical operators
are the exclamation point which means not
we have the guard operator which is also sometimes called AND. It's the double ampersand.
and we have the uh... default operator which is sometimes called
the OR operator. it's a double pipe
uh... in case you don't know what the pipe symbol is usually on the same key
as the backslash basically looks like a vertical line sometimes it has a look
uh... bite out of the middle of it
but that's called the pipe. Now let's take a look at the not operator. First it's
really the simplist. It's a unary operator and all it does
is take the boolean value and reverse it
so if we were to for example say not true
any answer we will get back its false. if we were to say
not false any answer we get back is true. Boy, thats complicated isn't it?
Every once in awhile that not operator comes in handy but in general I
believe you should try to avoid it. It can get a little bit confusing
when you have nots thrown in much larger more complicated expressions
just like people don't like nots in multiple choice tests and thing like
that because it confuses them
you should try to avoid using it in your code too.
Sometimes you run into the situation where not using it will cause
of a lot of trouble in which case i'm
pragmatic when it comes to that i say go ahead and use it.
But don't use it when there's just as easy of the solution to
not using the not operater. So anyway, that is not operator. Now
the guard and the default operators
are a bit more interesting. Let's start off here for example
uh... by doing a document dot write line
and putting in let's say true
and false.. The double ampersand is called the AND operator
because it operates very much like the word AND does in the English
language.
when we say one thing and something else what we actually expect is to
get both.
and the AND or guard operator is the exact same way. So here when we say
true and false, basically what we're doing is we're giving it something
that's true
and something that's false which will not make the and operator happy.
The and operator wants everything to be true.
so when you say true and false what we'll actually get back as a result is
false and operator being unhappy, more or less. If we were to say true and true
then that will make the and operator happy and will come back and tell us true.
but if we were to put false in the statement anywhere false and true, true and
false, false and false, all of those at the AND operator are going to end up
returning false.
basically the only way to get back true with the and operators is to put in true
and true.
Now of course it's not very realistic that we actually put true and
false here what would be much more realistic would be something like where
we have variable say X that have a value
good old nine again and we were to say something like x is greater than zero
and
let's say X is
less than ten. now both of those sort of sub expressions these two comparisons
the X greater than zero and x less than ten
each of those will be evaluated first producing their own true or false value. Those
true or false values can then be
worked with by the guard operator.
uh... the double ampersand or AND, whatever we want to call it here so here in that case X is
nine x greater than zero is true, x less than ten is true so true and true will come back and
give us true.
There we are. the second, I guess the third actually of these operators
uh... the default operator
the double pipe
or the
OR operator. Whatever you want to call it.
works very much like the guard or AND operator. as we could start off by playing
with it here just a little bit.
we could say something like for example true or false, which will come
back in this case and give us true. Now the double pipe the OR or the
default operator basically the way it works is again very much like the word
or in the english language if we say one thing or something else then we expect
one or the other
but not necessarily both.
so with the OR operator as long as there is a true
as one of its two operands then it will be happy in will get back that
true
but uh...
as long as
we don't end up giving it uh... sort of a double false a false on both sides
that would be the only situation where we actually end up getting a false
if we do something like false and false.
That's like saying give me hamburgers and pizza and getting a sandwich it's nothing at all like you
actually wanted.
and just like we were talking about before
um...
it would be fairly unrealistic to actually be putting in boolean literals here
instead we would probably have some other type of sub- expression using
comparison operators or something along those lines
that we would be using instead.
Okay,so anyway that's what uh... that's with those two operators appear to be on
the surface and the NOT operator is really just that it doesn't get a whole lot
more complicated actually but uh...
uh... but the
guard and the default operator are actually a little bit more interesting
Let me show you this for example.
If we were to do
uh... let's say uh... uh...
well we already have a variable X. Lets use the variable X we already have.
Let's say if X is equal to
and let's put in true or false.
uh... then let's do a document dot write line.
documents dot write
line
mhm work it works uh... X,what we have of course get back there is true
so really all we've done at that point is we've taken the or operator out of the
document write line statement assigned it's value to a variable and
it printed out that variable. but i did it that way because i wanted to show you
something else that we can do with these operators that can be kind of
interesting for example what happens if i were to put nine
or false? On the surface that doesn't seem like it makes sense as long as
you're thinking of the double pipe just as being an or operator, because nine and
false to really sort of different things, how can they be compared that way.
what we haven't discussed uh... and maybe when we come back to discuss a
little bit more later is that
just about every value every literal
every expression in java besides producing a
uh... value like we've been working with and seen,
can also be evaluated as being boolean,can be evaluated as being just true or false
The number nine for example. The number nine of course is just the value nine
but javascript also sees that value as being true so if we come over and we take a
look we can see what we actually get from our default operator now is
actually the number nine.
so
we find that uh... default operator here the or operator the double pipe
is uh... actually doing a little bit more behind the scenes than we realize that
it is.
if i were to say do nine or blank it comes back and gives me nine.If i
were to say blank or nine that way, I still get nine. You see the way the default
operator is actually working is that it will always return the value that it
considers to be true over one that it considers to be false.
so let me go back and show you one other aspect of it here if we say nine or blank
we get the nine back.
what happens if i say nine or ten
Whenever we get two things that are considered to be true like nine or ten
then it always gets us back the first one the one that's on the left in this case.
Nine.
and that can actually coming in handy in a number of places. you might remember
lightspeed example where we had something like a prompt here i'm
gonna tell the user to enter something.
That should leave them guessing.
uh...
if i were to then say uh...
X equals X or
uh... i said enter something
a string
then what happens when we actually run this program it says enter something.
if I put in something like a number or a string
then it comes back it actually gives me that string but if I leave it blank,
it says "i entered something."
if i hit escape or hit cancel "i entered something."
so what's actually happening here is that we're taking the return value from
prompt and we're putting in the X variable
we are then saying X or this string. Now this string is always considered to be true
all right uh... it isn't an empty string it's considered by javascript to have a true value
so uh... really what's going to determine what the result of that
expression is, is what the value of X is.
if i actually type in a value then that value is also true so javascript sees
this is being true and true and it returns the first which is just whatever
we entered, whatever we stored previously as X.
but if i just hit enter and leave it blank or I hit escape which we know
result in a null,
both empty strings and nulls in javascript are considered to be false.
So in those two situations when the value of x comes back false it takes the
true value instead my string over here and assigns that to X so that's what i get
when I actually print it out.
the guard operator actually has that same sort of second level to it. That
hidden work that it's doing
the difference is a guard operator, the double ampersand or what I was calling
before the AND operator
will always return the false value
or the second value. So kind of exactly the opposite of the
OR. the ORalways returned the true value or the left value
uh... guard operator always returns the false value or right value. So sometimes
those come in handy. We'll probably probably come back to explore this
little bit
more uh... in the future
the last thing we really have to talk about with operators is that operators
must obey a precedence.
uh... basically a ranking, same sort of way you've probably talked about
operator precedence in an algebra class um... in algebra they actually teach a
little uh... mnemonic to help people remember operator precedence uh...How's
it go?
Please excuse my dear Aunt Sally. they believe is the uh... mnemonic
they typically teach in the algebra class.
uh... basically uh... please excuse my dear aunt sally what it means is that
parentheses, P for please, uh... is the highest precedents that always happens
first so parentheses in any expression will always be the first
thing that's evaluated.
excuse is exponents which we don't really worry about too much at this point
javascript
my is for multiplication
second level of precedents
uh... dear is divide.
aunt is addition, sally subtraction
um... so anyway if that helps you remember operator precedence then that's
a good way to help remember it. but here's a little chart
it just kind of breaks down all of the different operators in a couple of the
common functions that you're going to run into in javascript
you can see that indeed the parentheses are the very top level they
always will be executed first
uh... on the second level we have some of the other operators we talked about
plus the type of function that we discussed in the previous episode
after that we have multiply, divide, modulus followed by addition
subtraction
in we start running into a lot of our comparison operators less than,less than
or equal to, greater than greater than or equal to followed in the next level by
equality operator, not equal to operator, non equality operator.
you can have our guard and default operators, then we've got our assignment
in all of our short cut operators, and then the very lowest level of precedence in
javascript operators is the comma which we will not see used very often at all.