- [Joe] In this video, we're going to talk about variables
and how to make them.
So here we are in the Chrome JavaScript console.
I've made it really big by typing command equal sign
a whole bunch of times,
and I've changed the doc settings.
So it's over on the left side,
and I've pretty much minimized the entire rest
of the regular browser window away
so we can concentrate on the console.
A variable, as you may have heard in math class
is a place to keep things that are unknown.
That's one way of looking at it.
For our purposes, you could think of a variable
as a box with a label on it.
We can label the box whatever we want
and put pretty much whatever we want in there,
and we end up with a convenient way to refer to some data.
If we were approaching this the way you'd approach it
in math class, you'd have variables called things like X.
That's enough to create a variable,
but it's an empty box right now.
To give this variable X a value,
we add a space, then an equal sign,
and then we give it a value.
So we could type 32.
And we end every line in JavaScript programming
with a semi-colon, if we're being good.
And by good, I mean, JavaScript doesn't require it,
but semi-colons help avoid confusion.
What I've done here is called assigning a value
to a variable.
I'm assigning the value of 32 to the variable X.
So now in the console I hit return,
and what I've just typed is executed by the browser.
Now, nothing here happens except the assignment,
I get back the value of 32 in this case.
But in the console, I can type the name of the variable
I just created again, and do nothing else
except in the line with a semi-colon
and I get back the value I just assigned.
And in Chrome,
it actually preemptively executes this for me,
and gives me a little preview of what will happen
if I were to execute this.
So I hit return and there's 32 again.
Calling things X is something that gets
a lot of complaints in math classes,
and we can certainly do better in our programs.
Variables can be named almost anything
that starts with a letter, underscore or dollar sign.
So I can create a variable called whereAmI
and set it to Santa Barbara, California.
The part in quotes is a string, which we'll get to later,
but that's how you store things like words or sentences.
Now that I've stored a couple of variables,
I can see their values and the JavaScript console
now knows about my variables
and will start to complete the names for me
if I start to type them, like this.
I can also keep the label, but change what's in the box.
So I can just do the assignment again with an equal sign
and change X to 45.
And I can change whereAmI,
I start to type this and then I can complete it
by hitting Tab and equal sign.
And again, Chrome is previewing
what's actually in there right now.
I can change it to Los Angeles.
Or,
I could change it to 75.
I did this by hitting up from a blank line
to get the last thing that I typed.
So whereAmI, set that to 75.
I can set it to whatever I want.
Of course saying where I am is 75
doesn't make sense in real world logical terms,
but JavaScript doesn't care what I assigned in there.
So far, I've been assigning variables
just typing the names.
I can also type the keyword var to create variables.
Generally speaking in actual code, outside the console
this is what you'll do.
So we'll do it here.
And then I'm going to create a few monsters.
So we'll say monster1 equals Grover.
Now I'll type a comma, Monster2 is Cookie Monster.
Monster3 is Animal.
And that was semi-colon.
This just saves me a little bit of typing
without having to do all of these on separate lines.
If I type each variable's name and it return,
I get exactly what I put in.
A couple more details.
Your variables can be named almost anything you want.
And I recommend you use names that are descriptive
because programs aren't just for computers,
they're for other humans to read as well.
The computer isn't gonna care what you call
your variables for the most part,
but humans, definitely will.
So make sure you name your variables
something that indicates the sort of thing
they're actually going to contain.
If I were writing a program dealing with how much it costs
to ship a package, for example,
I might have variables name things like package dimensions,
or tax rate,
and so on.
Starting a name with a lowercase letter
and mashing on additional words with capital letters
like this is called camelCase.
And it's a pretty common way to name things in JavaScript.
There are a few words you can't use for your variable names
because they're part of JavaScript itself.
They're called reserved words.
From what we've seen so far,
you wouldn't be able to use var,
because JavaScript already claimed it.
If you're curious, there's a list of reserved words
available on the Mozilla JavaScript reference site.
And of course, if you're using a nice code editor,
it will highlight those words for you
so you won't accidentally use them.
Chrome highlights them in purple here.
Things like var or function.
A string is character data.
Meaning things like sentences, words, single letters,
numbers, or punctuation.
Basically it means anything between quote marks.
So for example,
I could say "This is a string."
Chrome highlights in red for me.
When you formulate a string like this,
it's actually called a string literal.
Literal here basically means you're making data
of some type using the simplest notation possible.
So making a string literal like this,
means I'm putting string data inside quote marks.
There are other less convenient ways
to make strings as well,
but this is what we use 99% of the time.
A string doesn't have to be a sentence,
it can be a number inside quotes.
So it's a string of one, two instead of 12.
These are two different things
as far as JavaScript is concerned.
12 Versus a string 12.
You can make strings using these double quote characters,
you can also make strings using single quote characters.
This is also a string.
Whichever you use, you need to begin and end the string
using the same character.
So I can't do this,
a single quote at the beginning, double quote at the end,
I try and execute this, I get a syntax error.
Doesn't work.
Sometimes you're gonna need to write a string
that will have a quotation mark inside it.
This comes up a lot if you're working with HTML
and JavaScript.
So if we're writing a piece of HTML like this,
it works because I put single quotes at the beginning
and the end with the attribute.
using double quotes.
This is one of many times where syntax highlighting
is helpful.
Chrome offers some degree of this,
but let's switch over to our code editor
so we have a little more flexibility.
I have here a blank file,
and I'm going to use the default command,
command K, followed by typing M.
This lets me set the language mode for the file.
Going to type Java to get down to JavaScript,
and hit return.
Now it knows that I'm trying to type some JavaScript.
The color scheme that I have is gonna show strings in red,
so I can see whether a string is enclosed correctly.
If it is, everything inside stays red,
if not, it starts to turn black.
So I'll try that little snippet of HTML again.
The double quotes contained in the single quotes works fine,
and the opposite works as well."
"This is Joe's favorite string.
You will, at some point need to include quote marks
of both kinds inside the string,
like say, "This is Joe's favorite string."
You can see that the color starts to change
because I'm breaking the way that the string is delimited.
To JavaScript, what I have here right now is a string,
followed by some data in the middle
that's gonna make JavaScript mad,
and then another string.
To fix this, I need to use a backslash
to do what's called escaping the string.
So I'm going to put a backslash
in front of each of these quotes
that's supposed to be a part of the inside
of this entire string.
So for every quote mark that's causing trouble,
I add that slash.
Just to prove this works,
I'm going to select this, copy it and return to the browser,
paste it in.
There, it works.
And it's printed without those backslash marks,
which is a little bit confusing,
I couldn't just copy this and re-execute it,
It won't work.
As you can see, this is turning black again.
Backslashes let us do one more helpful thing:
Breaking strings up into multiple lines.
So I'll switch back to my editor,
and if I want to write another string
called "This is Joe's favorite string ever."
Got all these squiggly lines
telling me that this is not working.
But if I put a backslash on the end of each line,
I'm putting a little extra space in there
just to make it a little more readable.
All the squiggles go away,
the whole string is highlighted in red.
And then I just end the string
with the same kind of quote mark that I started it with.
For something that's short, it doesn't really matter,
but when you need really long runs of text,
this can be pretty helpful.
Along with the data we've put in the quote marks,
strings have a few tricks up their sleeve.
We can access what are called properties and functions
also called methods on any string.
They're like a toolbox we can open to do things
to our strings.
A property is a single piece of data
like the length of a string,
and a method is a bit of code to do something more involved
like convert string to uppercase.
So, I can assign a string to a variable.
Let's make one called myString,
and say, "This is my strength.
Leave it alone."
And now if I start to type my string and type a dot,
I can see all kinds of information that's available
on the string,
so that includes the length.
As you can see from this little preview is 34,
I'll still hit return.
So length is a property,
and then a method would be say to convert this to uppercase,
toUppercase.
I start to type that and it's completed.
So I'll hit a right arrow to finish that off
and type two parentheses to tell JavaScript
that I want to execute that method and actually do it.
And that returns the same string,
but with the whole thing turned into uppercase,
it doesn't change the original value.
So if I type my string, hit a right arrow, hit return,
my original string is unchanged.
Interestingly, you can do this without variables too.
JavaScript can take a string literal,
like "This is my string,"
and grant you access to the same properties and methods.
It's much more common to do this with variables,
but you'll occasionally see this usage as well.
So I can see that this string is 17 characters long.
We're going to talk about another of the basic types of data
in JavaScript, the number.
And we're also going to talk a little bit about math.
Some programming languages have different types of numbers
like integers, floats, doubles, and so forth.
All numbers in JavaScript are of the same type
called number.
So 12 in JavaScript is the same thing as 12.0,
which makes sense in terms of how we think of numbers
in the real world.
In programming, that's not always the case,
but in JavaScript, it is, they're both the same thing.
You can have numbers with lots and lots of decimal points.
Let's just add a whole bunch of decimal points to this guy.
And you can see that at a certain point,
it starts to get cut off.
Although you can see, I put this in with,
I don't know how many digits this is,
it's a lot of digits.
After the decimal point,
JavaScript can't handle that much precision.
You probably won't care about that most of the time,
unless you're getting into some pretty serious math.
Along with regular numbers,
of course, you can have negative numbers,
all that sort of thing, negative 12 works,
JavaScript can also represent infinity if you need it.
There is a built-in keyword called Infinity
with a capital letter.
In JavaScript, Infinity is any number that's larger
than a very, very, very large upper bound.
Odds are you won't run into it,
but there is such a thing in JavaScript as infinity
and even negative infinity.
There's also this, which stands for numnumber.
And this is what you get when you try to do math
and the result because of an error in your code,
most of the time or for various other reasons,
you can end up with something which is not a number.
Be on the lookout for this
if you're trying to do any kind of math
and you're starting to get unexpected behaviors.
If you assign a number to a variable,
like I have here with my number,
and I'll re type this and type a dot,
you can see that there are methods available on numbers,
just like there are with strings,
although I don't find myself using these
quite as often as I do with strings.
More interesting in the methods that numbers have
is a built-in global object called math.
We'll talk about objects later,
but this is like another toolbox with functions and methods
for doing things to numbers,
like rounding, chopping off decimal points,
taking square roots and so forth.
So if I type Math capitalized like this,
then a dot, that opens up the toolbox.
And all of these methods and properties are shown.
Next comes to the method name,
and then I can send the number into the toolbox
with parentheses.
So let's say I wanted to round a number.
And so that rounds this number
with all this decimal precision down to 12,
or if I change the decimal point to something over .5,
it rounds upward.
Math has a lot of useful functions
when working with numbers.
Including one for generating a random number,
okay, technically pseudo random,
a good enough for our purpose,
It's called Math.random.
This generates a random number between zero and one.
If type up, I can execute again,
and I get a different result every time.
And you'll notice that the pre-execution that Chrome does,
it gives a different result every time
which is handy if you need some randomness in your program,
like simulating the role of a dye or something like that.
This is not nearly everything that pertains to numbers
in math and JavaScript,
but now we know a little bit about them
and can recognize them in code.
You may know from the way people talk about computers,
sort of colloquially,
that computers deal with ones and zeros
on and off, true and false that sort of dichotomy.
Boolean is a data type that can capture true
or false for us.
So in JavaScript, a Boolean is one of either true
or false.
They need to be spelled exactly like this,
all lower case and spelled correctly
in order for a JavaScript to know
that you mean true and false.
If you write True with a capital T,
JavaScript is gonna think you mean a variable by that name.
Notice that it is not colored as a language keyword
here in Chrome.
Because it's so similar to that existing keyword,
you would do really well to avoid naming any variable True.
Likewise, all caps will not work either
or any combination of characters,
only all lowercase for both.
I can set variables to true or false,
like say buttonHasBeenClicked, equals false.
And by doing so, I would say that this variable
is a Boolean.
I can use this variable to track whether someone
has clicked a particular button on a page.
Started out set to false,
and then sometime later when I know that the button
has been clicked, set it to true.
I can act on that information somehow.
Booleans are important because they're one main way
of getting answers from your programs
about the state of your program's world.
What I mean is you can ask questions in the form of,
is this true or is it false?
It's one of the questions that JavaScript can answer for you
without having to do a bunch of extra work.
These questions that you can ask JavaScript
and get back the answers for,
are generally in the form of comparisons.
We'll look at these in more detail a little later on,
but just to give you a preview,
it looks like this.
I'll make two variables,
say my location equals Santa Barbara
and my other location will be Los Angeles.
And now I can ask a question of JavaScript.
Are these the same?
The way I can ask that question is by writing a statement
and using three equal signs to tell me,
are these exactly the same?
So my location with three equal signs in between,
my other location.
So I'm saying, is this exactly the same as this?
And you can see that the answer is false.
JavaScript knows the values of these two variables
and it can tell me whether or not they're the same.
I define them right next to each other, myself.
So this is not all that exciting,
but if there's a lot of other code in between the definition
and the comparison where the values might change
at some point,
this can be a very useful question to get the answer to.
So now, if I change my other location
to Santa Barbara like this,
and I asked the same question again,
I'll hit the up arrow, I get back, True.
Variables are assigned with one equal sign
and comparisons use more than one.
This is a very popular typo that introduces fun little bugs
and the programs of developers of all levels of experience.
So that's a look at Booleans, true and false,
very useful for answering questions in your programs.
(upbeat music)