Beau: This is the Beginnerās Javascript course
you are looking for. My name is Beau Carnes. And Iām with freeCodeCamp.org. 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. This course actually goes along with the
freeCodeCamp.org 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 freeCodeCamp.org,
but it could be helpful. 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. 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. 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. 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. And in the console, you can see it says āhello world.ā Thatās right from my Javascript program. So, whenever you do console.log,
itās going to show on the console here. You can also just use the code editor
thatās included on freeCodeCamp.org. Like I mentioned, this course follows along with the Javascript curriculum on freeCodeCamp.org. 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 CodePen.io, 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. We just need the Javascript and the Javascript console. So, if I do console.log 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 Scrimba.com. So, if you want, you can use Scrimba.com
to follow along. 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 console.log āHello from Javascript.ā And you can see in the console right here
āHello from Javascript.ā 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. [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. 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. 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 */. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. One thing I want to tell you about is console.log. Console.log allows you to see things in the console. So, Iām going to console.log(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 console.log(a)
it shows 7 down there. If we put another console.log right here, this will allow us to show what a was up here
and then down there. So, console.log. 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. [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. [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ā. 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. 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. 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. 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. 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 console.log, 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. 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. 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. 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. 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. 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. And I can console.log 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. [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. 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. 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. 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 +=. 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. 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. 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. [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. 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.āā 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. 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.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. 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. 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. 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. [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. 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.ā 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. [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. 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. Iāll do a console.log. 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ā. 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.ā 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 console.log 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. 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. 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 console.log. Iāll just put (myStr) here. If I show that "My name is Beau and I am well!ā
Looks good. [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!ā. 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. 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, firstName.length. 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. 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 console.log 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ā. [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. 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. 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 console.log we can see what it came up with. So, console.log.
(firstLetterOfLastName). 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. 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. 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. 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. You do it based on the length. So, if you look really here, in the brackets
we have an expression to be evaluated. [firstName.length-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[lastName.length - 1]. 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. So, we have the bracket notation,
[firstName.length - 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 [lastName.length]. And then we're going to subtract 2 to get
the second to last character of the string. [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. 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. 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. 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 console.log. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. So, var myData = myArray. And then Iām going to do index [0]. I can do index [1], index [2]. And then if we console.log 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. 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]. 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 console.log and then do (myArray],
we'll see that the array is now [45, 64, 99]. [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. 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. 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. 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 console.log and then do (myData) here. And we'll see if that equals 8. And it does. We did it. [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. 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 myArray.push(). And then I can push something on the end here
which will be like above, another array. 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]. So, now we do this -- ourArray.pop()
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. So, we can do the same thing here. So, removedFromMyArray = myArray.pop() and we can see what the array is going to equal
now if I just do a console.log(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. 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. We're going to do a shift() again. So, Iām going to do = myArray.shift(). 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. 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ā]. 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 myArray.unshift(). 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]]. [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. 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. 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. 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. 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. 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. 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. 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 console.log(a-b). 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. 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. 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. 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. 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. 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. 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. 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. So, when we console.log 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. 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. 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 console.log(myVar). It should console.log the 5. So, we're going to call the function here. And itās going to console.log myVar. But then the program is going to run this console.log
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.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. 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.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ā. Itās because this local variable outerWear took
precedence over the global variable. Another interesting thing about this,
if I do a console.log. And I console.log 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 console.log this function
which is sweater ā it returns sweater. And then we console.log 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. In this case, num-7. So, here we're going to console.log the function. And it returns the result of -7, is this 10-7, which is 3. So, itās going to console.log the number 3. If we look in the console, yep, it console.log
the number 3 because the function returns 3. Letās try creating another one. This function is going to be called timesFive. 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 console.log (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. 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(). 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. 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. 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. [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. 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. And then it should return the first item on the list. In this case, itās 1. So, you see, we had some console.log 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.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. 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 arr.push(). 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. 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 console.log here
it should show the number 1. So, instead of returning item,
Iām going to return arr.shift(). Thatās what shift does. 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. 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. [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. 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ā. 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). 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. 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 console.log. So we can console.log 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. ā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. 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. 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. I can do a console.log here. Console.log. 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 ===. 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. 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. 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. 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. 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. [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. 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. 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. 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. 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. 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. 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. [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. 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. 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. 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.ā 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ā. 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. 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. 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. 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. 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. 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. [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. 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. 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. 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. 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. 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. 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. 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. And we're just going to return āLargeā. So, with this one test here, for test 7,
we can actually console.log that. Console.log. 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ā. 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. 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. 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. 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. 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. 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]. 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. 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 console.log. And we're going to pass in the function
that we're calling. 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. 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. 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. 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. 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. 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ā. 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. 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. To really test this, we're going to have to add a
console.log 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. 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ā. 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. 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ā. 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. 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. 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. 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. 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. 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. 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. 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!ā. 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. 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. 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 console.log this out, console.log,
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. 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ā. 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, console.log. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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ā. 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. 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. 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ā. 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ā. 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. 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. 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, testObject.hat
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. 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. 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. ā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. 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ā. 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 ourDog.name. And use the assignment operator, the equals sign,
to set the name to āHappy Camperā. So, if we do console.log on ourDog.name 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, myDog.name = āHappy Coderā. So, just like above, we use dot notation
to set the object property to a new value. [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. ourDog.bark = ābow-wowā. So, it had four properties but now it has
5 properties as the property bark as well. 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. [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 ourDog.bark. 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. And this time we will delete the tails property
myDog.tails. 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. 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. 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. 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 console.log
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. 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. 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 (myObj.hasOwnProperty(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. 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. 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. 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ā. 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. 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. So, Iām trying to get the gloveBoxContents. So, Iām going to take away this undefined here
and Iāll do a myStorage.car.inside. 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ā. And now if we run this ā
see, we're going to console.log. 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. 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. 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 console.log
and we see āpineā. 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ā. 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ā. 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. 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 JSON.parse and JSON.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. 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. 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. 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. 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. 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. 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. 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. So, we already have this example down here,
but to see if it actually worked, we're going to do a console.log
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ā. 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ā. 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 console.log
what the final value is. So, if we look at 2468 here. 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. 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 myArray.push(i). 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 console.log. And Iām going to console.log 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. 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. 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. 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. 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. 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. myArray.push(i). So, the final thing we will do is test this. I will do console.log and put myArray inside here. 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. 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. We have console.log, 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. So, letās see whatās going to be inside our loop. myArray.push and Iāll just put i there. So, letās log this out and see if we did it right. console.log(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. 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. 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. 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 myArray.push
and then push on the i there. Now we'll just console.log
so we can see what it ended up as. 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. 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 OurArr.length. 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. 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. 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. 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 myArr.length. 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. So, we'll do a var total = 0. And then at the end weāll just console.log 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. 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. 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. And then we're going to say
while i is less than arr.length. And then we're just going to
increment i at the end of each iteration. Now, arr.length, 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. 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. 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. 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. 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 console.log here
so letās run this and see what happens. 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. 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. 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. 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. 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ā. 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ā. 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 contacts.length. And at the end of each iteration we'll do i++
to increment that. 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. 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]. 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. 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. 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 console.logging the data. And āPizzaā "Codingā "Brownie Pointsā. So, what if we passed in something else? If we passed in āShirlockā. Pass in ālastNameā. ā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. Itās with the math.random function. So, we have this function here
which just says randomFraction. And itās returning 0 currently. But we're going to use the math.random 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. 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 Math.floor. We have Math.floor here. This rounds down to the nearest whole number. So, we pass in (Math.random() * 20). And then we round down
to the nearest whole number. This is going to create a
random whole number between 0 and 19. Remember Math.random 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. Itās going to look just like this. So, we're going to modify this function. So, this Math.random we're going to pass
that into Math.floor. So, I have to put the parenthesis
because we're passing that in to that function. And itās Math.random * 10. And thatās going to give us a random number
between 0 and 9. 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. So, we have the Math.random 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. 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 Math.floor. 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. 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. 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. 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. 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. 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. [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. 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. 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. 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. 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. 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. 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 console.log
so we can see what this returns here. 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. 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. 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. 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. 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. 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. 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. 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 console.logging
āBlock scope i is: ā. 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ā. ā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. 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. 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. 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. 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. 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. 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. 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. 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. 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 console.log here. Console.log and put the array in there,
we should see the new array here, [2, 5, 7]. [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 object.freeze
that will prevent data mutation. So, let me talk to you about object.freeze. First of all, letās understand this function here. We're using this function to demonstrate
object.freeze. 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. 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. And down here we are putting it
into a variable called PI. So, if we run this youāll see
that we console.log 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 object.freeze. So, Iāll put it right here. Iām going to do object.freeze. 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. 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 object.freeze. [Use Arrow Functions to Write Concise Anonymous Functions] This function here is called an anonymous function. It doesnāt have a name. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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 Number.isInteger. And then we will pass in the number. And number is more than 0. So, let me complete the parenthesis here. 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. 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. 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. 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. 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. 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. 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. 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. 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. [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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. [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. 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. So, if I console.log 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]. 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. 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. 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. 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. 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. 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 stats.max and stats.min. So, instead of passing the entire stats into this
function, we can just pass in what we need. 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 stats.max
we can just do max. Instead of stats.min 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. 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. 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. 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. 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,
person.name which gets the name from up here. And then here we have person.age
which gets the age from right there. 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. 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 result.failure. Well, hereās result. result.failure 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. 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 arr.length). And then at the end we will increment i. So, inside this for loop we'll do
resultDisplayArray.push. 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. 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 console.log this out
because we just finished that, I do console.log(resultDisplayArray)
the array looks just like itās supposed to be. 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. 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. 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. 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. 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. 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. 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ā. And we said the targetPlanet of this.targetPlanet. Once we create the new object like this,
that allows us to do zeus.targetPlanet. So, zeus.targetPlanet 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. 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. 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). this.name = name. So, now that we have this, we can set this Vegetable
to makeClass which will return a Vegetable class. 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 this.name. So, when we console.log carrot.name,
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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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 = themos.temperature. So, thermos.temperature is going to use the getter,
get temperature, and itās going to return this._temp. 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. And then we can use the setter here,
thermo.temperature = 26, and then it sets it with the updated temperature. And now we can say
temp = thermos.temperature. And if we do a console.log 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. 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ā. 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. 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 string.toUpperCase. Now toUpperCase is just a string function
that makes ever letter uppercase. So, we can import this in our other file. 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. 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. [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. 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. 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. [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. 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. 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. 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. 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. 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. 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. Well, thanks for watching. Donāt forget to subscribe. And remember, use your code for good. Visit freeCodeCamp.org
Is this any good?
upvote for the great kid at the beginning and the dadās (I assume) patience.