Beginner's JavaScript Course Guide
Beginner's JavaScript Course Guide
Beau: This is the Beginner’s Javascript course you are looking for. My name is
Beau Carnes. And I’m with [Link]. In this full Javascript course you will
learn everything you need to know to get started with Javascript. This course is
perfect for beginners or anyone that just wants a refresher on basic Javascript
syntax.
[Link]
This course actually goes along with the [Link] Javascript curriculum.
So, if you want some live coding challenges to go along with every part of this
course, you can check the link in the description to that curriculum. But this is
a completely standalone video. So, you don’t need to go through [Link],
but it could be helpful.
[Link]
Also, after this course, you’re going to want to complete some, or build some
Javascript projects. So, I have a link in the description to some project
tutorials. But then after that, you’re going to want to create some projects on
your own. That’s how you really learn Javascript. You have to create things without
going through a tutorial and just use a search engine to find the things that
you don’t know or need to learn.
[Link]
To go along with the freeCodeCamp curriculum, I have all the ES6 stuff in the
second part of this course. That’s pretty much it. Let’s learn some Javascript.
[Running Javascript] So, how exactly do you install Javascript? Well, for the most
part, you don’t. Actually, all web browsers can run Javascript. Which is great
because a lot of devices have web browsers on them.
[Link]
So, when you write something with Javascript, it will run on all sorts of devices
and operating systems. So, you have a few options for writing Javascript. Let me
show you a few things you can do to follow along with this course. You could
download a code editor. Here, I have Sublime Text. You can also use Visual Studio
Code or Atom or any code editor.
[Link]
And I’ve created an HTML file because HTML files can be opened in web browsers.
And I have these <script> tags – these are HTML tags. But within our <script> tags,
we have our Javascript. So, if I open up this file in a web browser, it looks like
this. Well, I can open up my Javascript console.
[Link]
And in the console, you can see it says “hello world.” That’s right from my
Javascript program. So, whenever you do [Link], it’s going to show on the
console here. You can also just use the code editor that’s included on
[Link]. Like I mentioned, this course follows along with the Javascript
curriculum on [Link].
[Link]
And there’s a built-in Javascript editor right in here. And then it shows you the
console down here. Another option would be to use CodePen. If you go to [Link],
going to go to Create Pen. And then there’s going to be three windows. HTML, CSS,
and Javascript. Well, we just care about the Javascript. And in this course, we're
not going to be doing anything with HTML and CSS.
[Link]
We just need the Javascript and the Javascript console. So, if I do [Link] and
then do (“Hello World”) then we can see right in the console "Hello world.” The
final thing you can do would be use Scrimba. Most of the course I actually recorded
using [Link]. So, if you want, you can use [Link] to follow along.
[Link]
Once you log in, just click the [Plus] button. I’m going to [Javascript]
[Playground] and then [Confirm]. And it’s going to open up a new Javascript
window. Now, I can increase the font size here. And it already has [Link]
“Hello from Javascript.” And you can see in the console right here “Hello from
Javascript.
[Link]
” Also, if you hit [Reload], it reloads everything. And you'll see this popup
“Hello from Javascript.” So, that’s something interesting about Scrimba is that
has two ways of logging in the console. We have the popup and then we have the
console here. You’ll see that in this course too, the two different ways of
logging to the console.
[Link]
[Comment Your Javascript Code] The first thing we'll talk about in Javascript is
comments. Comments are lines of code that Javascript will intentionally ignore.
They don’t do anything. They’re just used to create notes for yourself and others
about what the code does. So, if you do a // you can make an in-line comment.
[Link]
An in-line comment means it’s at the end of a line of code. For instance, I can
put var number = 5. That’s a way to declare a variable. And we'll talk more about
that later. But right now we're just talking about comments. You can see that this
code is in color because the code editor knows that that’s code that’s going to
run.
[Link]
And the comment is automatically grayed out because it’s not going to run. We can
also do an in-line comment or I mean a multi-line comment. If we do a /* and I can
put "this is a,” and then I can put "multi-line comment.” And I'm going to end
with a */. So, it begins with a /* and ends with a */.
[Link]
And you can put as much text as you want in between these. And you can see this is
all grayed out because it’s all a comment. And then afterwards I can put number =
9 and you can see it will be in color again because it’s no longer commented out.
[Data Types and Variables] Now we're going to talk about data types and variables.
[Link]
In computer science, data is anything that is meaningful to the computer. And
Javascript provides seven different data types that you can use within Javascript.
Now, some of the more obvious and most common are strings and numbers. A string is
just any sort of text. A number is a number. Now let’s go from the top.
[Link]
So, undefined is something that hasn’t been defined. You may have a variable that
you haven’t set to be anything yet. Null means nothing. So, you’ve set this to be
something and that thing is nothing. So, you can say this is null or nothing. A
boolean means true or false. We talked about string. A symbol is an immutable
primitive value that is unique.
[Link]
Now we'll tall more about those later. A number is a number. And an object can
store a lot of different key value pairs. Again, we'll talk more about those
later. Now, you are often going to set data into a variable. A variable allows
computers to store and manipulate data in a dynamic fashion. It’s basically a
label to point to the data.
[Link]
A variable is almost like a box. And you can fill it with anything. You’ll fill it
with the data that you want. So, to declare a variable, one way is to use the var
keyword. Var stands for variable. And I can say myName. I can set this to anything.
It can be any of the datatypes above. But it’s common to set something to a string.
[Link]
So, I can set my name to be “Beau.” Now later, you can set it to be something else.
I can say myName = 8. And you can just set it to other data types later. Now, there
are actually three ways to declare a variable in Javascript. So, var is one of
them. And for a while, that was the only way. But there are other ways too.
[Link]
There’s a way called "Let.” So, I can say let ourName = “freeCodeCamp”. And then
the other thing would be const. So, I can do const Pi = 3,1004. Now, the difference
between var, let, and const, a var is going to be able to be used throughout your
whole program. Let will only be used within the scope of where you declared that.
[Link]
Now, we're going to be talking about let and const more later. So, I’m just giving
you a brief overview of what they are now. Const is a variable that should never
change. It can never change. So, like right up here, I declared myName, but then
we changed it here. So, it started out to be Beau and we changed it to 8.
[Link]
Const, you can never change it. If you do try to change it, you’ll get an ERROR.
Okay, that’s all for now. But like I said. We'll be talking more about the
different types of variables later. [Storing Values with Assignment Operator]
There’s a difference between declaring variables and assigning variables.
[Link]
Here’s how you assign a variable. var a and then a semicolon. I didn’t mention this
earlier, but you end all lines in Javascript with a semicolon. Well, it’s not
actually required. You can actually just skip the semicolons completely, but most
people recommend that you put a semicolon just so it’s obvious where the end of the
line is.
[Link]
So, here, we are just declaring a variable to be called a. And then here, we are
assigning a variable. We’re declaring and assigning in one line. So, we're
declaring it “var b” And then the equals sign is the assignment operator. It means
that 2 is being assigned to b. We're not checking if b = 2.
[Link]
We're just assigning 2 to be. So, after that, we can actually assign other things.
So, I can say a = 7. So, now I’ve just assigned 7 to a. I didn’t have to declare a
because it was already declared. And I can also say that b = a. So, I’ve now
assigned the contents of a to b. And I’ll put the semicolon there.
[Link]
One thing I want to tell you about is [Link]. [Link] allows you to see
things in the console. So, I’m going to [Link](a). And if I load this here,
you can see down here in the console it shows 7. So, right now we've assigned a to
be 7. And so, when we [Link](a) it shows 7 down there.
[Link]
If we put another [Link] right here, this will allow us to show what a was up
here and then down there. So, [Link]. Now, if I run that, we can see at
first, a was null. And then now it’s 7. So, here is null. And then it’s 7 down
here. So, you can check what variables are at various points in your program.
[Link]
[Initializing Variables w/ Assignment Operator] Now I’ll show you another example
of initializing a variable to an initial value at the same time it’s declared. So,
I’m going to say var a = 9. So, the var a is declaring it. And the = 9 is
initializing it with the assignment operator, which is the = sign.
[Link]
[Uninitialized Variables] Before we do anything to these variables, they are
uninitialized. That means their value is undefined. We have not set them to
anything. But it’s simple to fix that. I’ll just set this to five. I’ll set b to 10
and then we can set c to a string. That’s going to be “I am a string”.
[Link]
And we always have to put it in quotation marks like that. So, you can see a + 1
is going to equal 6. 5 + 1 = 6. b = b + 5. That’s going to be 15. And then c is now
going to say "I am a string”. [Case Sensitivity in Variables] Variable names and
function names in Javascript are case sensitive. That means that capitalization
matters.
[Link]
So, this declaration here is not the same as this assignment. Even though letters
are the same, the capitalization is not the same. So, it’s not going to assign
correctly. And in here, you’ll see there’s an ERROR if we try to run it because
this has not been defined. It has not been declared. It’s generally common practice
to use camelCase.
[Link]
So, let me show you how we do that instead of StUdLyCapVar, it’s going to be
studlyCapVar. So, the first letter is always going to be lowercase. Any time you
have a new word or a new section of a word, you just capitalize the first letter.
And so, we can change this. This one is correct. So, now we just go down here.
[Link]
studlyCapVar. And then we just do properCamelCase. And then titleCaseOver. So, now
all of these should be defined. So, we declare them here. We assign them right
here. And then this is not going to give us any errors. It’s going to behave
exactly how we want it to behave. [Adding Numbers] Adding two numbers in Javascript
is pretty straight forward.
[Link]
You just use the plus operator. So, this says 10 + 0 which equals 10. We can also
do, 10 + 10 which is going to equal 20, if we do a [Link], and I can put sum
here. And then you’ll be able to see that the answer is 20 right in the console.
10 + 10 is 20. [Subtracting Numbers] And subtraction is also what you would expect.
[Link]
We have the subtraction sign here. This says 45 – 0. We can also do 45 – 33. And
then that would equal 12. So, the difference variable equals 12 now. [Multiplying
Numbers] Multiplication in Javascript uses this * or a star symbol here. So, this
says 8 * 0 which is 0. Or we can change it to 8 * 10 which is 80.
[Link]
So now the product variable equals 80. [Dividing Numbers] You can divide in
Javascript with this / symbol. So, this says 66/0. We can change this to 33. So,
now 66/33 is 2. Quotient equals 2. [Incrementing Numbers] To increment a number
means to add 1 to it. So, here we’re incrementing myVar by 1. So, it starts at 87.
[Link]
87 + 1 is 88. There is a quicker way to increment a number. Instead of doing this,
we can just myVar++. myVar++. And now we have incremented myVar from 87 to 88.
[Decrement Numbers] We learned about incrementing a number with ++. You can also
decrement a number with --. That means subtracting one. So, right now, myVar is
going to equal 10.
[Link]
11-1 = 10. We can do the same thing with the -- operator. So, now, myVar still
equals 10. [Decimal Numbers] We can also create decimal numbers with Javascript.
These are sometimes referred to as floating point numbers or floats. You can see
this is one here – 5,700. It can be anything. I’m going to make one called
myDecimal.
[Link]
And then I’m going to store a 0,00009. Anything that has a decimal point in it, is
a decimal point number. [Multiply Decimals] Multiplying decimal point or floating
point numbers is the same as multiplying integers. So, we have 2,000 times 0,000.
If I just change this to 2,500, now the answer to product is going to be 5.
[Link]
And I can [Link] that so you can see. If I just put (product). And then if we
do the browser here, you’ll see that the answer is five. [Divide Decimals] You can
also divide decimal point numbers. So, in this case I’m going to change this to
4,400. So, now the answer to quotient is 2,200. Quotient equals 2,200.
[Link]
[Finding a Remainder] The remainder operator looks like a %. And it gives the
remainder of the division of two numbers. So, for instance, if I want to find out
the remainder of 11 divided by 3, I can do remainder = 11. And then I’m going to
put the percent sign %, which is the remainder operator, 3. And 11 divided by 3 is
9.
[Link]
11-9 is 2. So, the remainder is going to be 2. 11 remainder 3 is 2. The remainder
operator is often used to determine if a number is even or odd. If you can divide
a number by 2 and the remainder is 0, that means the number is even. [Compound
Assignment with Augmented Addition] It’s common to want to add a number to a
variable like this.
[Link]
See, A = A + 12. Well, A starts at 3, plus 12 is 15. So, we're just adding 12 to
whatever A is. Here we're adding 9 to whatever B is. Here, we’re adding 7 to
whatever C is. This is such a common pattern that there’s a shortcut to do the
same thing. It’s the += operator. So, instead of A = A + 12, we can do A += 12.
[Link]
So, this equals the same thing. So, instead of B = 9 + B. We can do B += 9. So, now
we're adding the value to the variable and assigning the answer to that variable.
So, again here, we can do += 7. So, that’s just a shortcut. [Compound Assignment
with Augmented Subtraction] Previously, we learned about +=.
[Link]
Well, -= does the same thing, but subtracting. So, this says A = A - 6. We started
at 11, minus 6 is going to be 5. So, the new A is going to be 5. But we can shorten
that. Instead of A = A - 6, we can do -=. This is just a shortcut that Javascript
has that means the same thing. That means A = A - 6. But it’s shortened.
[Link]
Same here. So, we can do -= 15. C = C - 1. We can do C -= 1. So, it just subtracts
the number from the original value and then assigns that new value to the
variable. [Compound Assignment with Augmented Multiplication] Here we have A = A *
5. Well, we can do the same thing as before. We can shorten this to A *= 5.
[Link]
So, that means the same thing. Here, we can do A *= 3. And then C = C * 10. We can
shorten this to C *= 10. And that’s another shortcut for Javascript. [Compound
Assignment with Augmented Division] And there’s also a /=. So, A = A / 12. We can
do A /=12. And here, we can just do /=4. Or /= 11. So, another way of just dividing
the variable by a new number and assigning that answer to the variable.
[Link]
[Declare String Variables] We’ve already mentioned strings a little bit. But
anytime you have some characters surrounded by quotation marks, they can either
be single quotation marks, double quotation marks, or backticks. It’s a string.
These are called "String literals.” And you can create them just like you see
above.
[Link]
I’m going to do a few more. So, var myFirstName = “Beau”. And var myLastName =
“Carnes”. So, that’s how you create a string in Javascript. [Escaping Literal
Quotes in Strings] Sometimes your string contains the quote symbol. Now, normally
the quotes identify the beginning and the ending of the string. But what if you
assign like this? “I am a ‘double quoted’ string inside ‘double quotes.
[Link]
’” I’m actually trying to use these quotes right inside the string, but the
Javascript doesn’t know what to do about it. It thinks that this is the whole
string. When it sees the first quote inside the string, it thinks we're at the end
of the string. So, there’s something called an escape character.
[Link]
So, if you want to escape a quote, that means it will no longer be considered the
end of the string. I’m going to put a \. So, if I put a \ before each of these
quotation marks, Javascript no longer interprets as being the last character in
the string. So, now you can see this is a full string. And then if I log this count
console.
[Link]
log and I put (myStr), you’ll see that it’s not going to show the quotation
marks. So, I mean it’s not going to show the / and the \. It shows the quotation
marks without the \ because when we put \” Javascript knows that this should just
mean a quotation mark. [Quoting Strings with Single Quotes] We talked about
escaping a quote character like this, where you put a \ before the quote character
so Javascript knows that this is supposed to be a literal quote character inside
the string.
[Link]
However, you’re not going to have to escape quote characters very often because
there are other methods of accomplishing the same thing of having a quote
character within a string. So, a common way is to use – instead of having your
string start with double quotes, have it start with a single quote.
[Link]
So, a string can either be surrounded by ‘single quotes’ or “double quotes”. So,
this time we're just going to have ‘single quotes’. And now I can remove all of
these escape characters from inside the string here. Okay, so now you can see that
Javascript still knows that this is a string, even though it has these double
quotes inside.
[Link]
An additional thing you can do is use backticks. So, if I put backticks before – at
the beginning and the end of the string, now I actually can use single quotes
and double quotes both within the string. But right now, I’m just going to focus on
showing you the double quotes or the single quotes with the “double quotes”
inside.
[Link]
[Escape Sequences in Strings] We talked about escaping a double quote character by
using the \ before the double quote. There’s actually quite a few other things you
can escape out. You can escape out a single quote character. You can escape out a
backslash. In fact, anytime you’re going to use a \, you’re going to have to put
two backslashes so the Javascript knows that you’re not trying to escape a
character.
[Link]
You can also add a new line character, or a carriage return, a tab, a backspace,
or a form feed, all with doing a slash and the corresponding letter here. So, let
me show you an example. I’m going to put a var myString = and we're going to make
a multiline string. So, we're going to have the “FirstLine.
[Link]
” And now, I’m going to put \n to add a second line. And then I’m going to put a
tab. So, \t for the tab. And \\ to add a \. Now, it’s going to say SecondLine. Now,
I’ll do a \ and then I’ll just say ThirdLine. And if I were able to logout all of
that, you would see three different lines. And you would see the tab and then the
backslash character.
[Link]
[Concatenating Strings with Plus Operator] You can concatenate strings with the +
operator. You can see here that we have two strings. “I come first” and “I come
second”. They’ve been added together or concatenated with this. So, the ourStr,
our string, is now one long string that says "I come first.
[Link]
I come second”. I’ll give you another example here. So, we can say, myStr = “This
is the start.” And then I’m going to put a space before the end quotation mark
because when these get concatenated together we want there to be a space between
these two sentences. And I’ll say "This is the end.” Now let’s just see what that
looks like.
[Link]
I’ll do a [Link]. And do a (myStr) and let’s see. If I run this, we can see
“This is the start. This is the end.” Just one long string. [Concatenating Strings
with Plus Equals Operator] You can also concatenate strings using the += operator.
You can see here in this example we have the ourStr = “I come first”.
[Link]
And then we have the ourString += “I come second.” So, remember, just like when
you’re using numbers, += means that you take whatever is on the end here and add
it to the variable. So, we’ve just added "I come second.” onto the end of “I come
first.” Let’s do another example down here. myStr = “This is the first sentence.
[Link]
” And then I’ll put a space at the end because we're going to do a, myStr – and
here I’ll do the += “This is the second sentence.” Now, if I just do a [Link]
here of (myStr) we should see that those sentences have gone together. “This is
the first sentence. This is the second sentence.” Good. [Constructing Strings with
Variables] You can concatenate strings together with variables.
[Link]
You can see here ourName = “freeCodeCamp”;. “Hello, our name is “ and then we add
this variable, the ourName variable which is freeCodeCamp. “Hello, our name is
freeCodeCamp. How are you?” Well, we're going to do the same thing down here. So,
I’m going to do myName = “Beau”;. And then myStr is going to equal “My name is “
And then I’m going to add the variable name which is my name.
[Link]
And then I’ll continue the string here. That’s supposed to be a + here. “ and I am
well!” See that I put a space here and here because you have to make sure you put
appropriate spaces in. And let’s see what that looks like. I’ll do a [Link].
I’ll just put (myStr) here. If I show that "My name is Beau and I am well!” Looks
good.
[Link]
[Appending Variables to Strings] You can append variables to strings with this +=
operator. You can see where this variable anAdjective which is set to the word
“awesome”. And then we have another variable "freeCodeCamp is “. And then we have
the ourStr variable += anAdjective. So, now our string is going to equal
“freeCodeCame is awesome!”.
[Link]
So, let me show you another example. We're going to say someAdjective =
“worthwhile”. And now, I’m going to use the +=, so myStr += and then I can put
someAdjective. So, now after we do the myStr += someAdjective, myStr is going to
say “Learning to code is worthwhile.” [Find Length of String] Sometimes you want to
find the length of a string.
[Link]
Javascript makes this easy. So, we have the firstName is set to “Ada”. But we just
use the .length property to find the length. So, [Link]. Remember,
firsName is “Ada” here. And then .length will return an integer, a number that has
the number of characters in the string. So, that will be three.
[Link]
So, let’s try this again. Here’s another example. lastNameLength = lastName. We
just have to type in .length. And just to show you, let me [Link] that and
you'll be able to see if I put in (lastNameLength) and if I run that you'll see 8
because there are 8 characters in the word “Lovelace”.
[Link]
[Bracket Notation to Find First Character in String] Bracket notation is a way to
get a character at a specific index within a string. So, you can see right here,
we have the firstName = “Ada”. And right here we the have firstName. And then
here’s the bracket notation. You can see there’s brackets with a number inside.
[Link]
So, most modern programming languages like Javascript don’t start counting at 1
like humans do. They start at 0 which is called "Zero-based Indexing.” So, with the
number 0, that refers to first index of the string which would be the A. So, the A
would be 0. D = 1. And then A = 2. So, this first letter of firstName, if we do
firstName with the bracket notation with a zero, that’s going to = A.
[Link]
So, let me show you another example. Let’s say we want to get the first letter of
the last name. Again, I’m just going to do the bracket notation and put a zero
here. If I wanted the second letter, the O, I would put a 1 here. So, if I
[Link] we can see what it came up with. So, [Link].
(firstLetterOfLastName).
[Link]
And if we look in the console "L” because the first letter of the last name is L.
[String Immutability] Strings are immutable, meaning they cannot be altered once
created. This does not mean that they cannot be changed, just that the individual
characters of a string literal cannot be changed. So, look at this example.
[Link]
myStr and then we're going to use bracket notation to choose the first letter. So,
it currently says "Jello World”. We want the first letter to change to an H to say
“Hello World”. But if I run that, there’s going to be an error because of the
immutability of strings. Now, we can still change this to “Hello World” but we
can’t just change an individual letter like that.
[Link]
So, we're going to have to do myStr = and I’m just going to have to type in the
whole thing which is “Hello World”. And now, it will change to the word “Hello
World.” [Bracket Notation to Find Nth Character in String] You can use bracket
notation to get any character position in a string. So, earlier we did the first
position, but here’s how you get the second position.
[Link]
Remember, the 0 index. So, [1] is the second position. [0] is the first position.
We can also get the third letter of the last name using the brackets. We’ll just
put [2] in the brackets to get the third letter of the last name. [Bracket
Notation to Find Last Character in String] You can also use bracket notation to
find the last letter in a string even if you don’t know how many letters are in
the string.
[Link]
You do it based on the length. So, if you look really here, in the brackets we
have an expression to be evaluated. [[Link]-1]. So, the length is 3. 3-1
is 2. The reason why we’re doing a -1 is because remember we count starting at 0.
So .length-1 is going to be the last index of the name. So, you can do that same
thing here to get the last letter of the last name, I can just do
lastName[[Link] - 1].
[Link]
And that’s going to get the last letter of the last name which is the E right
here. [Bracket Notation to Find Nth-to-Last Character in String] We saw how to use
bracket notation to get the last letter of a string. You can also do the third to
last letter or fourth to last letter. So, you just subtract however much you want
from the length of the string.
[Link]
So, we have the bracket notation, [[Link] - 3]. That’s going to get the
third to last letter. So, we want the second to last letter. Into this variable
here we do something similar. We just do [[Link]]. And then we're going to
subtract 2 to get the second to last character of the string.
[Link]
[Word Blanks] We’re going to use our knowledge of strings to build a Mad Libs
style word game. In a Mad Lib game you are provided sentences with some missing
words like nouns, verbs, adjectives, and adverbs. And then you fill in the missing
pieces with words of your choice to make a sentence that could be funny and
hopefully makes a little bit of sense.
[Link]
So, let me show you how you do this. This also uses a function. Now, we haven’t
talked about functions yet. I’m going to explain those more later. But for now just
go with it because that’s not the point of this lesson for now. But this function
called wordBlanks, you can call the function and you have to pass in certain
types of words.
[Link]
You pass in a noun, an adjective, a verb, and an adverb. So, down here, you can
see that we're calling the function called wordBlanks. That’s the function name
here. And we're passing in a noun, an adjective, a verb, and an adverb. So, the
point is that we are going to use all these words that are passed in to make a
sentence.
[Link]
So, we know that var result = an empty string at first. And then we have to use all
these words in result. And then the result is going to be returned from this
function. And eventually, it’ll be logged out onto this screen with this
[Link]. So, what I’m going to do here is do result +=. We're going to use the
+= to add something to this result using all the noun, the adjective, the verb,
and the adverb.
[Link]
So, let’s see. It’s going to say “The “ and then we'll use the adjective
myAdjective. In this case, the big. The big and then let’s put the noun. myNoun
because adjectives are words that describe nouns. The big dog. And then we're
going to say what this now is doing – the verb. myVerb. The big dog ran.
[Link]
And then where does he run to? “to the store ”. And then we're going to add – oh,
we need a space here. So, there’s a space between “ to the store “. And then we're
going to add the final adverb. So, now, we have to add a period. And there’s one
more thing we have to add, or a few more things. So, right now myAdjective,
myNoun, myVerb.
[Link]
And there’s no spaces in between those. So, if I run that you can see what that’s
going to look like in the console. It just said, with no spaces. So, we're going
to have to add some spaces in here also. Let’s do that. And now, it’s going to
take in the noun, adjective, verb, and adverb and then put it into that sentence.
[Link]
So, one cool thing is we can actually pass in some different words. So, like for
instance, if I copy this, I’m going to paste it. Instead of “dog” I will put for
the noun “bike”. And an adjective I’ll put “slow”. And then for the verb, I’ll put
“flew”. And the adverb I’ll put “slowly”. And now if we look in the console we
have two sentences.
[Link]
The big dog ran to the store quickly. The slow bike flew to the store slowly.
[Store Multiple Values with Arrays] Arrays allow you to store several pieces of
data in one place. So, look at this example, ourArray. Now, arrays always start
with a bracket and then end with a bracket to show the beginning and ending of
the array.
[Link]
And every element in the array is separated by a comma. So, you can see here the
first element is a string. The second element is a number. And you can have more
and more elements. You just put comma and you can keep adding elements. And the
elements can be any data type. You can see here we have a string and a number, but
you can also use arrays or floating numbers or really any sort of data type in
your array.
[Link]
So, lets see another example. So, let’s do myArray = [“Quincy”]. And then for a
number we’ll do 1 because Quincy is number 1. [Nested Arrays] When one of the
elements in an array is another array, that’s called a nested array or a
multidimensional array. You can see here’s the beginning of the array and here’s
the end of the array.
[Link]
But the first element in this array is another array with two elements of its own.
Same with here. The second element is an array. So, this is two arrays within
another array. So, we can do that here. Here’s another example. So, let’s our first
element in the array will be an array with a string and a number.
[Link]
And then I’ll put a comma to put the second element of the array which will be
another array with a string and a number. [Accesses Array Data with Indexes]
Earlier we learned how to use bracket notation to find a specific index in a
string. You can do the same thing with arrays. So, look at this array, ourArray.
[Link]
We have three elements. [50, 60, 70]. And these have the indexes [0, 1, 2]. So,
with this ourArray with the bracket notation and the [0], that’s going to be index
1, which is going to equal 50. So, we can do the same thing here. myArray = [50,
60, 70]. So, let’s try to find the first element in that array.
[Link]
So, var myData = myArray. And then I’m going to do index [0]. I can do index [1],
index [2]. And then if we [Link] that, we can see for sure what that is. So,
if I put (myData) and we can see in the console it’s 50. [Modify Array Data With
Indexes] You can use array indexes to modify arrays. Now, we tried to do this
earlier with strings using bracket notation and we were not able to modify a
string using bracket notation.
[Link]
But with arrays, you can. So, the original array is [18, 64, 99]. And then we're
going to use the array index of [1]. Now, [1] is going to be the second number.
Remember, [0, 1, 2]. And this number 64 is going to be set to 45. So, the new array
is going to be [18, 45, 99]. Let’s try it again with this, [18, 64, 99].
[Link]
So, let’s do myArray and then instead of doing the second digit, I’m going to do
the first digit in then array, the first index which would be index [0]. And I
will say = 45. So, now this array has been updated. So, if I do a [Link] and
then do (myArray], we'll see that the array is now [45, 64, 99].
[Link]
[Access Multi-Dimensional Arrays With Indexes] You can also use bracket notation to
select an element in a multi-dimensional or array of arrays. So, you can see this
array here, we have our outer array. But inside that array are more arrays. The
elements of the array are other arrays. And the last element of the array actually
has an array in this.
[Link]
So, this is a three-layer deep array right here. So, to access an array of arrays
or an element within an array that’s within an array, you use a double bracket
notation. So, if you see this example here, myArray, the first bracket is [0].
That’s going to get the first element in the array which will be right here.
[Link]
And then that element is an array. So, the second bracket would be the index of
the array within the array. So, this zero would point to here. So, let’s try to
figure out how we can select a value equal to 8. Well, let’s see. I see an 8 right
here. So, let’s figure out what this first number should be. Well, let's count.
[Link]
Zero, one, two. So, the third array would be index [2]. Now, we want to go zero,
one – now we have to do index [1] to get the second number in the third array. So,
let’s test to see if that equals 8. So, I’ll do a [Link] and then do (myData)
here. And we'll see if that equals 8. And it does. We did it.
[Link]
[Manipulate Arrays with push()] You can have pinned data to the end of an array
with the push function. So, see, an array has been set up here, ourArray.
[“Stimpson” "J” "cat”] And then we take ourArray right here and use the push
function to push into the next element in the array another array here.
[Link]
So, now it’s going to look like this. We can see at the end of the original array,
we’ve pushed this other array at the end. So, let’s try it again down here. We have
myArray. And you can see we have each element in the array is another array. So, I
am going to do [Link](). And then I can push something on the end here which
will be like above, another array.
[Link]
So, this is going to say [“dog”, 3]. And now we've pushed this onto the array.
[Manipulate Arrays with pop()] We can remove an item from an array with the pop()
function here. So, see this pop() here? And then we know it’s a function because
of the parenthesis at the end of the word pop. So, the array starts with [1,2,3].
[Link]
So, now we do this -- [Link]() and it’s going to remove the last element
which is the 3 and then it’s going to put it right into this variable here. So,
now as you can see down here, removedFromOurArray now equals 3. And then ourArray
is going to equal [1,2] because the 3 has been popped off.
[Link]
So, we can do the same thing here. So, removedFromMyArray = [Link]() and we
can see what the array is going to equal now if I just do a [Link](myArray).
And if you do this, we can see that the array only has the one item, the one array
instead of the two arrays. [Manipulate Arrays with shift()] The shift function is
very similar to the pop function except it removes the first element of the array
instead of the final element.
[Link]
So, we see the shift function on the end of the array here. And the array is the
same as before. But now the first element “Stimpson” is being removed. After we
shift off the first element the array is going to equal “J” "cat”. And the
removedFromOurArray is going to equal “Stimpson”. So, let’s do another example
down here.
[Link]
We're going to do a shift() again. So, I’m going to do = [Link](). And now
myArray is just going to equal [“Dog”, 3]. And the removedFromMyArray is going to
equal [“John”, 23]. [Manipulate Arrays with unshift()] The unshift() function is
similar to the push() array function. While push() adds an element to the end of
the array, unshift() adds at element to the beginning of the array.
[Link]
So, let’s look through this example code. We have the array – [“Stimpson” "J”
"cat”]. We're going to shift off the first element, remove the first element. So
ourArray is [“J” "cat”]. Now, we're going to unshift() or add an element at the
beginning which is the string “Happy”. So, the array will now be [“Happy” "J”
"cat”].
[Link]
So, let’s try again. This time the array is [[“John”, 23], [“dog”, 3]]. Because of
the shift, we’ve shifted off the [“John”, 23]. And now I’m going to unshift()
something. So, I’ll do [Link](). Now we're going to add something to the
beginning of the array. We’ll do ([“Paul”, 35]). So, now the array is just going to
be [[“Paul”, 35], [“dog”, 3]].
[Link]
[Shopping List] Let me give you another example of nested arrays. This will be a
shopping list. So, inside this array we're going to have another array. And we're
going to have items. Cereal – how many boxes? 3 boxes. We also need some milk.
Let’s get two cartons of milk. Let’s get some bananas. Three bunches of three
bananas.
[Link]
We'll also get some juice. Two containers of juice. And finally, we will get some
eggs. We'll get 12 eggs. And now we've created an array of arrays which is our
shopping list. [Write Reusable Code with functions] Functions allow us to create
reusable code in Javascript. This is how a function is set up.
[Link]
We have the word function. Then we have the function name. There’s always
parenthesis here. And you can pass information into the parenthesis. We'll talk
about that later. And then we have these curly brackets. So, this is the opening
curly bracket {. And then we have the closing curly bracket }. And everything
inside the curly bracket is run anytime the function is called or invoked.
[Link]
So, here the function is being called by just putting the function name with
parenthesis after the name. So, every time this function is called, just like this,
the console is going to say "Heyya, World”. So, if we load the console right now
you can see it says "Heyya, World”. And if I just copy this and paste it a few
times we'll see that it’s going to say "Heyya, World.
[Link]
Heyya, World. Heyya, World” in the console. Since we have run the function three
times, we see the words “Heyya, World” three times. So now I’m going to create my
own function that’s going to be very similar. So, we'll do function reusable
function(). And this time it’s going to say something slightly different.
[Link]
It’s going to say “Hi world” instead of “Heyya, World.” And now I can call the
function down here, just like this – reusableFunction. Oh, forgot to put the
parenthesis. That’s important. Now you see "Heyya, World” and “Hi World” in the
console. [Passing Values to Functions with Arguments] Parameters are variables
that act as place holders for the values that are to be input to a function when
it is called.
[Link]
So, we have defined a function right here called ourFunctionWithargs. And inside
the parenthesis we see the letters (a, b). Now, these could be any name. We could
call these anything, not just (a,b). They can really be any words up here. And that
means that when this function is called we're going to pass data into the
function.
[Link]
Or input data into the function. So, you can see the example here where we're
calling the function. And instead of saying, (a,b) in the parenthesis, we're
actually passing the values (10, 5). So, when the function runs, it can use the
information that’s passed into the function. So, in this case it says
[Link](a-b).
[Link]
Well, that’s going to be 10-5 because the numbers 10 and 5 have been passed into
the function. And that’s going to output 5. So, I’m going to create a function
that’s very similar to that that function. This one is going to be called
functionWithArgs. And it’s also going to accept an (a, b), but we could call it
anything we want.
[Link]
And inside instead of subtracting a-b, we're going to do (a+b). Now, I’m just
going to call this function functionWithArgs and I’ll pass in (10, 5) and let’s
see what that looks like in the console. So, first it outputted 5 for this one. And
then it output 10 for this one. [Global Scope and Functions] Scope refers to the
visibility of variables.
[Link]
Variables which are defined outside of a function block have global scope. Global
scope means they can be seen everywhere in your Javascript code. For instance, I’m
going to declare a variable right here called myGlobal. I’ll set it to 10. Now
since this is set outside of a function, we can see it anywhere in the whole code.
[Link]
Even in this function right here called fun2. We can see that we reference it here
and here. And we're going to be able to see it. Now, this is an if statement. Which
we will talk more about later. But we're checking if the type of myGlobal does not
equal “undefined”. So, it will not equal “undefined” if it has been defined and
the program knows about the variable.
[Link]
Since this is global scope, it does not equal undefined. It equals 10. The program
knows about the variable because this is in global scope. So, since this function
can access the myGlobal variable, it will run what’s in this if statement where
we just add to this output variable, myGlobal. And then we put the value of
myGlobal which is 10.
[Link]
Now, here’s another example where we're going to see if the type of oopsGlobal
equal “undefined”. Well, we're going to set that here. So, it is possible to set a
variable without using the var keyword. So, I’m going to set this to oopsGlobal =
5. So, you can see here that there is no var keyword.
[Link]
So, normally if you do use a var keyword, since this is within a function, it will
be scoped to that function. If we have the var keyword here, this would be scoped
to this function so you would not be able to see it in this function. However,
since we forgot to put the var keyword in this example, there’s no var keyword,
it becomes global automatically.
[Link]
That means you can access it anywhere else in the program including here. So, if
we put the var keyword, then oopsGlobal would equal “undefined”. And then we would
never have this line in the output. However, since we did not put the var keyword,
oopsGlobal = 5 and this will be added to the output – oopsGlobal and then the
colon 5.
[Link]
So, when we [Link] the output it’s going to say myGlobal 10, oopsGlobal 5.
Now actually it’s not going to say that because this is in Scrimba. And in Scrimba
it’s more careful and just enforces the fact that you have to use a var keyword.
But if we were in our browser it would not enforce the var keyword.
[Link]
And then it would actually show myGlobal 10, oopsGlobal 5. If this was a little
complicated, don’t worry about that because a lot of these concepts we’ll be
going over again later with additional examples. [Local Scope and Functions]
Variables which are declared within a function as well as the function parameters
have local scope.
[Link]
That means they’re only visible from within the function. Let me show you what I
mean. If I declare a variable right here, myVar = 5. So, we've declared this
variable inside a function. So, this variable, myVar is only visible inside the
function. So, it says [Link](myVar). It should [Link] the 5.
[Link]
So, we're going to call the function here. And it’s going to [Link] myVar. But
then the program is going to run this [Link] that’s outside of the function.
It’s still going to try to access myVar. And so, let’s see what happens. You can
see in the console that first there’s a 5 because it console.
[Link]
log within the function, then there’s an error because it tried to access myVar
outside of the function. So, really, we just need to delete this where we try to
access the variable outside of the function. And now there is no error. [Global vs
Local Scope in Functions] It is possible to have both local and global variables
with the same name.
[Link]
When you do this, the local variable takes precedent over the global variable. Let
me show you an example. Here we have a function called myOutfit that’s going to
return outerWear. That’s this variable up here. This is a global variable because
it is declared outside of the function. So, when we console.
[Link]
log the output of the myOutfit function, the myOutfit function is going to return
outerWear which is the word “T-Shirt”. So, let’s just check the console and you
can see, yep "T-Shirt” is there. However, let’s change this up a bit. So, you have
some space here because I’m going to put var outerWear = “sweater”. So, now if I
run this program you can see in the console it’s going to say “sweater” instead
of “T-Shirt”.
[Link]
It’s because this local variable outerWear took precedence over the global
variable. Another interesting thing about this, if I do a [Link]. And I
[Link] the outerWear variable, we'll see that it’s still “T-Shirt.” So, first
you see in the console it says sweater and T-Shirt. So, first we [Link] this
function which is sweater – it returns sweater.
[Link]
And then we [Link] the global variable which is T-Shirt. [Return a Value from
a Function with Return] You can return a value from a function with this return
statement. So, we have this function here. And we’re passing a number into it – the
num. And then it’s going to return whatever is after the return keyword.
[Link]
In this case, num-7. So, here we're going to [Link] the function. And it
returns the result of -7, is this 10-7, which is 3. So, it’s going to [Link]
the number 3. If we look in the console, yep, it [Link] the number 3 because
the function returns 3. Let’s try creating another one. This function is going to
be called timesFive.
[Link]
Again, we'll pass in a number. And it’s just going to return something. It’s going
to return the num * 5. And then just like before, we can test it using a
[Link] (timesFive) and we'll pass in the number 5 here. And if I run this,
we'll see that it retuns the number 25. [Understanding Undefined Value Returned
from a Function] Functions can have return statements, but they don’t have to.
[Link]
In this case, this function adds 3 to the sum variable which is a global variable
because it’s defined before the function. It does not return anything. So, if you
don’t specify a return value, the return value is just undefined. Now I’m going to
create another function that is similar. This is going to be called addFive().
[Link]
And this time we'll just do sum = sum+5. Or we can shorten this to use the +=. So
now that’s going to add five to the sum also, but it’s not going to return
anything. So, if we log this out, it would be undefined. [Assignment with a
Returned Value] It’s simple to assign a returned value to a variable.
[Link]
See right here we have the function change. And you pass in a number and it’s going
to return the result of this mathematical expression. So, when we call the
function change and pass in the 10, the value that is returned from this function
is going to be stored in this variable here. We can do the same thing down here.
[Link]
First we initialize the variable processed and processedArg. It’s going to return
the result of this mathematical expression. So, I can set processed to equal what
this function returns. So, I can say processedArg. And then I’ll just pass in the
number 7 here. And now processed equals the result of this mathematical
expression.
[Link]
[Stand in Line] In computer science a cue is an abstract data structure where
items are kept in order. New items can be added to the back of the cue and old
items are taken off from the front of the cue. We're going to simulate that right
now, some of the functionality of a cue using this nextInLine function.
[Link]
So, the purpose of this is to show that in this nextInLine function you can add
an item to the array that’s passed in. And then it’s going to return the first item
on the list. For instance, if we have this array right here, if we add an item to
this array it should come after at the end. So, it should come after 5.
[Link]
And then it should return the first item on the list. In this case, it’s 1. So, you
see, we had some [Link] set up. So, it should show what the list looks like,
the array looks like beforehand. And then show what it looks like afterwards. This
JSON.
[Link]
stringify is just a way to change an array into a string that can easily be
printed out to the screen. So, to do this, we're just going to have to do two
things that we've learned about already. So, the first thing is to add the item
onto the list. So, we see right here, nextInLine passed in the testArr and 6. So,
we're calling this function nextInLine.
[Link]
We're passing in this testArr here. And the number 6. We want the number 6 to be
added to the end of the array. So, we'll just do [Link](). And then I’ll put in
(num). Just like that. Oh, actually, it’s (item). So, what we did, we took this
array that was passed in here which is in this case, testArr.
[Link]
And we push the time that was passed in. And in this case here, it’s item 6. Now we
want to return the first item on the list. We want to remove and return this item.
So, that we [Link] here it should show the number 1. So, instead of returning
item, I’m going to return [Link](). That’s what shift does.
[Link]
Shift moves the first item and returns that first item. So, let’s check this out.
Okay, you can see before, [1,2,3,4,5]. Then we've popped off the 1 and after it is
[2,3,4,5,6]. We did it. [Boolean Values] Booleans are another datatype in
Javascript. There are only two values, true or false. They’re basically little
on/off switches where true is on and false is off.
[Link]
They don’t use quotation marks around the Boolean. See, it just says return false.
So, this is a function here. It should be indented, where it’s going to return
false when you call this function. It could also be true. So, we could return true.
You can use true and false in more places than just function returns and we'll be
talking more about that later.
[Link]
[Use Conditional Logic with If Statements] An if statement is used to make
decisions in code. The keyword If tells Javascript to execute the code in the
curly braces under certain conditions defined in the parenthesis. So, here is a
full if statement right here. And there’s always parenthesis after the keyword if.
[Link]
And here’s the condition. So, if the stuff inside these parenthesis evaluates to
true, then the code within these curly braces will be evaluated or run. So, in
this case, it’s a variable. So, if the isItTrue variable is true, it will return
“Yes, it’s true”. Now if this is not true, then we'll get to the second return
statement "No, it’s false”.
[Link]
So, this whole function here takes in a variable. And we check if that’s true or
not. So, I’m going to make another example just like this. We have another function
that hasn’t been filled out yet, trueOrFalse. And there’s a variable that’s passed
in (wasThatTrue). So, we'll say if – and then the parenthesis (wasThatTrue).
[Link]
If that’s true, we're going to return something. It will be a string just like
before. And the string is "Yes, that was true”. If it’s not true, then we'll get to
the second return statement in the function. And we'll return a different string.
We'll return “No, that was false”. I’ll just add some semicolons, and then I can
run this.
[Link]
And we'll see what happens. Oh, return needs to be spelled correctly. So, let me
spell return correctly. So, before I run this, I’m going to add a [Link]. So
we can [Link] the answer. So, this is the function call here, true or false.
We’re passing in true. And then we're going to log what is returned here.
[Link]
“Yes, that was true”. Since we passed in true, this if statement evaluates to true
and this code is run right here. [Comparison with the Equality Operator] There are
many comparison operators in Javascript that will return a Boolean of true or
false. The most common is the equality operator. And it’s often used in an if
statement.
[Link]
So, here it just says if (val). So, we have this whole if statement right here, if
(val). We're going to see if if (val) = 12. Now, to check if it equals 12, we're
going to have to use the ==. That is the equality operator and we'll say if (val
== 12). The reason why we can’t just use a single equal sign is that a single
equal sign is the assignment operator.
[Link]
If we just had a single equal sign, that would mean that we were setting the value
of the val variable to equal 12. We're not trying to set this to equal 12, we're
trying to check if the value of this variable equals 12, so we have to use the
double equal sign. So, now, this testEqual function is going to test to see if the
number we pass in is equal to 12.
[Link]
I can do a [Link] here. [Link]. And then we can see what appears in the
console here. “Not Equal” because 10 does not equal 12. [Comparison with the Strict
Equality Operator] We learned about the equality operator which is the double
equal == sign. There’s also the strict equality operator, the triple equal sign
===.
[Link]
So, here we're checking if 3 equals 3 with the strict equality operator. So, the
difference is that the equality operator, the double equals sign attempts to
convert both values being compared to a common type while the strict equality
operator does not do the type conversion. So, this is going to evaluate to true,
the 3 === 3.
[Link]
But the 3 === ‘3’ with the string on the side is going to evaluate to false. Both
of these would be true if we were using the double equals sign == because the
string would be converted to a number and it would be equal to true. But with the
=== it does not get converted to a number, so it would be evaluated to false –
this second one with the three equal signs.
[Link]
So-and-so, here, we're just going to use it right in this if statement. And do ===
7. So, now we can pass in the number 7 and it’s going to evaluate to true. But if
we pass in a string 7, it will evaluate to false. [Practice Comparing Different
Values] We will do one more review with the equality operator and the strict
equality operator.
[Link]
So, if I run this here, we'll see in the console it says "Equal” because it’s
checking if the number 10 and the string “10” are equal. So, if a = b, the number
10 equals a strict number 10, return “Equal”. Since we're using the equality
operator with two equal signs, it performs a type conversion.
[Link]
And it converts the string into a number. But if we use the strict equality
operator with three equal signs, I’ll run that again, and you’ll see “Not Equal”
in the console because now it’s not converting the types and it’s just checking
if a number is equal to a string, which it’s not, so we get not equal.
[Link]
[Comparison with the Inequality Operator] Now I will show you the inequality
operator which is basically the opposite of the equality operator. So, I’m going
to do the inequality operator with an exclamation point and an equal sign. In this
case, I’m going to see if the value is not equal to 99. And again, just like the
equality operator, this does type conversion.
[Link]
So, let’s just run this program and we'll see it is “Not Equal” because 10 – we
passed in 10 into the function here. And 10 is not equal to 99, so we get “Not
Equal”. [Comparison with the Strict Inequality Operator] The strict inequality
operator is basically the opposite of the strict equality operator.
[Link]
Now, it works like this. So, it says if (val) – I’m going to do if (val) does not
equal 17. So, this is the strict inequality operator. Instead of one equal sign we
have two equal signs. And that means it’s going to check if this is not true. But
it’s not going to convert types. So, for instance, if we were checking if the
number 3 does not equal the string 3, that would be true.
[Link]
So, in this example, we're just checking if 10 does not equal 17. If we run this,
we will see it’s not equal. [Comparisons with the Logical And Operator] We can also
use the greater than operator. So, in this function we're checking if a value is
over 100. So, I’m going to put greater than 100. And then here we're checking if a
value is over 10, so I’ll put greater than 10.
[Link]
So, here we call the function. We pass in 10. And if I run that function, you'll
see “10 or Under” because we're not over 100. We’re not over 10. 10 or under,
because we passed in 10. [Comparison with the Greater Than Or Equal To Operator]
We can also use the greater than or equal to operator. So, we'll finish this
function by using greater than or equal to.
[Link]
It’s just a >=. And we'll put 20 down here. Just greater than or equal to 10. If I
run that, we should see “10 or Over” because we're passing in 10 and it’s greater
than or equal to 10. [Comparisons with the Less Than Operator] Now I’ll show you an
example of the less than operator. With this function, we're going to check if
the value is less than 25.
[Link]
And then up here we're checking if a value is less than 55. So, here, it’s a trick
I use to remember which symbol is less than and which symbol is more than. If you
see the less than symbol looks kind of like the letter L which is the first letter
in less than. And then the more than symbol is just the opposite.
[Link]
[Comparisons with the Less Than Or Equal To Operator] And we also have the less
than or equal to operator we can use in Javascript. So, here, we're going to check
if it’s less than or equal to 12. So, we just put the less than operator 12. Equal
– less than or equal. That’s an important part. Here it’s the less than or equal to
24 to make this statement true.
[Link]
And if we run, we see “Small Than or Equal to 12”. The number 10 we passed in.
[Comparisons with the Logical And Operator] Sometimes you want to check if 2 things
are true at the same time. For instance, you may want to check if this value is
less than or equal to 50. And you also want to check if the value is more than or
equal to 25.
[Link]
So, here we have a nested if statement. So, it’s going to check if it’s less than
equal to 50 and if it’s more than equal to 25, then it’s going to return “Yes”.
But there’s an easier way to do this. So, what I’m going to do is copy this where
it says value is more than or equal to 25, I’m going to delete this nested if
statement.
[Link]
So, we don’t need that if statement. And I’m going to use the And operator. So, we
have less than or equal to 50. And if I put two ampersands, like this, that means
and. Now, I’m going to put value is more than or equal to 25. So, this says if
value is less than or equal to 50 and the value is also more than or equal 25,
then we're going to return “Yes.
[Link]
” So, both this statement and this statement have to be true to get inside this
if statement here. [Comparisons with the Logical Or Operator] In this code here,
we’re checking if the value is not between 10 and 20. So, if the value is less
than 10, we return “Outside”. And if the value is more than 20, we return
“Outside”.
[Link]
There is an easier way to do this with the logical Or operator. So, I’m just going
to delete this whole if statement here. And then I can add an or statement. Which
is just two pipes. So, I’m going to put val is more than 20 here. So, now, we're
checking if the value is less than 10 or if the value is more than 20.
[Link]
Either way, we're going to return “Outside”. And if it’s not true, we'll return
“Inside”. [Else Statements] When an if statement is true, normally the block of
code right after the if statement will be evaluated. And if it’s not true, nothing
happens. But with an else statement, an alternate block of code can be executed
when it’s not true.
[Link]
So, this is a perfect use case. If value is more than 5, the result is bigger than
5. If the value is less or equal to 5, the result is 5 or smaller. We can do this
with an else statement. So, I’m just going to type in else here. And then we can
just delete this whole if statement. Just like that. And now we have if the value
is less than 5.
[Link]
The result is going to be “Bigger than 5”. Else, if it’s not more than 5, we'll
return “5 or Smaller”. [Else If Statements] If you have multiple conditions that
need to be addressed, you can use else if statements. It’s a way of chaining if
statements together. In this example, we have three conditions.
[Link]
If value is more than 10, we're going to return greater than 10. If it’s less than
5, return smaller than 5, or else we're going to return 5 and up. So, this is a
perfect use case for an else if statement. So, this is how we do it. We’ll do else
and then just we're going to add the if statement at the end of the else.
[Link]
I’m just going to delete all of this stuff. So, else if value is less than 5, and
then we're going to have one final else statement. Else – and I’m going to put this
statement here. This final return. Just going to cut that. And then paste in right
in there. So now, instead of using multiple if statements, we have the if and then
we have the else if, and then we have the else.
[Link]
[Logical Order in If Else Statements] When you’re using else if statements order
is very important. Let’s look at this example here. In this function, first we
check if the value is less than 10 and return less than 10, then else if we check
if the value is less than 5, and return less than 5. Well, if we look at this
example and we pass in the number 7.
[Link]
If I run this, you’ll see it’s going to say "Less than 10” which is what we want.
However, if we put 3 it’s still just going to say “Less than 10”. Really, we want
this to say "Less than 5” because it is actually less than 5. However, this is in
the wrong order. So, what we need to do is change the order.
[Link]
So, this should be 5. This should be 5. And this should be 10. And this should be
10. So, once the first condition is met, it doesn’t even check for the rest of and
conditions. So, that’s why it’s important to think about the order. So, if we run
this now, yeah "Less than 5”. That’s what we want. [Chaining If Else Statements]
You can also chain if and else if statements.
[Link]
So, I’m going to complete the following challenge here. Write chained if/else if
statements to fulfill the following conditions. So, we have these conditions. If
the number is less than 5, we're going to return “Tiny”. If it’s less than 10,
return “Small”, and so on. So, what I’m going to do is actually just copy this
right here because this is written – part of it is written exactly how we want it
to be written.
[Link]
I’ll just paste it here. And I’m going to just add the if and else statements. So,
it’s going to be if – and then we put this in parenthesis because the condition
is always in paranthesis. If number is less than 5, then we're going to use the
curly braces and we're going to return “Tiny”. So, I’ll just move that up here.
[Link]
I’ll cut it and paste it. Now, we're going to use an else if statement. And I got
the curly braces. First of all, also I need to put the condition in these
parenthesis. I’m just going to cut this. Number is less than 10. Put it right here.
And we're going to return this “Small”. So, I’ll put that in the curly braces here.
[Link]
And then we have another else if statement. Else if and the condition. Just like
before, the number is less than 15. Put that in there. We always need the curly
braces to show what’s going to happen in the if statement. So, I’m just cutting
and pasting this text again. We have an else if. And then we have this here.
[Link]
And we have return “Large”. Another – actually, the final thing is just going to
be else. We don’t even need an else if with this statement at the end. We don’t
even need to put the condition because if it’s more than or equal to 20 that’s
going to be everything else. So, I’m just going to cut this. We don’t need any of
this stuff here.
[Link]
And we're just going to return “Large”. So, with this one test here, for test 7,
we can actually [Link] that. [Link]. And see what it returns for 7. We
can try a few different things. Oh, we have an error here. Oh, forgot to – I put
this parenthesis the wrong way. Let’s try that again. “Small” but if this is 20, it
should be “Huge”.
[Link]
And if it’s 19, which would be less than 20, we should see “Large”. Yep, that
worked. [Golf Code] In the game of golf each hole has a par which means the
average number of strokes you’re supposed to use to get the ball into the hole.
So, depending on how far above or below par your strokes are, there’s a different
nickname.
[Link]
So, here are some of the nicknames "Hole-in-one!” “Eagle” “Birdie” “Par” and
we're going to write a function where you pass in the par and you also pass in the
strokes. You can see up here, par and strokes. And it’s going to return the
nickname. So, that’s what we're going to write. You can see this table here shows
what we have to do.
[Link]
If the strokes are 1, then you get “Hole-in-one!”. If the stroke is less than or
equal to par-2, you get an “Eagle”. And so on. And we also have this array that’s
going to make it easier because we can just use things from this array instead of
typing out the words. So, we're going to start with an if statement.
[Link]
If – and then we have to put the condition. If (strokes) == that’s the equality
operator. We don’t want to use a single equals sign because that would be the
assignment operator. If it equals 1, then we can return. And we can see down here,
we're going to return “Hole-in-one!”. But we can just use it from this names array.
[Link]
So, it’s going to be names. And this is going to be index zero of the array. So,
we'll do names and then [0]. And then we can do an else if. Else if – and then we
can put the condition, (strokes). I have to spell strokes right. Strokes. And then
we can just actually copy this right from here. Less than or equal to par-2.
[Link]
And then we are going to return name and this will be the index[1] which is an
“Eagle”. At this point, I can do some copy and pasting. I’m going to copy this
whole thing because a lot of the rest of this will be else if. So, else if strokes
is – this time it’s going to be equal to par-1. And we're going to return “Birdie”
which is array index[2].
[Link]
And I’m going to continue just like this. So, this time it’s if strokes equal par,
we're going to return name index[3]. See? Zero. One. Two. Three. It’s going to be
the word par up. Keep just like this. Now it’s going to be par+1. And we'll change
this to [4]. Now it’s going to be par+2. And we’ll change this to [5] which is
going to be the double bogie.
[Link]
And finally, if strokes is – change this to more than or equal to par+3 that
means you did very poorly so you should just go home. So, it’s going to be name
index[6]. And we don’t need this anymore. So, now we're going to do some tests
here. I’m going to do a [Link]. And we're going to pass in the function that
we're calling.
[Link]
So, in this case, the par is 5 and the strokes are 4. So, that should return
“Birdie”. Let’s see what happens. Null. Okay. That’s not what I expected. It’s
because this should be names. I spelled this wrong. That’s why it’s sometimes
better to check before you go through the whole thing. You can test things as you
go.
[Link]
But let’s do that again. Yep "Birdie”. And if I type in 2 here "Eagle”. If I type
in 8, it’s probably going to tell us to go Home. “Go Home!” Yep. We just completed
this challenge. [Switch Statements] Instead of using chained else if statements
you can use a switch statement. A switch statement tests a value and can have many
case statements which define various possible values.
[Link]
So, let me show you how that works. Here we're going to write a switch statement
which tests val and sets the answer to the following conditions. If we pass in 1,
the answer should be “alpha”. If we pass in 2, the answer should be “beta”. And so
on. So, let me show you how that works. We'll just type in the word switch.
[Link]
That’s the keyword here. And we're testing the val that’s passed into this
function. So, it starts off kind of like an if statement. And right now – so, we're
going to compare the val to the different cases that we have. So, we'll have case
and the first number is going to be 1. So, here we're saying if the case of val is
1, if val = 1 and it’s using the strict equality operator, so it’s like the ===,
it’s going to make sure that the type of the variable are the same.
[Link]
So, a string ‘1’ and a number 1 will not be equal. But if the case is 1, then we're
going to set answer to = “alpha”. And then we're going to break. Break means that
we're at the end of that case statement. And once you break it, it just goes to
the end of the switch statement and doesn’t evaluate anything else in the switch
statement So, we're also going to have case 2.
[Link]
And one thing I forgot, that we're going to indent that so it’s easier to see the
different cases. And case 2, the answer is going to equal to “beta”. And then we
also need the break statement. If you don’t have a break statement it will just run
through to the next case statement automatically. So, if the case was 1 and you did
not have a break here, first it would set the answer to “alpha”.
[Link]
And then it would set the answer to “beta”. It would just skip over to the next
case statement. The break is here. It’s going to go out of the switch statement
completely. So, it would go – start running the code after this last curly
bracket. So, now we're going to do case 3. We’ll just do some copying and pasting
here.
[Link]
And we're going to have 4 cases so I’ll just do the rest of the pasting here. So,
we’ll have 3 and 4. “alpha” “beta” and then we have “gamma” and “delta”. And we
know that the switch statement is over because we have this final curly bracket.
And then we're just going to return answer. So, let’s do some tests.
[Link]
To really test this, we're going to have to add a [Link] here to log what
it’s going to be. And I’ll run this. “Alpha” good. Now 2 should be “beta”. 3 should
be “gamma”. Good. And we'll just assume 4 is correct so we're done. [Default Option
in Switch Statements] Now we'll talk to you about the default option in a switch
statement.
[Link]
The default option is kind of like else in an if else statement. So, here’s a
switch statement that’s very similar to the one we already saw. And it’s inside
this function where we pass in a value into the function. And we're going to check
if the value equals a. If it equals a the answer is going to be sent to “apple”.
[Link]
B, answer set to “birds”. C "cat”. So, in this example we can see that we passed
in here – we passed in the a and it returned “apple” because that was one of the
options. But what if we pass in something else? If I pass in the number 2 here it’s
going to return an empty string. That’s because the answer is set to an empty
string and we never override the answer here so it just returns the empty string.
[Link]
What if we want to return something anytime a, b, or c is not passed through. So,
for anything else that’s passed into the function, we're going to do default. This
is like the else statement. So, the default, we're going to do answer = “stuff”.
Again, we're going to have the break. But now, whenever we pass in something
that’s not a, b, or c, it’s going to return “stuff”.
[Link]
So, we can pass in 5. It’s going to return “stuff”. But if I go back to passing in
c, one of the things we have a case for, it’ll return “cat”. And that’s the switch
statement. [Multiple Identical Options in Switch Statements] Sometimes you want a
switch statement where multiple inputs give the same output.
[Link]
Well, that’s easy enough by omitting the break statement. Let me show you how that
works. So, let’s get a switch statement here. And we're going to have val, that’s
what’s passed into the function. And then this case we want the case of 1, 2, and
3 all to return the answer of low. So, I can do it like this, case 1 – and I can
go straight into case 2.
[Link]
And then I can go straight into case 3. And since I don’t have any break statement
between these cases, it will just keep going to the next one automatically. And
now, I’m going to say that the answer is going to be set to equal “Low”. And here
is where I put the break statement. Okay, now we're going to do the same thing
with cases 4 through 6.
[Link]
And actually, I’m just going to do some copying and pasting. I’m going to copy all
this. And now we're going to paste. That’s 4, 5, 6. We're going to do the same
thing with 7, 8, 9. So, I’m going to do copy and paste again. And then I’m just
going to update the code. So, this is going to be 4, 5, 6.
[Link]
And we'll have 7, 8, 9. And we're going to have “Mid” and “High”. So, if the case
is 1, 2, or 3 – like for instance, if it’s 1, it’s going to pass through 2 and 3
to get low. And then it’s going to break about it. If it’s 4, 5, or 6, it’s going
to pass through to get to “Mid” and then it’s going to break out 7, 8, and 9.
[Link]
It’s going to pass through to the “High” and break out. So, let’s test this out and
see. Since we're passing in the number 1 here it’s going to be “Low”. But if we
pass in 5, we should get “Mid.” And if it’s 7, 8, or 9, we should get “High”.
[Replacing If Else Chains with Switch] Sometimes a switch statement can be easier
to write and easier to understand than a chain of if else statements.
[Link]
So, we're going to change this chain of else if statements to become a switch
statement. So, let’s do that right now. So, we're going to start with the switch
keyword and we're going to be evaluating the value with open curly bracket, and
we'll have to make sure to have an end curly bracket at the end.
[Link]
So, for a case “bob” we're going to set the answer to “Marley”. And then we need
to have a break in here. For case 42 we're going to set the answer to “The
Answer”. For case 1 we’ll set the answer to “There is no 1”. We need a break up
here. For case 99 the answer is “Missed me by this much!”.
[Link]
And then we need a break. Now we have for case 7 – 7, 8, 9, and break. And now we
just changed that chain of else if statements into a switch statement. [Returning
Boolean Values from Functions] Here’s a little trick when you want a function to
return a Boolean, a true or false value. You can see in this function, we're
checking if a is less than b.
[Link]
And if so, we return true, else we return false. You may remember from before the
all comparison operators return a Boolean true or false value. So, instead of
using this if statement here we can just – we can actually delete all of this
and just return the result of this, return – we’re just returning the result of a
is less than b.
[Link]
So, this is going to be true or false. And we can just skip that whole if statement
logic and just return this. So, if we [Link] this out, [Link], we
should be able to see if 10 is less than 15. It is less than 15. It’s true. But if
we put a 20 here then it’s false. [Returning Early Pattern from Functions] We've
already seen a few examples of this.
[Link]
But you can return early from a function with the return statement. So, if you see
this function right here, we return at the very end of the function, so it leaves
the function and returns this value from the function. But you can leave the
function any time with a return statement. So, we're going to modify this function
so that if a or b are less than 0 the function will immediately exit with the
value of “undefined”.
[Link]
So, let’s do that. We're going to set an if statement. If a is less than 0, or –
that’s two pipes. B is less than 0 then we're going to return undefined. So, we can
do a test here, [Link]. 8. But what if this is a negative number? It’s going
to return undefined. Scrimba has a little quirk here where it just shows null.
[Link]
But in a browser it will show undefined. [Counting Cards] We are going to create a
blackjack card counting function. So, how card counting works, at least how this
function is going to work, is that when you see a low card, the count goes up.
And when you see a high card, the count goes down. And if it’s a middle value
card, the count stays the same.
[Link]
And then when the count is positive, the player should bet high. And when the
count is a zero or negative, the player should bet low. So, we are going to use a
switch statement to figure out what card has been passed in and what to do about
it. You can see that the function looks like this – cc and we pass in card.
[Link]
And depending on what the card is, it’s going to increase this global count
variable or it’s going to decrease it, or it’s going to stay the same. And then
we are going to return two things. We're not going to return “Change Me”. We're
going to return the current count value and whether the player should hold or bet.
[Link]
So, every time you call the cc function it’s going to change this count value and
return the total count. So, let’s see how this is going to work. We are going to
use the switch statement, like I said. And we're going to check the card value
that was passed in. So, if the case is 2, 3, 4, 5, 6, we are going to increment
the count variable.
[Link]
So, we're going to do it like this – case 2. I’m going to do some copying and
pasting. If the case is 2, 3, 4, 5, 6, we'll just have to change these values. 3,
4, 5, 6. Now, there are many ways to write any program. This could be done with if
statements and else statements. It could be even done with other ways that we
haven’t even talked about yet.
[Link]
As long as the program works, in this case, that’s all that matters. So, if you
find a different way to write this program, that’s great. So, if the case is 2, 3,
4, 5, or 6, we are going to take the count value. And if we just do ++, it
increments it by 1. And then we're going to break. Now, if the case is 7, 8, 9 –
so let’s paste in three of these.
[Link]
We’ll do 7, 8, 9. Actually, we're going to do nothing. The count is not going to
change at all. So, we don’t even need case 7, 8, or 9. So, instead of doing 7, 8,
9, we just need to check in the case that something is actually going to happen.
So, we are going to decrement the count variable if we have 10, Jack, Queen, King,
or Ace.
[Link]
So, that’s what we're going to change this to. 10 "Jack”. “Queen”. “King”. or
“Ace”. In this case, we're going to decrement the count. So, we're going to do
count --. So, that’s the same as count = count -1. And then we will break. Now
we've taken care of the count and updating the count, now we have to take care of
what we're going to return.
[Link]
We are going to return the count. And we're also going to return whether we are
going to hold or bet. So, we're going to actually return a variable. But first
there’s going to be a space. There’s a space between the number and then we're
going to return the hold variable. Now, this is a variable we haven’t created yet.
[Link]
Normally, this would be the perfect time to use the turn area operator, but we
haven’t learn that yet and we're not going to learn that for a few more lessons
so I won’t use that now. We are going to set what that hold bet value is. First,
we’ll create the holdbet variable. Variable holdbet. And we’ll set it to ‘Hold’.
[Link]
However, if (count) is more than 0, then we can set holdbet to equal ‘Bet’. So,
now this should work. Let’s test it out and see if we’ve made any mistakes yet.
holtbet is not defined. We have it right here. Oh, we spelled that wrong. So,
instead of holtbet that should be holdbet. Okay. In this case, we're going to bet
because we had a bunch of positive numbers and then negative numbers.
[Link]
But if we change this to ‘K’ and we change this to 10, let’s see what happens. Now
we're going to hold. Okay, it worked. [Build Javascript Objects] Objects! Objects
are similar to arrays except that instead of using indexes to access data, you
use properties. So, here’s an object called ourDog. Objects are going to be defined
with these curly braces at the beginning and the end.
[Link]
And these are the properties. Now, the properties are everything before the colons.
So, we have “name” that’s a property. “legs” is a property. And then the values are
the things after the colons here. So, the name is “Camper”. The legs, 4. Tails,
there’s only one tail on this dog. And “friends” are “everything”.
[Link]
Now you can see that the properties can be strings. They can be numbers. They can
be arrays. They can be any datatype in Javascript. So, now we are going to create
our own dog. So, this is going to have a “name”. Personally, I like the name
“Quincy”. So, we'll use that for our dog’s name. Also, we're going to have “legs”.
[Link]
Unfortunately, our dog has had an accident. He only has 3 legs. But to make up for
only having three legs, he does have 2 tails. And for “friends”, another
unfortunate thing, it’s an empty array. He has no friends. Okay. We’ve now created
our own object. [Accessing Object Properties with Dot Notation] There are two main
ways to access a property on an object.
[Link]
The first I will talk about is dot notation. So, we have this testObj. And we have
“hat” “shirt” and “shoes”. And we want to find out the value of these properties.
So, right here the hatvalue we're going to set to testObj. Now here’s where we use
the dot notation. We just put a dot or a period and then I put the name of the
property, .hat.
[Link]
And then for the shirt value, I will do .shirt. So, see this word right here is
just a word here. So, the value of hatValue, [Link] is now going to be
“ballcap”. And the value of the shirtValue is going to be “jersey” [Accessing
Object Properties with Bracket Notation] Besides using dot notation you can also
use bracket notation to access a property in an object.
[Link]
You can use bracket notation anytime but it is required if the name has a space in
it. You can see in this object we have three properties. And each of them have a
space. So, to get the value of these properties we're going to have to these
bracket notation. So, the entreeValue we're going to do testObj.
[Link]
That’s the name of the object. And then we're going to put brackets kind of like
an array index. So, you need the opening and closing brackets. And inside we will
put the name of the property. So, I’ll do “an entree”. And then we can do it again
down here for the drink value. I’ll use a single quote this time instead of a
double quote to show that each of those will work.
[Link]
‘the drink’. And then we need the closing brackets here. So now, entreeValue is set
to equal hamburger. And drinkValue is set to equal “water”. [Accessing Object
Properties with Variables] Bracket notation can also be used to look up object
properties using variables. So, here we have this testObj. We have these different
numbers associated with these names here.
[Link]
And we are going to set this variable to be one of the numbers. So, I’ll set this
to be 16. So, now we can – in this testObj, 16 is “Montana”. And we can look that
up using the variable name instead of the number. So, instead of putting 16, I’m
going to put [playerNumber] in here. And now player is set to the word, the
string "Montana”.
[Link]
And we use these variable to look up the object property. [Updating Object
Properties] We can use dot notation to update object properties. Here you can see
an object called ourDog. It has a name, legs, tails, friends. And the name is
“Camper”. However, here we used dot notation [Link]. And use the assignment
operator, the equals sign, to set the name to “Happy Camper”.
[Link]
So, if we do [Link] on [Link] it would no longer be “Camper” it would
be “Happy Camper”. Well, we have another dog here with the name of “Coder”. But we
want to change the name to “Happy Coder”. So, that’s what I’ll do right here. So,
[Link] = “Happy Coder”. So, just like above, we use dot notation to set the
object property to a new value.
[Link]
[Add New Properties to an Object] You can add new properties to an object using
dot notation or bracket notation. So, here’s an example right here. We have this
object, ourDog. And there’s four properties here. But down here we're adding a new
property. [Link] = “bow-wow”. So, it had four properties but now it has 5
properties as the property bark as well.
[Link]
Now down here we'll add a property to the myDog object. So, we can do myDog. And
then here I’m going to use bracket notation instead of dot notation. ‘bark’. I’m
going to set that to equal “woof”. And because he’s yelling it we’ll have an
exclamation point. And that’s how you add properties to objects.
[Link]
[Delete Properties From an Object] It’s simple to delete a property from an object.
Our ourDog object has all these properties. And with the delete keyword, delete
[Link]. So, now this property here, the bark, has been deleted and is no
longer in the object after we’ve deleted it. So, we can do the same thing down
here.
[Link]
And this time we will delete the tails property [Link]. So, now the myDog
object no longer has a tails property. [Using Objects for Lookups] Objects can be
thought of as a key value storage like a dictionary. You can use an object too
lookup values. So, in this case we have a switch statement that returns certain
values.
[Link]
So, when you pass in “alpha” to the function it returns “Adams”. If you pass in
“bravo” it returns “Boston”. We can replace this switch statement with an object
and use the object for lookups instead of the switch statement. Let me show you
how that’s down. I’m going to create var lookup. This is going to be an object
here.
[Link]
And the object is going to have a bunch of key value pairs. So, we have alpha and
that’s going to be “Adams”. And then we have “bravo”. And the value for “bravo” is
going to be “Boston”. And that’s it. So, we can now delete this whole switch
statement and now we can say result = lookup. And bracket notation we put the
value that was passed in.
[Link]
And then I forgot one thing which was the equals sign here because lookup equals
this object. And let’s do a test. So, let me put [Link] so we can actually
see what happens here. So, if we do “charlie” we're going to get “Chicago”. If we
do “foxtrot” the result will be “frank”. So, it works. [Testing Objects for
Properties] You can check if an object has a property with the hasown property
method.
[Link]
Let me show you how to use this method and finish making this function where we
check if an object has a specific property. If it doesn’t have the property we’ll
return “Not found”. So, let me show you how that’s going to work. We’ll do myObj –
that’s the object up above. .hasOwnProperty. And then we pass in the property
we're going to check which is checkProp.
[Link]
This is either going to come back as true or false if it has the property. So,
let’s make this into an if statement. if ([Link](checkProp)). But if
that’s true, we're going to return myObj and then use bracket notation
[checkProp]. So, we're going to return the value of that property.
[Link]
Else we're going to return “Not Found”. So, let’s take off this other return
statement. And I’ll do a test. So, when we pass in “gift” here, we returned “pony”.
But let’s say we pass in “hello.” Load that "Not Found”. Okay, it works.
[Manipulating Complex Objects] A Javascript object is a way to store flexible data.
[Link]
So, you can store strings, numbers, and arrays. And even other objects. So, in this
example we have an array called myMusic. We can see it’s an array because we have
the open bracket and closed bracket. But inside the array are objects. So, this is
one of the objects. And inside the objects are all these key value pairs with the
strings and the numbers and so on.
[Link]
So, I’m going to add another object. So, since this is an array, after each element
in an array, you have to have a comma. So, I’m going to add a comma here. And then
I’m going to add my next record right below this comment here. And we're going to
have just like above, we're going to have an “artist”.
[Link]
The artist is going to be “Beau Carnes”. And then we have a “title”. The title will
be “Cereal Man”. “release_year” will be “2003”. And for “formats” this is going to
be an array, just like above. So, we can have any format. I’m going to put
“YouTube video”. And now we've created a second object in our myMusic array.
[Link]
And each object holds data and a property which is the key value format. This is
very similar to JSON which we will talk more about later. [Accessing Nested
Objects] Here we have an object with other objects nested inside that. So, in
order to access sub-properties of an object you can chain together the dot or
bracket notation.
[Link]
So, I’m trying to get the gloveBoxContents. So, I’m going to take away this
undefined here and I’ll do a [Link]. And then now the next thing
"car” “inside” and the last thing is “glove box”. Because there’s a space here we
have to use bracket notation. So, I’m going to use bracket notation on the end here
and say “glove box”.
[Link]
And now if we run this – see, we're going to [Link]. So, let’s see if we get
the contents here. Yeah "maps”. It worked. [Accessing Nested Arrays] Array bracket
notation can be changed to access nested arrays. You can see we have this array
here. And inside this array are two objects. The first element in the array is this
object.
[Link]
The second element of the array is this object. And then inside the object we have
a key value pair. The key is list and the value is another array here. So, we can
combine dot notation and bracket notation to access the second tree. That’s what
we're trying to do here. So, let’s do that. First we need to do myPlants.
[Link]
And the trees are the second element in the myPlants array, which is index [1].
Now we need to get the list. So, the list of trees here, so I’m going to do .list.
And since .list is an array, I can use the bracket notation to get the second list
element which again is array index [1]. So, if we run this it’s going to
[Link] and we see “pine”.
[Link]
That’s the second tree here. [Record Collection] This is a coding challenge we're
going to do. We're given this object here which is a record collection. Each
record has an ID and then also has different pieces of information about the
record. They don’t all have the same information. But see, we have “album” “artist”
“tracks” "album” “artist” “tracks”.
[Link]
This just say “artist” “tracks” and this just has album here. And we are supposed
to create this updateRecords function where we can pass in the ID, the property,
and the value. And it’s going to update our record collection with the property
and the value. So, for instance, if we pass in the ID "2468” and we put the
property “artist”.
[Link]
And if we set a different value, like “Quincy” or something like that, then we
should update this whole object. So now it says “Quincy” instead of Prince. And we
should return the full collection. So, it’s going to update the collection and
then return the collection. If we have an empty string for the value, it should
just completely delete that property.
[Link]
Also, if we have the property of tracks and then we have a value, instead of
updating the whole tracks here with what we put in, it’s just going to add the
track to the end of this array. So, if you look really here, the comment says
"Keep a copy of the collection for tests”. This [Link] and JSON.
[Link]
stringify and then collection, this is just a fancy way in Javascript to make a
copy of the object. Remember, in our function we are going to be changing the
collection object. But we want to have a copy of the original object before
anything was changed. So, that’s what that’s for. So, let’s go ahead and do that.
[Link]
So, we're just updating this function here. This update records function. Okay, so
let’s get to this. So we'll do if (value)=== blank. Because the first condition we
are going to test for is if we need to delete the property. Remember, if the value
is set to blank we delete that property. So, if the value is blank, we are going
to delete collection.
[Link]
And then we have to use bracket notation [ID] and then [prop]. The collection[ID]
[prop], that’s the collection here. If we pass in the ID 1248, it’ll go to there.
The property, if we pass in album for the property it would go to here. And then
it would just delete that whole thing if our value is an empty string.
[Link]
Okay, the next condition we have to look for is if the property is “tracks”.
Because for most properties we're just going to override that property with the
value passed into the function. But if the property is tracks, we're going to push
onto the end of the array. So, let’s do an else if. Else if (prop) === “tracks”),
then we just have to push onto the end of the array.
[Link]
So, there’s also another condition here which is if the tracks property is empty.
If the tracks property is empty, we need to create it. Here’s a fancy way to do
that. Collection[ID][prop] So if prop = tracks, we are going to set the tracks –
because remember prop is going to equal tracks. We're going to set the tracks to
equal.
[Link]
It’s going to either equal itself if it exists. Or if it doesn’t exist, we're going
to create it. I’ll show you how. Collection[ID][prop]. It’s going to equal itself.
Or – if the or operator is going to equal an empty array. So, if this already
exists we're going to set it to equal itself. But if itself doesn’t exist, we'll
just set it to equal an empty array.
[Link]
So, that’s just a way to create that property if it doesn’t already exist. So, now
that we know it exists we can just push the value to the end of the array.
Collection[ID][prop]. And we'll just do the .push and then put in the parenthesis,
the value. So we're able to push the value that was passed in to the function onto
the end of the array.
[Link]
Okay, there’s only one last condition which is the kind of the default condition.
Else. So, if the value isn’t blank and the property isn’t tracks, then we just
push the value onto the property. Then we just set the property to equal the value,
just like this. collection[ID][prop]=value. Okay. Let’s test this out.
[Link]
So, we already have this example down here, but to see if it actually worked,
we're going to do a [Link] so we can see the output there. And if I run that
– oh, let me open up the console so we can really see it. So, let’s see what we
changed. Go to 5439 and we set the artist which didn’t previously exist to “ABBA”.
[Link]
So, let’s look down here. In the console, 5439 and the artist is “ABBA”. Let’s see
what happens when we add a track. So, we'll do one more example here. I’ll just put
it right above here, updateRecords. And I’m going to pass in something. I’ll pass
in – let’s see, the ID 2468. And we'll pass in the key which is going to be
“tracks”.
[Link]
And then for the value, we'll put “test”. So, let’s see what happens here. If we
run that, it’s going to update the record here. And then it’s going to update the
record again, but we don’t care about that. We mainly care that it’s going to
[Link] what the final value is. So, if we look at 2468 here.
[Link]
2468, let’s see the tracks. We got “1999” “Little Red Corvette” and “test”, so
it’s working. Great. [Iterate with While Loops] Loops allow you to run the same
code multiple times. I’m going to talk to you about a while loop that runs while a
specified condition is true and stops once it’s no longer true.
[Link]
So, we are going to push the digit 0 through 4 onto this array. Here’s how it’s
going to work. while is the while loop. while i is less than 5. And we're going to
do something while that’s true. First, we have to set what i starts off at. So, var
i = 0. So, while i is less than 5, we'll do [Link](i).
[Link]
Just push it onto the array. And to make sure this loop eventually ends, I’ll have
to do i++ which increments i. So, then I will test this out by doing [Link].
And I’m going to [Link] the myArray. So, let’s see if this works. I’ll run
this and check the console. [0, 1, 2, 3, 4]. The while loop worked.
[Link]
Every time it went through this five different times and pushed 0, 1, 2, 3 and 4
onto the loop. [Iterate with For Loops] A for loop is the most common type of loop
in Javascript. So here is an example of a for loop. You start with the keyword for.
And then we have these parentheses with three different items and they’re
separated by semicolons.
[Link]
The first thing is the initialization. Then we have the condition. Then we have the
final expression. So, the initialization happens before any of the code inside the
loop runs. So, we will start by initializing i to equal 0. So, this is what most
for loops start with, is you have a variable that you’re going to initialize for
the for loop.
[Link]
Then the next thing is the condition. So, once this evaluates to false we break out
of the loop. So, while i is less than 5 we'll continue to run through the loop
over and over until this is false and we break out of the loop. The final thing is
what we do at the end of each iteration. At the end of each iteration, we will
increment i by 1.
[Link]
In this example, we are filling our array with the numbers 0 through 4. I’m going
to do another example where we fill an array with the numbers 1 through 5. So,
we'll start with 4. Now, we're going to initialize i to equal 1. We're starting
with 1 instead of 0 this time. And we're going to do i is less than 6.
[Link]
So while i is less than 6 or until i is more than 6, we are going to run all the
code in this loop. And at the end of each iteration, we are going to increment i.
Now I can just do what we have before. [Link](i). So, the final thing we will
do is test this. I will do [Link] and put myArray inside here.
[Link]
And I’ll just load this and see what we see in the console. [1, 2, 3, 4, 5]. It
worked. We iterated five different times and each time we pushed a new digit onto
the array. And at the end of each iteration we incremented i so it pushed a larger
number onto the array. [Iterate Odd Numbers with a For Loop] Loops don’t just have
to increment one at a time.
[Link]
Look at this for loop here. We have our initialization where we initialize i to 0.
And then we are going to run the loop until i is less than 10. And finally, our
increment, instead of incrementing i by 1, we're incrementing i by 2. So, now this
is going to push all the even numbers onto the array.
[Link]
We have [Link], so let’s log it out and see what it looks like. [0, 2, 4, 6,
8]. I’m going to write another loop right now that creates an array of odd
numbers. So, let’s do that. for (var) i = 1. We’ll start at 1. While i is less than
10. I can use 10 again. I’m going to do i +=2. So, we're still going to count by
2s, but since we're starting at 1 instead of 0 this should give us the odd
numbers.
[Link]
So, let’s see what’s going to be inside our loop. [Link] and I’ll just put i
there. So, let’s log this out and see if we did it right. [Link](myarray). And
I’ll run that. [1, 3, 5, 7, 9]. It worked. [Count Backwards with a For Loop] A for
loop can also be used to count backwards. So, if we see this for loop here, we’re
initializing i to 10.
[Link]
We're starting at 10 and we're going back to 0. So, we're going to iterate through
this loop while i is more than 0. We’re going to keep iterating. And at the end of
each iteration we're going to decrement i instead of increment it. We're going to
go down by 2. i -= 2 means i=i-2. So, we're going to continue pushing the lower and
lower numbers onto the array until i is less than 0.
[Link]
So, let’s log this out and see what ourArray becomes. You can see [10, 8, 6, 4, 2].
Well, I’m going to write another where we’re going to push the odd numbers from 9
through 1 to myArray. So, another for loop. And I’m going to do var i = 9 because
we want to start at 9. Now we’ll still do i is more than 0.
[Link]
So while i is more than 0 we're going to keep going through this array. And we'll
do i – and everything else is really the same. -= 2. And this is going to get all
the odd numbers onto the array. So, we just have to do [Link] and then push
on the i there. Now we'll just [Link] so we can see what it ended up as.
[Link]
myArray. And I’ll run the code. [9, 7, 5, 3, 1] We did it. [Iterate Through an
Array with a For Loop] It is common in Javascript to iterate through the contents
of an array. So, look at this example. We have this array here. Before, we were
always adding items to the array. But this time the array already exists.
[Link]
Right here, ourArr = [9, 10, 11, 12]. So, we are going to start at 0. But now
instead of going to a specific number of iterations, we are going to the
[Link]. So, the length is 4 here. But if we added elements to this array,
that means this loop would just go even longer until we went through every element
of that array.
[Link]
And then at the end we're going to increment i by one at the end of each
iteration. So, look at what we're doing inside the array. We're going doing
ourTotal that starts off at 0 up here. And we’re doing +=. That means we're going
to do ourTotal = ourTotal plus something else. So, we're going to keep adding to
the total whatever is in the array at that index.
[Link]
So, ourArr[i]. So, it starts at 0. And then it goes 1, 2, 3 until it gets to 4
which is the length of the array and it doesn’t even run the iteration at 4. And
there is no index[4] on the array. Remember, it’s 0, 1, 2, 3. So this is just going
to add up all those numbers. If we run this we can see it adds up to 42.
[Link]
I’m going to write another for loop down here that’s going to add up all the
numbers in this array here. So, we'll do for (var i = 0). And then we’ll do i is
less than [Link]. And i++. So, just like before. For each element in myArr
we're going to do a total += myArr index [i]. So, we have to initialize the total
variable right up here.
[Link]
So, we'll do a var total = 0. And then at the end we’ll just [Link] that out
to see what the total is. So, if I just run this we can see that the total this
time is 20. [Nesting For Loops] If you have a multidimensional or nested array,
you can use nested for loops to access all the array elements.
[Link]
So, for instance, we have this multiple all function. It’s defined up here, but
we're calling it here and we're passing in this multidimensional array. Which is
basically an array with the arrays inside the array. So, inside the first array
there are three elements. One. Two. Three. And you can see each of those elements
are in array with their own set of elements.
[Link]
So, we are going to use nested for loops within this multiply all function to
multiply every number in these nested arrays here. So, let’s get started. We're
going to start with a for loop. And it’s going to look just like the other for
loops that we started. i = 0. We’re going to initialize i to 0.
[Link]
And then we're going to say while i is less than [Link]. And then we're just
going to increment i at the end of each iteration. Now, [Link], that’s going
to start off as 3 because we're passing in this array. And the first level of the
array, there’s just one, two, three elements.
[Link]
So, that’s going to be 3. But now, we're going to go inside this for loop and
create another for loop. So, we're going to do var j = 0. Normally, it’s standard
practice to call the variable that we're incrementing i, but we already have an i
within this scope. So, we need to create another name and it’s pretty standard to
call the next variable j because j is after i.
[Link]
So, now we're going to do a j. while j is less than – now this is where it gets a
little tricky. We're going to do while a is less than arr index[i].length. Also,
we're going to increment j here. So, this is going to change. So, the first
iteration of this outer for loop, we're looking at the length of this array.
[Link]
Then we're looking at the length of this array. Then we're looking at the length of
this array. The index is going to be different every time so we're going to be
going to each different array inside the nested array. So, at this point, we just
have to multiply all the numbers together. So, we already have the product that
we've defined above.
[Link]
So, we're going to do product *= which is just going to multiply everything
together. And we're going to do arr[i][j]. So, the i references the outer array
and the j references the inner array within what we're passing in. And now we're
done. So, let’s – we have the [Link] here so let’s run this and see what
happens.
[Link]
And 5040. [Iterate with Do…While Loops] Next I’m going to talk about do while
loops. Now we already talked about while loops and I’m going to review this while
loop and then I will tell you how a do while loop is different than a while loop.
So, this while loop first checks the condition before it runs any code within the
loop.
[Link]
A do while loop will always run at least one time and then it will check the
condition. So, here we have this empty array. We have i = 10. So, while i is less
than 5, well, i is not less than 5 so it’ not going to do anything. Let’s see what
happens. So, we see it logged out 10 and then an empty array because i started as
10 and myArray started as this empty array.
[Link]
So, you were logging the i in myArray. With a do while loop, it’s different. So,
what I’m going to do is cut this line up here and put it at the end. And then at
the beginning I’m going to put the keyword do. In a do while loop, this is always
run at least once before it checks the condition. So, first it’s going to do these
things and then it’s going to check the condition.
[Link]
In this case, it’s going to find out the condition is false and it’s going to
break out of the loop. Let’s see what happens here. See, now i is 11 and the array
has the 10 added to it. [Profile Lookup] This is a coding challenge. We have this
array of objects in our contacts list. And you’ll see each object is one of our
contacts.
[Link]
What the first name, a last name, a number, and likes. So, these are key value
pairs here. So, what we want to do is create this lookUpProfile function where we
pass in a name. This is a first name. And the property. and it’s going to return
the value of that property. For instance, if we pass in the name “Kristian” here
and we pass in the property of “number” it should return “unknown”.
[Link]
If we pass in the first name of “Sherlock” up here and we return the property and
we pass in the property of “likes” it should return the array “Intriguing Cases”
and “Violin”. If the name that’s passed in does not correspond to any contacts,
then our function should return “No such contact”. And if there’s no property, it
should return “No such property”.
[Link]
So, let’s go to this function here and start creating it. So, the first thing we're
going to have to do is iterate through each element in the contacts list. So,
let’s make a for loop. So, for (var i = 0) while i is less than [Link].
And at the end of each iteration we'll do i++ to increment that.
[Link]
So, for each of these contacts the first thing we're going to check is if the name
is a name in this list. So, if(contacts[i].firstName === The name that was passed
in. So, we're checking each item to see if it was the name that was passed in. And
if so, we're going to do something. Now, if not, we're going to do something else,
so let’s do that now.
[Link]
Remember, if the name that was passed in is not in the array, we're going to
return “No such contact”. If it is in the array we're going to go something else.
If the name is in the contacts list we're going to return the value of the
property that was passed in. So, return contacts[i][prop].
[Link]
So, this will return the value of that property that was passed in. However,
there’s another case which is if the property does not exist we return “No such
property”. So, a fancy way in Javascript of saying use this value if it exists,
but otherwise use a different value is to use the or operator.
[Link]
So, we'll say return contacts[i][prop] or if it doesn’t exist, we're going to
return “No such property”. And just so you know, there would be a way to do this
without using this or operator as long as that your code passes the requirements,
that’s all that’s important. There’s many ways of doing this.
[Link]
But let’s check it. So, right now we have our lookUpProfile. We're passing in
“Akira” and we're trying to find the “likes”. And we're [Link] the data.
And “Pizza” "Coding” "Brownie Points”. So, what if we passed in something else? If
we passed in “Shirlock”. Pass in “lastName”.
[Link]
“No such contact.” Well, that’s working because I spelled “Sherlock” wrong. This
is E. So, this is a good way to test that. “Holmes”. And the last thing we'll check
is if we pass in a property that does not exist. I’ll just say “Hello”. And “No
such property”. So, our function works. [Generate Random Fractions] There is a
simple way to create a random decimal number in Javascript.
[Link]
It’s with the [Link] function. So, we have this function here which just says
randomFraction. And it’s returning 0 currently. But we're going to use the
[Link] function. And you well see that when I run this we have 0,2003813741
and so on. So, it’s always going to be a number between 0 and it could be 0.
[Link]
Between 0 and 1, but it could not be 1. [Generate Random Whole Numbers] Often you
want a random whole number instead of a random decimal number. That can be
accomplished with [Link]. We have [Link] here. This rounds down to the
nearest whole number. So, we pass in ([Link]() * 20). And then we round down
to the nearest whole number.
[Link]
This is going to create a random whole number between 0 and 19. Remember
[Link] can never be 1. It can be 0, but it can ever be quite 1. So, when we
multiply it by 20 we’re going to get a number between 0 and 20, but not including
20. And then we round down, which will end up being 0 to 19. So, let me show you
another example where we're going to get a random whole number between 0 and 9.
[Link]
It’s going to look just like this. So, we're going to modify this function. So,
this [Link] we're going to pass that into [Link]. So, I have to put the
parenthesis because we're passing that in to that function. And it’s [Link] *
10. And that’s going to give us a random number between 0 and 9.
[Link]
So, if I reload this I can see. Every time I load it, it’s a different random
number. [Generate Random Whole Numbers within a Range] You can also generate random
whole numbers within a range. So, look at this function here, ourRandomRange. It
takes a minimum number and a maximum number and then it just runs through this
calculation here.
[Link]
So, we have the [Link] and we multiply it by the maximum or min number + 1.
And then we get the floor which is rounding down. And we add all that to our
minimum number. So, this is just a calculation to get a random number between the
min and max. So, as practiced, I’m going to rewrite it down here.
[Link]
So, we have the random range. And instead of ourMin and ourMax, we have myMin and
myMax. However, the equation is going to be the same. So, we have [Link]. You
can take a chance to actually just look over the equation and see if you can
understand how it works. myMax minus myMin. And then we just have to do + 1.
[Link]
And then this whole thing is going to be + myMin. So, we already have this example
test set up down here. randomRange between 5 and 15 and we're going to log it out
here. So, let’s try that. See, every number is between 5 and 15 whenever I run
it. [Use the parseInt Function] Another useful function is the parseInt function.
[Link]
It takes a string and returns an integer. A lot of times you want to make sure
you’re dealing with integers and not strings for different calculations and
things like that. If the string cannot be converted into an integer it returns in
NaN for Not a Number. So, let me show you how it works. From this convertToInteger
function we are going to return.
[Link]
And we're going to return the string except we're going to convert it into an
integer first. So, we'll do parseInt. And then I’ll pass in the string. Now, it was
a string because you can see here we're passing in the string of “56” but it’s
going to return it as a number and integer. [Use the parseInt Function with a
Radix] The parseInt function can also be used with a radix.
[Link]
The radix specifies the base of the number in the string. Such as base 2 or base 7
or base 8. A base 2 would be binary. So, that’s one of the most common ones to use.
Now the default is base 10. That’s what we use normally every day. But let me show
you how that would work. We're going to convert this number which is a binary
number to an integer.
[Link]
So, we'll do return. And I will do the parseInt. I’ll pass in the string as before,
but now we'll have a second argument after the comma which is going to be the
number 2. So, instead of the default of base 10 we'll be passing it as base 2. So,
the computer knows that this is a binary number.
[Link]
[Use the Conditional (Ternary) Operator] I love the ternary operator. It’s like a
one line if else expression. Now this is what it looks like. You have your
condition just like in an if statement. And then you would have a question mark.
After the question mark you have what’s going to happen if the condition is true.
[Link]
Then you have a colon. Then you have what’s going to happen if the condition is
false. So, we can replace an if else statement like this into something using the
ternary operator. So, here we have if this condition is true, we're going to
return true. Else, we're going to return false. Let’s change this.
[Link]
So, now we're going to use the ternary operator. So now it’s just going to say
return a === b. That’s the condition. Then we use the question mark. So if it’s
true, we're going to return true. And then we have a colon. And after the colon we
have what’s going to happen if it’s false, which is we're going to return false.
[Link]
Now I’m going to be honest. You would never write a line like this in real life
because you could just write return a === b. And this line is actually going to do
the same thing as this line. However, I just want to give you a simple example of
using the ternary operator. [Use Multiple Conditional (Ternary) Operators] One of
the great things about conditional or ternary operators is that you can nest them
within each other which gives them even more power.
[Link]
So, we're going to write a function here. The function checkSign. And it’s going to
return the string “Positive” if this number is positive "Negative” if the number
is negative, or 0. And we're going to use a nested conditional operator. So, here
it is. return. And first we're going to check if num is more than 0.
[Link]
And then we'll use the ternary operator. If so, the first thing after the question
mark is if it’s true. If it’s true, we're going to return “positive”. If it’s
false, if the number is not more than 0 we'll do something else. Here is where
we're going to have another ternary operator. We're going to check if num is less
than 0.
[Link]
So, if the number is less than 0, well, if that’s true, we have to have the
question mark for the ternary operator. If that’s true, we're going to return
“negative”. And if it’s false, that’s where the colon comes in, we're going to
return “zero”. So, let’s do this checkSign. I’m going to do a [Link] so we
can see what this returns here.
[Link]
And we can see this is going to return “positive”. If we have a negative number
here it’s going to return “negative”. Or if we have a 0 it’s going to return
“zero”. Now you’ll see that after this colon we have an entire ternary operator.
So, if this is true we just return “positive”. If it’s false, then we do everything
here which is another ternary operator where it checks if this is true.
[Link]
And if that’s true, we return “negative”. And if it’s false, it would return
“zero”. [Differences Between the var and let Keywords] For a long time in
Javascript if you were going to declare a variable you had to use the var keyword.
But starting with ES6 in 2015 we can now declare variables with let and const as
well.
[Link]
Over the next few lessons I will be talking about what let and const do that is
different than var. But one of the things is that let does not let you declare a
variable twice. So, let’s look at this example. You have var catName = “Quincy”.
And then down here, var catName = “Beau”. And if I just run this code you’ll see
that nothing is happening.
[Link]
It’s just allowing us to set the catName twice and declare it twice with the var
keyword. However, if we change this to let. We're going to change all the var to
let. And you’ll see that when we load it again, you’ll see an error, Duplicate
declaration “catName”. So, this is good that it’s creating this error because you
usually don’t want to declare a variable two times in the same scope.
[Link]
So, this allows your program to give you an error to tell you that you’ve done
something wrong. Now you can still reset it. So if we don’t use the word let here
we could just set the catName variable. And now we're not going to get an error. In
this case, we're declaring the variable here to be “Quincy” and we're setting the
same variable to a new name here.
[Link]
This is one of the few reasons that many people only use let and const and never
use var to declare variables. Another thing in this code you can see is “use
strict”. Now this enables strict mode which catches common coding mistakes and
unsafe actions. So, a lot of people will use “use strict” at the top of a full
Javascript file or maybe just in a function to catch coding mistakes.
[Link]
Such as if you create a variable and don’t declare it with var, let, or const.
[Compare Scopes of the var and let Keywords] Another major difference between the
var and let keywords is that when you declare a variable with var, it is declared
globally or locally if declared inside a function. However, let – the scope of let
is limited to the block statement or expression that it was declared in.
[Link]
So, let’s look at this example here. If you see this code, we have this checkScope
function and we're calling it down here. And it’s setting i with a var here, the
var keyword, to “function scope”. Then we're setting it to “Block scope” in here.
And you can see it’s [Link] “Block scope i is: “.
[Link]
And it says “Block scope”. And when we get down here "Function scope” it’s still
“Block scope”. If we want this to be “function scope” down here, we're going to
have to use let. So, we would use let here and then we would use let here. And if
we run the code, now you can see in the console ""Block scope i is: “block
scope”.
[Link]
“Function scope i is: “function scope”. So, even though we set i to block scope
here inside this block. Now, a block is just anything inside these squiggly
braces here. So, with an i inside this block to “block scope”. But then when we get
out here, it’s now back to “function scope” because of this up here.
[Link]
Here’s another thing I want to show you. If this is – if we comment this line out
and we change this to var, what do you think is going to happen? Well, let’s run
it and find out. Look, we set the var inside this block here to “block scope”. And
it says Block scope is: “block scope”. But then when we're outside of the block,
when we're outside of this squiggly braces here, we can still access i here.
[Link]
And it’s set to block scope. But if this was a let and we're declaring it inside
this block. If we run that now when we get outside the block, we get an error
because it’s not defined. So, that’s another reason why people use let instead of
var is so that they can make sure the variable is only defined in the area they
want it to be defined in.
[Link]
But for now I’ll uncomment this out. [Declare a Read-Only Variable with the const
Keyword] Const is another way to declare a variable. It has all the features of let
but it’s also read-only. You cannot reassign a const. So, let’s look at this
program here. We’re running this printManyTimes. And it’s going to log out this
sentence.
[Link]
And the sentence is up here. var sentence is declared. And then we reassign it
here. So, first we declare the sentence to be the string “ is cool!”. Then it’s
reassigned to be the string “ is amazing!”. So, if we run that it should work. It
prints freeCodeCamp is amazing! many times. But if we change this to const let’s
see what happens.
[Link]
Now I’ll run this and we get an error. “sentence” is read-only. If you declare a
variable with the const keyword you cannot reassign it afterwards. This can be
very helpful to prevent you from accidentally making mistakes later. If you know
for sure that you never want to reassign a variable, always use const so you
don’t accidentally reassign it when you don’t mean to.
[Link]
Another thing is when you’re using const it’s very common to use all capital
letters. So, like this, SENTENCE like that. And that’s another away to remember
that it’s a constant. So, if I rename this here, I’m also going to have to repeat
it here. And while we're at it, we're going to change this to let because for the
most part you should only use const or let, but there are certain circumstances
where you would use var.
[Link]
And also in some other videos in this course I’ll be using var. But in your own
code you should mainly use const and let. Let’s reload this to see what happens.
And it worked. freeCodeCamp is cool! many times. We can no longer say that
freeCodeCamp is awesome, even though we know it actually is. [Mutate an Array
Declared with const] While you cannot reassign a variable declare with const you
can mutate an array.
[Link]
So, look at this example that’s not going to work. First we declare the variable s
and we assign it to an array. We declare with const. And now we're going to
reassign the variable s here. But if we do that we're going to get the error “s”
is read-only. However, we can update the array using bracket notation.
[Link]
So, I’ll just comment that out. And using bracket notation, I’ll do index [0]. I’ll
assign to the 2. Index [1], I’ll assign that to 5. And then index [2] I’ll assign
that to 7. And just like that it is going to reassign the array. So, if I just do a
[Link] here. [Link] and put the array in there, we should see the new
array here, [2, 5, 7].
[Link]
[Prevent Object Mutation] As seen previously, a const declaration alone doesn’t
really protect your data from mutation. If you have an object or an array, you can
still mutate it even if it’s declared with const. There is something called
[Link] that will prevent data mutation. So, let me talk to you about
[Link].
[Link]
First of all, let’s understand this function here. We're using this function to
demonstrate [Link]. So, it’s going to create this constant, a math
constant with the Pi in it. This is an object. And right now this can still be
changed. So, if we look down here, this is a try catch block. We'll talk about try
catch blocks in more detail later.
[Link]
But for now, you just have to know that it’s going to try what’s in the first part
of the block. And if there’s an error, then it’s going to go into the catch part
and it’s going to log it out. So, right now we're going to try to change
MATH_CONSTANTS.PI to 99. And if you can see right here, we're going to return the
MATH_CONSTANTS.PI.
[Link]
And down here we are putting it into a variable called PI. So, if we run this
you’ll see that we [Link] PI and it’s 99. But wait a second, we don’t want PI
to change because we know that PI never changes. That’s why we're going to use
[Link]. So, I’ll put it right here. I’m going to do [Link].
[Link]
And in parenthesis I’ll put the object which is (MATH_CONSTANTS). Now I’ve frozen
MATH_CONSTANTS. So when it tries to change MATH_CONSTANTS.PI here it’s not going
to work and it’s going to go into this catch block and it’s going to log out the
error or the exception. So, let me run that. And you’ll see.
[Link]
So, we had an error. And we can see here that PI stays the same at 3,1004. So
whenever you have an object and you don’t want any of the items in the object to
change, use [Link]. [Use Arrow Functions to Write Concise Anonymous
Functions] This function here is called an anonymous function. It doesn’t have a
name.
[Link]
It is assigned to this variable magic. But there’s no word right before the
function keyword to assign the name to the function. Whenever you have an
anonymous function you can convert it into an arrow function. That makes it a
little quicker to write. So, instead of the word function, I’m going to take that
out completely.
[Link]
And then put an arrow here. So, this is the same thing except it’s just a little
quicker to write. But we can shorten this even more. If we're just returning one
value here we don’t even need the return keyword. And we don’t need the curly
braces. So, I can delete all this. And I can delete all this here.
[Link]
And now this is the full function from before, but it’s just really shortened up.
And to make this even nicer, we're not going to use var. I’m going to change this
to const. [Write Arrow Functions with Parameters] Just like in a normal function,
you can pass arguments to arrow functions. So let me show you how to convert this
function into an arrow function.
[Link]
So, it’s a normal function now and it has two arguments. And then it’s going to
concatenate the two arrays passed in. So, first we'll take off the function
keyword. We're going to leave these parenthesis with the parameters. Now I’ll put
the arrow. Since all we're doing is returning this, we don’t even need the return
keyword and we don’t need the curly braces.
[Link]
So, I’ll take that off. We'll take this off. And now we’ve done this. I just
converted that function into an arrow function and it has these two parameters.
So, we just have the parameters in parenthesis. We have the arrow. And then we have
what’s being returned right after the arrow. So, if I run that you’ll see that we
concatenate the two arrays that are passed in in this example.
[Link]
And then for good measure we'll change this to const. [Write Higher Order Arrow
Functions] Arrow functions work really well with higher order functions such as
map, filter, and reduce. I’ll go into more detail at a different time about map,
filter, and reduce. But the main thing to know is that they take functions as
arguments for processing collections of data.
[Link]
Whenever one function takes another function as an argument, that’s a good time
for an arrow function. So, what we're going to do here is we're going to update
this function right here. We want it to compute the square of only the positive
integers in the array. So, it’s passed in this array which is this.
[Link]
And we want to filter out everything that’s not a positive integer. So, I’m going
to use the filter and map functions to do that. But the main thing I want you to
look at is the arrow functions that I’m passing in to filter and map. This line is
going to be a lot more succinct because of the arrow functions.
[Link]
So, ,we have the squaredIntegers is going to be the arr. And we're going to filter
this. So, .filter. Now, again, I’m not really going to explain in detail what the
filter function does, but that will be something for another time. Just look at
this arrow function. We're going to create this arrow function.
[Link]
We're starting it just like this. Now before I showed you that you passed an
arguments in parenthesis for an arrow function. But if you only have a single
argument like this, the number argument, you don’t need parenthesis around the
argument. You can just put the argument and then the arrow. So, this is the
beginning of the arrow function.
[Link]
And then we'll see what’s returned from the arrow function. First we want to
filter this array so we only have numbers that are integers and numbers that are
more than zero. So, we'll do [Link]. And then we will pass in the number.
And number is more than 0. So, let me complete the parenthesis here.
[Link]
Now the result of this filter command will be an array with all the numbers that
are more than 0 and also integers. So, that will be 4, 42, and 6. But after we get
that new array we want to get t he square of each number in that array. So, that’s
where we’re going to use the map function. Now the map function takes a function as
its argument.
[Link]
But instead of writing a full function out we can use an arrow function. So, we're
going to pass in x to the function. And then there’s going to be an arrow function.
Now x just means every element from the array that’s being passed to it. So,
remember the map is getting the array for 42, 6. x means for every element in the
array this is what we're going to do to it.
[Link]
x * x because it’s going to be squared. Again, the main point of the lesson is not
to understand the filter and map functions, but to see that we can put an arrow
function, we can pass in an arrow function and it makes it so we can fit
everything really succinctly on one line. So, let’s reload this and see if it
works.
[Link]
Now we have [16, 1764, 36]. [Write Higher Order Arrow Functions] In order to create
more flexible functions you can use default parameters. The default parameter
kicks in when the argument is not specified or is undefined. So, for instance,
with this increment function we want to change it. We want to change the increment
function.
[Link]
So, you can pass in two arguments, the 5 and 2 to increment by 2. Or you can just
pass in the one argument, the 5 if you want to increment by 1. So, here are the
numbers we're passing in. A number and a value. So, we just have to put value = 1.
So now if a value isn’t passed in, it will be set to 1 automatically, but if it
is passed in, it will be set to whatever is passed in.
[Link]
So, if we run this we can look on the console, we have 7 for this first one and 6
for the second. [Use the Rest Operator with Function Parameters] The rest operator
allows you to create a function that takes a variable number of arguments. The
rest operator is three dots. So, we have this function here.
[Link]
And it’s taking three arguments, x, y, and z and it’s summing them. So, at first
it’s converting these x, y, z into an array called args. And then it’s reducing
them. So, it’s summing them all up here and then returning the results. So, right
now if we just run this, it’s going to log 6 because 1 + 2 + 3 is 6.
[Link]
But we can change this to use the rest operator. So, we're still going to pass in
1, 2, 3. But where it’s accepted here, where we have the arguments here, x, y, z,
I’m just going to put .... That’s the rest operator. Just .... And I’m going to put
args. So, with this rest operator, ..., it will convert everything that’s passed
in into one array and the array is called args.
[Link]
So, now we don’t need this anymore. And it should work the same. If we run this,
we'll get 6. But we can also now add any number of numbers. So, I’ll put a 4 on the
end and 10. It’s going to add those numbers together. So, before we could only pass
in three arguments. And now, we can have any number of arguments.
[Link]
[Use the Spread Operator to Evaluate Arrays In-Place] The spread operator looks
just like the rest operator. Three dots. But it expands an already existing array.
Or it spreads out an array. So, it takes an array and spreads it out into its
individual parts. So, here we have an array with some months. And the spread
operator can spread this array, this arr1 into the individual months instead of
the actual array here.
[Link]
You can only use it in an argument to a function or in an array literal. So, let’s
look at this. So, right now we're setting arr2 to equal arr1. In this example we're
not actually copying it. Because if we change arr1, if we set the index of arr1 to
‘potato’ and we log arr2, you’ll see that index [0] is “potato” even though we're
logging arr2 and we only changed arr1 because these are equal.
[Link]
arr2 and arr1 are the same. But what if we want arr2 to be a copy of arr1 ? We can
use the spread operator. Now we can’t just use the spread operator like this.
That’s not going to work. But if we put this inside brackets, which is an array,
it will spread out the contents of arr1 into this new array. So, we're not making
arr2 equal to arr1.
[Link]
We're making arr2 equal all of the contents of arr1 so they’ll be different. So,
if we run this again, you’ll see that it says “January” for the first element in
the array instead of “potato”. [Use Destructuring Assignment to Assign Variables
from Objects] The next few lesson will be about destructuring assignment.
[Link]
This is a special syntax for neatly assigning values taken directly from an object
to a variable. So, look at this object here. We have this object with three
elements. We have the x, y, and z with their values. And it’s all in the voxel
variable. So, if we want to take each individual element in this object and
assign it to its own variable, this is the old way of doing it.
[Link]
So, we can do vox with an x. This stores x. voxel.y stores y. voxel.z stores z. Now
with destructuring, there’s a simpler and quicker way to assign variables for each
element in an object. So, here’s the destructuring syntax right here. This time, we
are creating variables a, b, and c and assigning them to a values from the object
x, y, and z.
[Link]
We can see we put it in curly braces here. And we just say it equals the object. It
equals voxel. You can read it like this, get the field of x and copy into the
value a. So, get the field of x from the object, copy into the value a. Get the
field of y from the object, copy into the value b. Get the field of z, copy it
into the value c.
[Link]
So, this is just a quicker way of assigning things from an object into variables.
Now we're going to use destructuring to obtain the average temperature for
tomorrow from the input object AVG_TEMPERATURES. So, we have AVG_TEMPERATURES. It
has today and tomorrow’s temperatures. And then the average temperature is
inputted into this function here.
[Link]
So, I’m going to change this line here to use destructuring and destructure the
AVG_TEMPERATURES object here that’s passed into this function. So, first I’m just
going to put the AVG_TEMPERATURES variable here. And then on this side of the
equals sign I’m going to have to use the destructuring. So, I’ll put the curly
braces.
[Link]
And we'll put tomorrow. And then a colon, and then the other curly brace. So, this
is saying get the tomorrow field from the AVG_TEMPERATURES object and assign it
to the tempOfTomorrow variable. So, if we run this, we should see it says 79 in
console because we got the tempOfTomorrow variable. We returned tempOfTomorrow,
and it was logged right here.
[Link]
So, we successfully used destructuring to get the tomorrow variable out of
AVG_TEMPERATURES. [Destructuring Assignment with Nested Objects] We can also use
destructuring assignment to assign variables from nested objects. We have this
nested object right here, the local forecast. And inside we have some nested
objects.
[Link]
So, we have the forecast from today and the forecast for tomorrow. So, here we
have getMaxOfTmrw where we’re going to pass in the forecast. And here we can see
the LOCAL_FORECAST becomes the forecast variable. And we're trying to figure out
the maxOfTomorrow. So, we are going to use destructuring to figure that out.
[Link]
So, it’s going to equal forecast. And remember that is a nested object. So, here,
when you’re destructuring you’re always going to use the curly braces. And we are
first going to get tomorrow. And on the other side of the colon we're going to
have some more curly braces because it’s nested. So, we need to go inside of the
tomorrow object and we need the max.
[Link]
So, we'll do max. And then we have the colon. And maxOfTomorrow. Now we need two
sets of squiggly braces here. So, we have this one. And this one. And so we’ve
destructured two times. And the variable is maxOfTomorrow. So, we’ve set the max
that was inside tomorrow to maxOfTomorrow. So, if I run this, you’ll see it’s
84,600.
[Link]
[Use Destructuring Assignment to Assign Variables from Arrays] You can use
destructuring assignment to assign variables from arrays. Look at this example
here. So, we have this array of [1, 2, 3, 4, 5, 6] and we're assigning the
variable z and x to the first two numbers of the array, 1 and 2. The difference
between destructuring from arrays and destructuring from objects is that you
cannot specify which element from the array to go into a variable.
[Link]
It just goes in order. However, if we wanted number 4 to be going to a variable,
we can just do like this. We would just add some commas. So, we put a comma with
nothing in it, like that. Two commas in a row. And I’ll put a y here. So, now we
have the first element, the second element, we skip the third element, and then
we have the fourth element.
[Link]
So, if I [Link] z, x, and y we should see 1, 2, and 4. Here’s another thing
you can do. You can use destructuring of arrays to switch the places of variables.
Let me uncomment out these. And what I’m going to do is use destructuring to
switch the places of a and b. So, it’ll be like this. I’ll say [a, b].
[Link]
And I’ll say = [b, a]. So now it’s just taking this and switching the places. So
instead of a being 8 and b equals 6, it’s now going to log out 6 and 8. So, let’s
see. Yeah, it worked. [Use Destructuring assignment with the Rest Operator] We can
use destructuring assignment with the rest operator to reassign array elements.
[Link]
We can see in this example we have this array, the digits 1 through 10 in the
array. And we have this removeFirstTwo function. We’re calling it here. And we're
passing in the source. That’s the source array. And it becomes the list. So, we
want to return the array with the first two elements removed.
[Link]
So, let’s use the rest operator inside an array here. So, we'll use the rest
operator, the three little dots. And to remove the first two, I just have to put
two commas here with nothing in between them. So, it’s saying do nothing for the
first element, do nothing for second element. Everything else, put into the arr
variable.
[Link]
We could have assigned the first two numbers in the array to two other variables.
I could do a, b, and then a would be 1, b would be 2, and then arr would be an
array of 3, 4, 5, 6, 7, 8, 9, 10. But right now we just need to return the array
with the first two elements missing. So, if I run that you’ll see that we did that.
[Link]
If you look in the console, we've logged the array and the first two elements are
missing. And then we have the original array down here. [Use Destructuring
Assignment to Pass an Object as a Function’s Parameters] You can use destructuring
assignment to pass an object as a function’s parameter. Let me show you what I
mean.
[Link]
Right now we have this half function. And it’s getting the stats argument. So, the
stats is being passed what is called down here. And it’s passing in this whole
object, so this whole stats object. But you can see within this function we're
only using [Link] and [Link]. So, instead of passing the entire stats into
this function, we can just pass in what we need.
[Link]
So, this is what we're going to do. I’m going to put in some curly braces here and
just put max and min. So, now when the stats get passed in, it’s destructured into
just the max and min variables. And the max and min from the function gets passed
in. So now instead of doing [Link] we can just do max.
[Link]
Instead of [Link] we can do min. So, if we reload that it’s going to work
exactly like it did before, but now we only pass in what we need. This is commonly
used with API calls. When you are getting information from an Ajax request or an
API request, it will often have a lot more information than what you need.
[Link]
And you can use destructuring to get it down to what we actually want to work
with. [Create Strings using Template Literals] Template literals are a special type
of string that makes creating complex strings easier. You make them with this
backtick. So, here’s an example of a template literal right here.
[Link]
We have the beginning backtick and we have the ending backtick. This would be in
place of using a quotation, a single or double quotation mark. A few advantages of
using these template literals, these backticks instead of quotation marks, are
one, you can make multiline strings. You can see this has two lines.
[Link]
Here’s the first line and here’s the second line. And if we log the greeting, it’s
going to put the new line right in there. Another thing is you can add single or
double quotation marks right in the string and you don’t have to escape them. The
third thing is you can put variables right in the string.
[Link]
So, if we see this, see the $. And then we have these curly braces. And so,
anything in between these curly braces that start with the $ is Javascript. So,
right now we just have this variable, [Link] which gets the name from up
here. And then here we have [Link] which gets the age from right there.
[Link]
So, it makes things easier that you can put variables right in the strings. So, if
we run that, you’ll see. And normally it would actually also be printed with a
new line. But with this exact code editor and console, it doesn’t show the new
line. So, there’s going to be a coding challenge that we're going to do right down
here.
[Link]
We have this makeList function. And we want it to create a list based on the array
that’s passed in. So, when we call makeList, we pass in [Link]. Well,
here’s result. [Link] is this array here. And we want it to return an array
that looks like this. Each element in the array is a template literal that has
some HTML in it and then it also has this no-var, var-on-top, and linebreak that
comes right from this array that’s passed in.
[Link]
So, let’s use template literal to create that. So, instead of setting this to equal
null, I’m going to start this off to be an empty array. Now, there’s many ways to
do this, but I’m going to use the classic for loop. So, we'll do for(). And
hopefully, you’ll remember how to make a for loop. We'll do (let i = 0 while i is
less than [Link]).
[Link]
And then at the end we will increment i. So, inside this for loop we'll do
[Link]. And then here is where I’m going to use the template
literal. Put a backtick. And I’ll put this HTML code here. <li class=”text-
warning”>. And now this next part is going to be a variable because it changes for
each array element here.
[Link]
So, I’m going to do dollar sign and then the curly braces. And now I can just do
arr. And then index[i]. Now end curly brace. And then I can just put the </li>.
Okay. And if we [Link] this out because we just finished that, I do
[Link](resultDisplayArray) the array looks just like it’s supposed to be.
[Link]
If you look in the console, it returns correctly. [Write Concise Object Literal
Declarations Using Simple Fields] ES6 added some nice support for easily defining
object literals. If we look at this function here, this function is an arrow
function. It takes in three variables, name, age, and gender. And it’s going to
return an object.
[Link]
And the object is going to have a series of key value pairs where the key is the
name, age, and gender. And the values are the passed in variable names. The passed
in names, age, and gender. So, if you look in the console you can see this
currently does. We did the createPerson. We passed in a name, age, and gender.
[Link]
And you can see in the console, the object is name. And “Zodiac Hasbro”, age 56,
gender: “male”. So, you can see there’s some repetition. We’re repeating name:
name, age: age, gender: gender. Now the first name is the key and the second
name is the value. But there’s a way to just make this simpler.
[Link]
If you know that you want to create an object where the key is the name of the
variable and the value is the value of the variable, there’s an easier way to do
it. We can actually delete this whole thing here. And this is how we're going to do
it. We'll just do name, age, gender. Javascript knows that it’s going to return
this object and it’s going to have three key value pairs, the name, age and
gender.
[Link]
So, if I reload this, you’ll see in the console it looks exactly the same because
this code does the same thing that the previous code did. [Write Concise
Declarative Functions] An object can contain a function. This is the long way to
put a function within an object. But there is a simpler way. We have the setGear
function.
[Link]
But instead of using the function keyword and this colon, we can just delete all
that. And the now this is the new way. If I load this again, you’ll see 3 in the
console just like it was before. Because we've been able to set the gear using
that function. [Use class Syntax to Define a Constructor Function] ES6 provides a
syntax to create objects using the class keyword.
[Link]
So, here’s the older way to create an object. It’s with the new keyword. We can
instantiate an object using this new keyword. And we're instantiating the
SpaceShuttle object. We have to have this constructor function up here. So, we use
this to construct the object. Where we pass in the target planet, ‘Jupiter’.
[Link]
And we said the targetPlanet of [Link]. Once we create the new object
like this, that allows us to do [Link]. So, [Link] which we
set to Jupiter. So, in the console you can see Jupiter. The class syntax replaces
the constructor function creation. So, I’m going to delete that.
[Link]
We're going to use the class syntax. So, I’ll do class SpaceShuttle. And then we
have the curly brace here. And so, inside here we have a constructor. So, do
constructor(targetPlanet). And then that’s all. We just have to put in the curly
brace. And this works exactly the same as before. We’re using the class keyword and
this constructor.
[Link]
So, down here we are going to do the same thing for a vegetable class. So, for the
vegetable class, we'll have class Vegetable. And we're going to have a constructor
with the (name). [Link] = name. So, now that we have this, we can set this
Vegetable to makeClass which will return a Vegetable class.
[Link]
So, that’s up here. And then when we do new Vegetable and passing ‘carrot’, this
carrot will go into here. And it’ll get set as [Link]. So, when we [Link]
[Link], we should get carrot. [Use getters and setters to Control Access to
an Object] With the class object you often want to obtain values from the object
and set a value of a property within an object.
[Link]
This are often called getters and setters. So in this class object, we have the
constructor which we already talked about. We also have a getter and setter to
get and set the writer. So we can get the writer and we can set the writer. Getter
functions are meant to simply return or get the value of an object’s private
variable to the user without the user directly accessing the private variable.
[Link]
So, the private variable is this _author that gets set when you construct the
object. And then when we do get writer, it’s going to return this ._author. So,
you never actually interact directly with this variable, but it’s going to get
the writer which is the author here. And when you’re setting, it’s the same.
[Link]
So, you’re never interacting with the _author, but you can set that with the
writer setter. This change could invoke calculations or even overriding the
previous value completely. So, you can have any number of code lines in this
setter to ultimately maybe do different calculations before you set it or
calculations before you get the property.
[Link]
So, what we're going to do is make our own getter and setter for the Thermostat
class. We're going to create a Thermostat class and we're going to have a getter
and setter. So, here’s the thing about this challenge, is that when we construct
the class, it’s going to accept Fahrenheit temperature, but we're going to create
a getter and setter in the class to obtain the temperature in Celsius.
[Link]
So, it’s going to have to do the calculation right within the class. So, let’s do
that. We're going to do a class of Thermostat. And in this class we need the
constructor. When you first create the Thermostat you’re going to pass in a
temperature. And remember, this is going to be Fahrenheit. Now within this
constructor, we're going to set a private variable.
[Link]
this._temp. So, the word this just means that this variable is only accessible
within this class here. And the _temp – whenever you start a variable with an _
that’s going to generally signify that it’s a private variable. That you’re not
supposed to access it outside of that scope or outside of that class.
[Link]
So, we're going to set the temp. And we're not going to just put this._temp = temp
because it’s passed in as a Fahrenheit and we want to convert it to Celsius. I
just happen to have the equation for Celsius, so it’s 5/9 * (temp – 32). So, now
we can create the getter and setter. So, for getter we’ll do get temperature.
[Link]
And we're just going to return this._temp. Which now it’s in Celsius because we're
storing the value in Celsius even though the thermostat is created in Fahrenheit.
So, with the setter, it’s going to be the same. set temperature(updatedTemp). And
it’s now going to still be in Celsus. So, this._temp = updatedTemp.
[Link]
So, let’s look at the code down here, how we're using it. So, the const Thermostat
= makeClass(). This makeClass function is going to return this thermostat object
here. And then we're going to do const thermos = new Thermostat. So, when you’re
instantiating an object you always use the new keyword.
[Link]
new thermostat, that’s this. And we're passing in 76. That goes into the
constructor, the temp. And so we do this calculation to convent that Fahrenheit to
the Celsius in this local variable here. And then let temp = [Link].
So, [Link] is going to use the getter, get temperature, and it’s
going to return this._temp.
[Link]
So, a key thing to look at is that there are now parenthesis after this. So,
generally, if something is a function, you would see parenthesis after the
function name, but if it’s a variable or a property name, it’s going to not have
parenthesis. So, getters and setters are accessed similar to properties.
[Link]
And then we can use the setter here, [Link] = 26, and then it sets it
with the updated temperature. And now we can say temp = [Link]. And
if we do a [Link] here, we can do that with the temp. And it should have the
new temperature if load that. 26. [Understand the Differences Between import and
require] In the past people would use the require function to import functions and
code from other files.
[Link]
But now we have import and export. You can export code in one file and then import
it in another file. It also allows you to only import certain functions from a
file or certain variables. Let me show you how it works. So, in this file, we have
this capitalized string function. We're passing in this string “hello”.
[Link]
And we want to log out the capitalized strings. But right now it just has an error
because there is no capitalizeString function in this file. However, in this other
file, we do have a capitalizeString function. In this string function .js we have
export. This is the export statement I was talking about.
[Link]
And then it’s exporting this function. It’s actually a variable. Capitalize string,
that’s set to equal a function. This is an arrow function, where we pass in a
string. And then we return the [Link]. Now toUpperCase is just a string
function that makes ever letter uppercase. So, we can import this in our other
file.
[Link]
So, let’s go back to our other file. And I will import – and with the import
statement we're going to use curly braces. And then I’ll put capitalizeString. And
then we have to say what we're importing it from. We want to import it from. And
this is where I put the file name. Now normally you’re going to start with a ./
which just means the current directory.
[Link]
And I’ll type in the file name. “string_function”. Now, the file name has a .js
after it, but that’s assumed. So, you don’t have to put .js. You can just put the
file name without the extension. So, if I run this, you can see HELLO! in all
capital letters. It successfully imported this function from the other file and we
used it in this file.
[Link]
[Use export to Reuse a Code Block] I’ve talked a little bit about export in the
last lesson, but now I’m going to go into more detail. You export functions and
variables from one file so that you can import them into another file. That’s how
you can reuse different code. So, we have this function here.
[Link]
This is a capitalizeString function. It actually just capitalizes the first letter
of the string. And then leaves the rest of the string lowercase. And before, I
showed you you can just put export right before here. But we can export it a
different way. So, I’ll do export and then curly braces capitalizeString.
[Link]
And so now we just exported this function. And to export a variable like this we
have const foo =”bar”, const bar = “foo”. To export these variables you just type
in export before. So now in this file, we're exporting this function and these two
variables. And then we can import them into another file.
[Link]
[Use * to Import Everything from a File] If a file exports multiple different
things, you can import each thing individually or you can import everything. So,
let me show you how you would import everything from a file. It’s just import. And
then you’re going to put an asterisk or a star. And then you’re going to put as.
import * as.
[Link]
And then you have to create an object to store everything in. So, I’m going to
import stuff from a file called capitalizeStrings. I’m going to call this
captalizeStrings. So, this could really be anything. I’m creating an object with
this. And then I’m going to see what I’m importing it from. And then I just put the
file name.
[Link]
In this case, it’s just going to be “capitalize_strings”. Sometimes you would have
to put a ./ if it’s in the same directory there. And then I’ll make sure to put a
semicolon at the end. So, if you’re importing everything, you always start off
with import * as. And then this could be anything. It could be any object name that
you create.
[Link]
And then you’re going to put from. And then you put the “file name” in quotation
marks just like that. [Create an Export Fallback with export default] Before when I
talked about exports, I was talking about named exports. There’s also something
called an export default. This is a fallback export. And it’s often used if you
only want to export one thing from a file.
[Link]
So, let’s say I want this to be my fallback export. I’m just going to only export
this one thing from the file. I can just put export default. So, now we know that
this is just the fallback. Basically, just the one thing we're going to export
from this file. [Import a Default Export] So, we talked about exporting a default
export.
[Link]
Now I’m going to show you how to import a default export. It’s pretty much the
same as before but there is a slight difference. So we are going to pretend we
have a file called math_functions that has a default export name subtract. So,
let me show you how you would import that. So, it’s going to be import subtract.
[Link]
And we’ve already reached the difference here. If it’s not a default export,
you’ll put curly braces around this. But it is a default export so we are not
going to use curly braces. But we still have to say what it’s from. So, from
“math_functions”. Okay, so that is how you would import a default export.
[Link]
Well, thanks for watching. Don’t forget to subscribe. And remember, use your code
for good. Visit [Link]