This gives you a REPL, which stands for Read Evaluate Print Loop. How this works is we give it a command and it Reads it into the system. Then, it Evaluates the command. The Print part shows us the value or result of the expression. Once it does that, it Loops back around waiting to read in more input.
You can do all kinds of math with this. You can even do complex math using parenthesis to group things together.
To represent text you need to use what’s called a string. If you were to just write: Hi my name is Kyle, it might thing Hi and my are commands. So, you put single or double quotes around them. Notice how a string just evaluates to itself. If we use single quotes, it still evaluates to double quotes, which is for our benefit so that we know it’s a string.
We can join two strings together using the plus operator. However, it stuck them together without a space. To have the space, we’d need to add it in to one of the words.
Tip: You can call a previous command just by pressing up to go through your history.
We can use functions as commands to make things happen on pages. alert is the command and the () are where you put the expression. So below, we’re saying we want to alert the value of twelve. This is called executing the function.
After you close the pop up, it says undefined, because the command results in nothing/undefined. This is because commands and functions not only take values like 12, but can also return or evaluate to a value. We can pass other values, like strings:
The prompt command prompts the user for info. It will then evaluate the string entered by the user.
We can combine these things. If we add a “Hi ” at the beginning, it will say Hi name that was entered.
We could then take that expression and wrap it inside an alert call.
Writing Your Program
console.log is a function that will output information into the console at the bottom of the screen. Note – this will only work if the browser has developer tools enabled. We add a semicolon at the end to indicate that’s the end of a command. We don’t actually have to do this, it will recognize the next line is a new command and auto insert the semicolon for you, but it’s good practice to do so.
As you’d expect, you can add multiple commands in a single file.
Whitespace between lines doesn’t matter to the .js file at all. It’s good to add to separate chunks of code to make things more readable. In the example below, first the console.logs run, then the prompt, then the alert, then the page loads.
To organize this, we can use variables, which are basically a box where we can store values and give it a name. First you write the keyword var, then a space then the name for the variable (which should start with a lowercase letter), then set it equal to the value you want it to represent. In this case, name is the name we choose for the variable, and we set it equal to the prompt command. Now, for the alert we can just use the variable name rather than having to write out the whole prompt. Note how we don’t use quotes for it, as that would make it a string and not a variable.
The outcome is the same as before, but now we can use our variable name in other places.
An important feature of variables is that they are variable, as in, they can change. Notice that we don’t have to preface it with var the second time. This is because we already declared name as a variable with it, the system knows it’s a variable, so we can just go ahead and change the value without having to declare it as a variable again.
You can also add a comment later in a line, and it will only comment out what’s after the //
To comment out several lines of code, like css you do /* comment here */
Use comments to describe what you’re doing or trying to do, it will help you when come back and look at it later.
These allow you conditionally execute bits of code in your program. An if block begins with the keyword if, then a set of parenthesis where you enter a condition which will decide if the next piece of code will run or not, based on whether it evaluates to true. Then, there are a set of curly braces which are the statements associated with this if block.
If we set it to false, it won’t run the code.
An else needs to be paired with an if, and will run if the if block is false e. In the example below, since the if block didn’t execute, the else block did.
You can put variables in there as well. In the example below, where the if block is true or not depends on what the user puts in the prompt.
Loops let you repeat code over and over again. Let’s say you wanted to say hello world ten times. You could write it ten times, or, loops.
A while loop has an expression that reads either truth e or false e like the if block that determines whether to run the code in the curly brackets. If we just put in true, it will become an infinite loop and never stop running, freezing up our page. You can’t even refresh the page.
If we set it to false, it doesn’t run it.
What you really want to do is enter a dynamic value that will only run this code ten times. First, we’ll declare a variable counter and set it to ten. Then, we’ll set the expression for the while loop to counter, and make it so that every time the loop runs we subtract 1 from counter. After it does that ten times, counter will be at 0, which is a false e value, and the loop will stop running.
If we did this with prompt, if would keep looping until we entered a false e value, by not entering a value at all for null. In the example below, I entered my name three times before not entering a value.
The for loop is like while loop in terms of formatting, but you put three things in it’s parentheses, separated by semicolons. We can use it to replicate what we did for the while loop, all in one spot. The first is the initializer, like how we declared the variable before. Next is the condition, which is what was in the parentheses of our while loop. Finally, you put what will be run after each time the loop is run.
We can put our counter variable as a second part of console.log to see what its value is as the loop runs.
So to break down how this works. First, the initializer sets the initial value, then it checks the expression counter, subtracts one from counter, runs the code in the curly bracket, then checks the expression counter, subtracts one from counter, runs the code in the curly bracket, etc, until counter goes down to zero and it reads false, at which point the loop stops.
An array is a value that is simply a list of other values. Let’s say you wanted to list all of your friends names, you could put them all in a string: “Marty Jim Mehow”. But, this isn’t a good way to separate values. To make an array, declare a variable like before, then use square brackets, separating the different values with a comma. If we call an array with console.log, we get this:
Arrays let us do cool things. We can use the length property to tell us how many things were in the array. You call it by writing .length after the variable. To get it to display, you put in a console.log.
It’s worth noting that in JS, the values of the array don’t have to be the same type.
You can even put other arrays inside the array. Now, the array has 4 elements instead of 6. Notice how it compiles the second array, though you can click to open it.
To get a specific value from an array, write the variable followed by square brackets. This is called subscripting. We put in the index of the value we want to get. To get Marty out of the list, we’d put 0 (not 1), since that’s how we start counting when programming.
Jim would be 1, and Mehow would be 2. If we try an index that’s not in the array we have, we get undefined.
We can also put variables in here.
We can combine arrays with loops, in this case a for loop. For the initializer we’ll do another counter, and commonly they’ll use a single letter like i. For the outcome (the third part), we want to increase i by one. We could write i=i+1, but in JS there’s a shorthand for this by writing i+=1, which will simply add i plus 1. For the expression in the middle, we want it to go two times (because we have 3 friends, and the first will be 0), so we use a comparison operator and say that i < 3. When i is less than three, it will evaluate to true, and when it does not, it will evaluate to false.
Finally, in the code part we make it so it displays whatever friends[i] is, where i will be changing as the loop runs, showing each person based on their index.
It’s worth noting, your index should always be less than your .length, because if you had 4 elements, the index would be 0,1,2,3, while the length would be four.
If we add another friend to the list, the loop will still only go to the third element of the array, because the loop stops after i becomes equal or greater than 3.
To fix this, we can use friends.length, which uses the length of the array. Now, every time it goes through the loop if will check if i is less than the number of elements in the array, versus a set number. So, it will always loop through the needed amount.
Objects are another type of value that can store values in a more flexible way. It has key value pairs or properties. You define it like any other variable, but you set it equal to curly braces, containing multiple values, each of which is assigned to a specific key. You distinguish between a key and its value using a colon, and separate each pair with commas. If we save this below, we now had an object called me, with a first_name and last_name property.
To pull my first name, we’d first write the object me, followed by the dot operator, which means we’re going to get a property. If we then type first_name, it will evaluate to “Kyle”. Same for last name. We can easily get the values by putting dot then the key.
Although we used strings, the values can by numbers, true/false, etc. Anything we’ve seen before. It’s worth noting that the key name can be any string. So, Employee Number wouldn’t be valid, because it’s not a string, but “Employee Number” would be. Alternatively, so would employee_number.
To get to just the “Employee Number” value, we could try me.Employee Number or me.”Employee Number”, but neither would work. Instead, there’s a second way to get at the properties of an object, by using the subscript square brackets and the full string of the key name.
So, we could have also written the other ones as (me.[“last_name”]) and it would have worked as well, but using the dot operator is an easy shorthand that’s preferable. Or, you could even do this for console.log(me), changing it to console[“log”](me). The advantage of using the subscript to access the property is that you can use more types, like the string with a space in it we saw above.
Using a subscript to access a property also is good in that it’s dynamic. Let’s say we declared a variable called key and set its value to “first_name”. If we wanted to get the value of the key first_name from the me variable, there’s not a great way to do that with the dot. But, with the subscript (which remember is when we use the square brackets).
console.log(me.key) doesn’t work, because it’s looking for the key value “key” within the me object. By writing console.log(me[key]), key is the variable that has the value first_name, which then equates to the key first_name in the me object.
If we were to change the var key line to = “last_name”, then it would pull the last name instead.
You can change the value of a key value pair using the dot operator as well. Let’s say we wanted to change the first name. We do the object (me) then the dot operator, then the key we want to change (first_name) and then the new value (“Sam”).
Once again, we can instead use the subscript operator for the same result.
Unlike everything else we’ve seen so far like arrays and objects, functions are less about storing data and more about storing behavior. We’ve used these before: prompt() and alert(). Functions are invoked using parentheses. For example, alert is the function, and we pass it a value, like “Hello”. The value in the parentheses is called an argument.
Let’s say we wanted to use console.log(“Hello World”) in multiple places, but with other things happening between them, so we cannot use a loop. And what if we need to add an exclamation point? It’d be a nightmare to go through and change them all.
Instead, we’ll define a function. We’ll declare a variable called sayHello, then set it equal to the function keyword. Then we’ll add parentheses, which are slight different that the ones we say for console.log, which invoke that function, while these are defining what types of arguments you’ll be able to pass. For now, we’ll leave these out completely.
Next, we’ll use curly braces (like we did for if/else blocks and loops) to define the chunk of code that will be the behavior of our function. In this case the Hello World console.log. We’ll put in some other console.logs to show the parts as they run. We can invoke sayHello with the (), even if there’s nothing in them.
Now, if we need to change what sayHello means, we only have to change it in one place rather than in every place it appears.
We can add more than one command in sayHello. This gives us the same result, by a different means.
Let’s say we want to set up a function that takes an argument. We’ll put it in the parentheses and give it a name, just like any other variable. In this case we’ll call it message. It acts just like a variable, so it needs the same naming conventions. Now, inside the code for the behavior, we now have access to message, just like it was a variable. For the console.log, remember it can take any number of arguments so long as they’re separated by a comma.
Now, we’ll can change the console.logs. We’ll make it so it now calls debug, passing in “x has been set” and “x has been increased. y has been set” as the argument.
The key takeaway here is that you can set up a function that changes based on invocation (like what was passed to the message argument).
Finally, functions can also evaluate to some value. If we were to directly enter debug(“x has been increased. y has been set”); into the console, it would show it like it did before, but it would evaluate to undefined.
Let’s write a function that will double a number. I did it this way which I’m proud of for figuring out. I know it doesn’t double any number, but it worked for 1.
This is how they did it. They use the * to multiply the argument by 2, then the return the value using the return keyword. It is used to exit the function and define the value the function call will evaluate to.