Skip to main content

JavaScript 1: Basic JavaScript

Programming Fundamentals

This is a tough section to teach because the needs of the student vary quite widely here. Some of you are Computer Science or Data Science majors who already know multiple programing languages. Some of you are totally new to coding and JavaScript will be your first programming language. Just like you know Spanish already, learning Italian becomes a whole lot easier since you take the same concepts and express them with minor variances. Our curriculum is meant for those totally new to coding and thus we assume no prior knowledge. If you do know another programming language or have taken an introductory programming course such as CS 61A or Data 8, feel free to instead to skim this section in familiarize with how JavaScript looks.

What is code???

A dumb question but its answer may surprise you. Code is for humans first and computers second. You can think of writing code as essentially writing notes on how to solve a particular problem that just happens to be in a way that computer can understand it.

Wait, why? The why is because you or someone else will have to go back and re-read that code sometime in the future, maybe tomorrow or maybe in ten years. As such, it's important to write code in a such way that it's easily understandable to someone with little context. You will spend far longer maintaining this code than you will be writing it the first time. Be explicit. Be deliberate. The point here is not to be clever but to be simple and to communicate clearly. Code is communication.

Okay, given this, let's frame how this code works then. When you write code, the computer breaks it down into smaller pieces it can understand and then executes those one bit at a time. With JavaScript, only one thing is ever happening at a time (this is called being single-threaded but that is not a term you need to know.) In general, this means it executes line 1, then line 2, then line 3, etc. Let's see that in action:

const monthlyRent = 500;

const yearlyRent = monthlyRent * 12;
console.log(yearlyRent);

Result

6000;

The first thing that happens above is that we declare a variable, monthlyRent. The const keyword is how we let JavaScript know we're declaring a variable. Variable names cannot have spaces in them, which is why we squish the words "monthly rent" together. In order to make this more readable, we use what's called camel casing (because the capital letters in the middle make it look like humps on a camel). Some people like to use underscores e.g. monthly_rent which is cool too, but in JavaScript the convention is camel-case.

Notice the ; at the end of every line. This semicolon lets JavaScript know you've finished the statement. Semicolons are optional in JavaScript (some languages like C require them). Since they are optional, there is a passioante debate about whether or not you should use them. For this course, we don't mind but the writer personally likes to use them.

Variable can be called almost anything. They can consist of any letter, number, underscore, or $, however they cannot start with a number. You can't use keywords. An example would be const const = 15. const is a keyword so it can't be used as a variable name.

You do want to give your variables good names. Imagine we have a huge file and 200 lines below we see the variable named monthlyRent: we'll know instantly what this variable does and we won't have to go try to read the code to figure it out. Always, always, always use good variable names. Seriously. Put time into it. Naming things is hard and it's a big part of your job.

Okay, so after line one, I have a variable named monthlyRent that I can use as much as I want. In this case, it represents the number of 500 but it also semantically represents monthlyRent. Imagine if I had 1000 lines between where monthlyRent is declared and where yearlyRent is calculated. I could have just put 500 directly in yearlyRent but I don't because I now understand how that's calculated just by reading the code. Use variables. Use them everywhere. It makes your code way easier to read. Also, later, if my monthly rent changes, I can change it one place and everywhere I reference monthlyRent gets updated automatically. Powerful stuff.

Okay, I think calculate yearlyRent. I use the * to represent multiplication. I'm also mixing variables and numbers which is just fine. I also could have said const yearlyRent = monthlyRent * monthsInAYear; (assuming I put const monthsInAYear = 12; somewhere else) too and that would be a good idea. I would argue the two are roughly the same since it's obvious there are 12 months in a year. But you do what you think is most clear. That's your job.

console.log(yearlyRent); is going to print whatever is stored in yearlyRent to the JavaScript console. The JavaScript Console is a part of the dev tools. If you need help finding them, see here. We'll explain how it works in a bit but for now just know that anything you put between the parenthesises gets logged out to your JavaScript console.

Let's get this little snippet working in our browser. Make a new folder (I'll just a put it on my desktop) and add an index.html file with the following in it:

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Experiments</title>
</head>
<body>
<h1>JavaScript Experiments!</h1>
<script src="./experiments.js"></script>
</body>
</html>

That script tag is going to let us load JavaScript code into out HTML page. So make another file in the same folder called experiments.js (it really can be called anything as long as the script tag matches it.) Then in the that JS file put our code from above:

const monthlyRent = 500;

const yearlyRent = monthlyRent * 12;
console.log(yearlyRent);

Result

6000;

Now, if you open your HTML file, not the JS file, in your browser and open your console, you should see the number 6000 being printed. Congrats! You just wrote your first code!

Python to Javascript

The easiest way (for me at least) to learn a programming language is to directly compare the conventions of a different programming language and directly apply it to the new programming language. For example, things like functions, lists, variables, and so on and so forth. Since a majority of you are taking or have taken CS 61A or Data 8, we'll be using python as that language of comparison.

Statements

Let's take this simple python code for example:

x = 5
y = 6
z = x + y

In Javascript, the following code would look like this:

let x, y, z;
x = 5;
y = 6;
z = x + y;

Notice how we have to declare our variables first in JavaScript. The let statement let's us do just that. We can also declare and assign a variable at the same time like so:

let x = 5;
let y = 6;
let z = x + y;

Syntax and Convention

In JavaScript you declare variables using the let or const keyword. A variable declared const cannot be modified. You only use let or const when first declaring the variable, after the variable is declared, you do not include a keyword to set it:

let myNumber = 1;
myNumber = 2; // OK

const myNumber = 1;
myNumber = 2; // ERROR
tip

You may see the var keyword in old code. The var keyword is similar to let but has weaker semantics. Specifically, the let keyword defines variables only in the block that they are defined. This prevents your variables from leaking/modifying things they shouldn't.

tldr, use let over var, but they mean similar things.

let myNumber = 420;
let myFloat = 4.2;
let myString = "Hello, World!";
let Mystring = "Hello, World again!"; // Different than the above.

To have a line that is a "comment", that is code that is ignored by JavaScript, you use //

let myInt = 420; // This code is executed
let myFloat = 4.2; // This code is executed
// let myString = "420"; // This code is NOT
// let myString = '420'; // This code is NOT

We recommending adding as many comments as possible to explain how your code works and why you chose to structure it a certain way.

Types

Strings

So far we've just dealt with numbers. Let's go further and start working with words and characters. In programming, we refer to these things are strings, as in a string of one-letter characters. An example of this would be

const myName = "Ben Awad";

You can see I use the " (double quote) to enclose everything I want to be in the string. In JavaScript you can also use ' (single quote) and ` (back tick) as well to demarcate strings.

Strings, as you may imagine, are everywhere in programming. We're constantly keeping track of names, addresses, names of products, cities, etc. and thus constantly need strings.

Let's go further. Strings let you connect them together through string concatenation. If I want to be able to greet someone based on their name, I might have something like this:

const firstName = "Jonathan";
const lastName = "Ma";

const sentence = "Hello " + firstName + " " + lastName + "! How are you!?";
const sentenceWithTemplate = `Hello ${firstName} ${lastName}! How are you!?`;

console.log(sentence);
console.log(sentenceWithTemplate);

Result

"Hello Jonathan Ma! How are you!?";
"Hello Jonathan Ma! How are you!?";

The first way is the old way. We can use the + to tell JavaScript to connect two strings. Notice how we have insert the space between firstName and lastName. The computer only does exactly what you tell it to do. If you don't insert that space, it doesn't get put there.

The second line is the new way of doing this. JavaScript got a large update in 2015 and it made things a lot easier. Now you can use the back tick (notice the first uses a double quote, you must use back ticks to do template strings) to do template strings. If you do that, anything inside of ${yourVariableHere} gets output in the string. Cool, right?

info

Both Ben Awad and Jonathan Ma (Known as Joma Tech) are well-known tech/development YouTubers. Go check them out!

Ben Awad

Joma Tech

Booleans

Sometimes you just need a simple true or false. These are where booleans are useful. Something like a light switch's state is best represented by a boolean. A light is either on (true) or off (false). You'd have something like const lightIsOn = true;. Useful and you'll see them everywhere.

Number

Some languages separate integers (whole numbers, like 1, 2, 3, 4, 500, 1000) and floats (1.2, 3.14159, 14.01, etc.) differently but not JavaScript. JavaScript just has one type of number, Number. A number is a number.

Operators

There are lots of shortcuts you can take when programming, and there's almost always more than one way to write an operation. Some common shortcuts are shown below.

let friendsAtYourParty = 0;
friendsAtYourParty = friendsAtYourParty + 1;
friendsAtYourParty += 1;
friendsAtYourParty++;
++friendsAtYourParty;
console.log(friendsAtYourParty);

Result

4;

Control Flow

If Statements

Sometimes I want to modify the flow of how my program works, or in other words, some time I only want to run code if some condition is true. This is where if statements are very useful. Imagine if we tried this.

const skyIsBlue = true;

if (skyIsBlue) {
console.log("The sky is blue!");
} else {
console.log("The sky is … not blue?");
}

Result

"The sky is blue!"

In the above example, the condition inside of the parens is evaluated and if it's true, the first block is run and the second is skipped. If it is false, the second block is run and the first block is skipped. Paste that code into your experiments and play with it. You also do not have to have an else block. Okay, let's go further.

if (2 + 2 === 4) {
console.log(
"Oh thank god, the fundamental principles of mathematics still hold true."
);
} else {
console.log("Uh, panic?");
}

Result

"Oh thank god, the fundamental principles of mathematics still hold true.";

You can put any expression (a technical terms, means anything you can stick on the right side of an equal sign, we'll explore it more as we go) inside of the if statement. In this case, we are asking, is two plus two still equal to four. If this is true (I hope so) then again the first block will be run. If not, the second will be.

Let's talk about === for a second. If you use just one = in JavaScript, it means is assigned to. So when we have const isBrianCool = true; you can verbalize that as "The variable isBrianCool is assigned to true". Thus we can't use that inside of the if statement because that's not we mean. We're trying to ask a question, not assign something. We're trying to ask "is two plus two equal to four." Enter the triple equals. Triple equals is the same as asking "is this equal to that." We use the triple equals instead of the double equals because double equals does a lot of funny business that usually we don't want it to do. It does what's called coercion and we'll talk about that below. But in an example 2 == "2" but it does not 2 === "2". String 2 is double equal to number 2 but string 2 is not triple equal to number 2.

There's also !==. This is asking "is this not equal to that". Lastly you can ask with numbers > >= < <= as well to ask if numbers less than or greater than too. For another example:

const friendsAtYourParty = 10;

if (friendsAtYourParty === 0) {
console.log("Cool, now I have a lot of nachos to myself.");
} else if (friendsAtYourParty >= 4) {
console.log("Perfect amount to play some Mario Kart.");
} else {
console.log("Wooooo turn on the dance music!");
}

Result

"Perfect amount to play some Mario Kart."

This also demonstrates the else if if you have more than just two different conditions.

Loops and Iteration

Okay so now what if I want do one thing multiple times? I could do something like this

let friendsAtYourParty = 0;
friendsAtYourParty = friendsAtYourParty + 1;
friendsAtYourParty = friendsAtYourParty + 1;
friendsAtYourParty = friendsAtYourParty + 1;
friendsAtYourParty = friendsAtYourParty + 1;
friendsAtYourParty = friendsAtYourParty + 1;
friendsAtYourParty = friendsAtYourParty + 1;
friendsAtYourParty = friendsAtYourParty + 1;
friendsAtYourParty = friendsAtYourParty + 1;
friendsAtYourParty = friendsAtYourParty + 1;
friendsAtYourParty = friendsAtYourParty + 1;
console.log(friendsAtYourParty);

Result

10;

That's annoying though. I wish there was a better way. Before we explore that, let's chat about this example a tad more.

We used let instead of const. Things that are const cannot be reassigned later. In general I find this be of minor help but others do not so I leave you to make your own judgement call. In general one should try to follow the "principle of least power." You should always choose the least powerful "thing" to accomplish whatever you're trying to do. Things with less power tend to be simpler and simple things are less prone to having or causing bugs. We instead use let here because you can see on the subsequent lines we do reassign friendsAtYourParty to be a different number. If you used const your code would crash because const won't let you do that. Thus here we use let. There's another one called var that is the old way of doing JavaScript. There are differences but I don't see a reason to use var at all anymore. It behaves more similar to let.

Okay, so, we want to do this better, let's explore a few ways to do that using loops.

While Loops

let friendsAtYourParty = 0;
while (friendsAtYourParty < 10) {
friendsAtYourParty = friendsAtYourParty + 1;
}
console.log(friendsAtYourParty);

Result

10;

This is a while loop. The first part works similar to an if statement: as long as what's inside that statement is true it will continue running and re-running the body (what's between the { }) until that statement is false. Once that statement is false, it'll break the loop and continue on. This case, we add 1 to friendsAtYourParty until it's 10, and then the next loop, when it's 10, it'll stop because 10 is not less than 10.

Okay, so now let's see a second kind of loop to achieve the same effect as above.

For Loops

let friendsAtYourParty = 0;
for (let i = 0; i <= 10; i++) {
friendsAtYourParty++;
}
console.log(friendsAtYourParty);

Result

11;

This is a for loop which is likely the most common kind of loop. Inside the parens are three statements and you need all of them. The let i = 0; is you defining your control variable that will control the loop. For some reason people always use i, not sure why. It's just that way. It really could be anything. The second statement i <= 10 is just like the while loop, is that's the statement that is as soon as it's false it breaks the loop. The last statement, i++ is that happens at the end of every loop. In our case, we increment the control variable i so that it creeps closer to the end of the loop each time.

An important note: in coding, we start counting from 0. In English, we count 1, 2, 3, 4, 5, etc. but in coding we count 0, 1, 2, 3, 4, etc.. So the fifth element of a string is index 4 (where index is how we'd refer to where that item is in the string). Index 0 is the first element. It's weird but you get used to it and it makes a lot of things easier.

Sometimes, if you mess up what's inside the control condition for the loop, you'll get a runaway loop that'll never complete. This is called an infinite loop and it'll lock up and crash your code. Something like this:

let friendsAtYourParty = 1;
while (friendsAtYourParty > 0) {
friendsAtYourParty = friendsAtYourParty + 1;
}
console.log(friendsAtYourParty);

Since you're adding one to friendsAtYourParty each time, and the loop will continue each time until it's less than zero, that condition will never happen. Thus it'll continue going until it crashes your code. Be careful of these. Nasty bugs.

Functions

A function is a bit of re-usable code. Just how we like to re-use CSS classes, we love to re-use code. Let's start with an example:

function addTwo(number) {
return number + 2;
}

const finalAnswer = addTwo(5);
console.log(finalAnswer);

Result

7;

This isn't super useful but hopefully it shows you the mechanics of how a function works. We created a function called addTwo. This function takes in one parameter, number and it returns that number with 2 added to it. We can now use that addTwo function as much as we want! Let's make a something a bit more useful.

function greet(firstName, lastName, honorific, greeting) {
return `${greeting} ${honorific} ${lastName}! I’m extremely pleased you could join us, ${firstName}! I hope you enjoy your stay, ${honorific} ${lastName}.`;
}

console.log(greet("Clément", "Mihailescu", "Lord", "Salutations"));
console.log(greet("Patrick", "Shyu", "Millionare", "A-hoy"));

Result

"Salutations Lord Mihailescu! I’m extremely pleased you could join us, Clément! I hope you enjoy your stay, Lord Mihailescu.";
"A-hoy Millionare Shyu! I’m extremely pleased you could join us, Patrick! I hope you enjoy your stay, Millionare Shyu.";

Now we rather than have to repeate ourselves over-and-over again with that long string, we can just call greet with the appropriate parameters. Here we use four parameters. The order is important that we send in the parameters because this will be the order function receives these parameters. You can have as many or as few parameters as you like.

The way we call a function is you add parens to the end of it, like this: someFunctionName(). If you see parens after a variable name, you instantly know that that's a function. Inside of the parens go the parameters. These variables will be passed to the function that is being called in the order that you put them there. Example:

const myHomeCity = "Salt Lake City";
const myHomeState = "Utah";
const myHomeCountry = "USA";

function logOutYourHome(city, state, country) {
console.log(`You are from ${city}, ${state} ${country}.`);
}

logOutYourHome(myHomeCity, myHomeState, myHomeCountry);

Result

"You are from Salt Lake City, Utah USA.";
info

Clément Mihailescu and Patrick Shyu (Who goes by Techlead (as a millionare)) are both well-known tech youtubers. Check them out!

Clément Mihailescu

TechLead

Builtins

Lots of functions already exist for you! Smart people have created this commonly-used functions for things we often need. For example, say you have a string and you want to make everything lowercase, you can do this:

const sentence = "ThIs HaS wEiRd CaSiNg On It";
console.log(sentence.toLowerCase());

Result

"this has weird casing on it";

Always be looking for the parens. And the best place to look all this stuff up is from our friends at Mozilla (makers of Firefox): the MDN. MDN used to stand for "Mozilla Developer Network" I think but now it's just synonmous with the documentation for the web. I literally look at this website several times a day. As I said before, you are not expected to remember everything. Looking things up on the MDN is not cheating.

You can call Math.round(5.1) and it'll return that number rounded (in this, 5). You can use string.substr(indexToStart, howManyCharactersToInclude) to return part of a string. For example const name = "Brian Holt"; console.log(name.substr(6, 3)) logs out "Hol" (remember numbering starts at 0). We'll introduce them as we go but know there are a lot of them. You'll learn by doing.

console.log(Math.round(5.1));

const name = "John Denero";
console.log(name.substr(5, 4));

Result

5;
("Dene");

Data Types

  • undefined vs null and use cases

A brief note on what is called types in JavaScript. We've danced the idea already and I want to make it a little more concrete for you. Strings, booleans, objects, arrays, numbers, these are different types of types. JavaScript is a language where you don't have to concern yourself a lot with types since it doesn't strictly enforce them (other languages do) but in this problem you are definitely going to have to deal with it.

const num = 10;
const str = "test";
console.log(num, typeof num); // this is a number here
console.log(str, typeof str); // it's a string here

result:

10 "number"
"test" "string"
undefined

Since you're doing math here, you'll need the numbers to actually be of the number type. Otherwise you'll get "5" + "5" = "55". There's a function called parseInt(string) that will turn a string of a number ("5") to a number (5).

You'll also see that we used the typeof operator. typeof tells whatever the type of the thing that comes right after it is. This is useful to quickly see what's happening in your code. Be careful because typeof is not always useful, but it is useful for telling numbers and strings apart.

Objects

So far we've talked about having one variable at a time: one first name, one last name, one price, etc. What if we have a collection of data? It'd be nice to group together like data. Good news! You can!

const person = {
name: "Josh Hug",
city: "Austin",
state: "TX",
favoriteFood: "🌮",
wantsTacosRightNow: true,
numberOfTacosWanted: 100,
};

console.log(person);
console.log(person.name);
console.log(person["name"]); // same as the line above; definitely prefer using the other one

Result

Object {
"city": "Austin",
"favoriteFood": "🌮",
"name": "Josh Hug",
"numberOfTacosWanted": 100,
"state": "TX",
"wantsTacosRightNow": true,
}
"Josh Hug"
"Josh Hug"

This is called an object. They're extremely useful in JavaScript, and are very similar to dictionaries in python. They're how you'll group together like-information so that they can be used together. They contain a bunch of keys and values. The keys are on the left side of the : and represent how you get that piece data of out of the object. name is one such key.

Used in conjunction with functions they're very powerful. Take this example:

const person1 = {
name: "Sahil",
ageRange: "18-20",
};
const person2 = {
name: "Sarah",
ageRange: "20-22",
};

function suggestMusic(person) {
if (person.ageRange === "18-20") {
console.log("Drake");
} else if (person.ageRange === "20-22") {
console.log("Illenium");
} else {
console.log("The Beatles");
}
}

suggestMusic(person1);
suggestMusic(person2);

Result

"Drake";
"Illenium";

Now we're able to pass all this information as one package which makes it easy to keep track of since we're just passing one variable. You'll see this become even more useful as we start integrating with servers and APIs.

Objects can even have their functions! Let's see that.

const dog = {
name: "dog",
speak() {
console.log("woof woof");
},
};

dog.speak();

Result

"woof woof";

Objects can as well have nested objects inside of them.

const me = {
name: {
first: "Brian",
last: "Holt",
},
location: {
city: "Seattle",
state: "WA",
country: "USA",
},
};

console.log(me);

Result

Object {
"location": Object {
"city": "Seattle",
"country": "USA",
"state": "WA",
},
"name": Object {
"first": "Brian",
"last": "Holt",
},
}

JSON

JSON — short for JavaScript Object Notation — is a format for sharing data. As its name suggests, JSON is derived from the JavaScript programming language, but it’s available for use by many languages including Python, Ruby, PHP, and Java. JSON is usually pronounced like the name “Jason.”

JSON uses the .json extension when it stands alone. When it’s defined in another file format (as in .html), it can appear inside of quotes as a JSON string, or it can be an object assigned to a variable. This format is easy to transmit between web server and client or browser. Very readable and lightweight, JSON offers a good alternative to XML and requires much less formatting.

It is important to keep in mind that though they look similar, a JSON object is not the same format as a JavaScript object, so, though you can use functions within JavaScript objects, you cannot use them as values in JSON. The most important attribute of JSON is that it can be readily transferred between programming languages in a format that all of the participating languages can work with. JavaScript objects can only be worked with directly through the JavaScript programming language.

If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server. You don't need to worry about what "send it to a server" means right now - you can just think of it as a way to send data to our database, much like how when you post on Facebook, Facebook sends that post's data to their database, which is hosted on a server. This is why you might hear someone say that they're "sending data to a server" when they're sending data to a database.

We use JSON.stringify() to convert an Object into a JSON datatype.

let myObj = { name: "John", age: 31, city: "New York" };
let myJSON = JSON.stringify(myObj);
console.log(myJSON);

Result

{"name":"John", "age":31, "city":"New York"}

If you receive data in JSON format, you can convert it into a JavaScript object. We use JSON.parse() to convert JSON into an Object datatype.

let myJSON = '{"name":"John", "age":31, "city":"New York"}';
let myObj = JSON.parse(myJSON);
console.log(myObj);

Result

{name: "John", age: 31, city: "New York"}

Notice how there's quotes around the JSON's keys but not the Object's keys. This is because while Javascript Object keys don't need to be in quotes, and can be in single or double quotes if they are in quotes, JSON keys must be double quoted.

Arrow Functions

A shorthanded way of writing a normal function. Can omit {} and return if return something directly

let addNums = (n1, n2) => {
return n1 + n2;
};

let addNums = (n1, n2) => n1 + n2;

Arrays

Objects are un-ordered collections of datas using keys and values. Arrays, in contrast, are ordered collections of data. If you put something in an array, it has an order. For example, you might a list of the days of the week.

const daysOfTheWeek = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
];
console.log(daysOfTheWeek);
console.log(daysOfTheWeek[0]);
console.log(daysOfTheWeek[1]);
console.log(daysOfTheWeek[6]);

Result

Array [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
]
"Monday"
"Tuesday"
"Sunday"

You first can see how we declare an array, using [ ]. Inside of an array, you can store anything you can store in a variable. You can have an array of numbers, an arry of strings, an array of objects, an array of arrays, an array of arrays of arrays, etc.

You can also see above how we access individual elements in an array: we use square brackets again and then we reference the number that we want to access. Again, remember, the numbering starts at 0. So the first element is index 0.

Arrays also have many methods (another word for functions that live on an object) and properties (another word for key/value pairs) that live on them. Let's see some of those:

const primeNumbers = [1, 2, 3, 5, 7, 11, 13, 17];
console.log(primeNumbers.length);
console.log(primeNumbers.join(" | "));

Result

8;
("1 | 2 | 3 | 5 | 7 | 11 | 13 | 17");

primeNumbers.length gives you back an number that is how long the array is. In this case there are eight elements in the array so it gives us back 8. primeNumbers.join(" | ")) takes your whole array and makes it into one string. THe " | " paramenter I'm passing is what I want put between each element, so you end up with the string "1 | 2 | 3 | 5 | 7 | 11 | 13 | 17".

So what if I want to add an element to the array after I've created. Use push!

const courses = [
{ teacher: "John Denero", course: "CS 61A" },
{ teacher: "Paul Hilfinger", course: "CS 61B" },
{ teacher: "Nick Weaver", course: "CS 161" },
{ teacher: "Dan Garcia", course: "CS 61C" },
];

courses.push({ teacher: "Josh Hug", course: "Data 100" });

console.log(courses);

courses[2] = {
teacher: "Anant Sahai",
course: "How to Have 2 Hours of Free Time Per Week",
};

console.log(courses);

Result

Array [
Object {
"course": "CS 61A",
"teacher": "John Denero",
},
Object {
"course": "CS 61B",
"teacher": "Paul Hilfinger",
},
Object {
"course": "CS 161",
"teacher": "Nick Weaver",
},
Object {
"course": "CS 61C",
"teacher": "Dan Garcia",
},
Object {
"course": "Data 100",
"teacher": "Josh Hug",
},
]
Array [
Object {
"course": "CS 61A",
"teacher": "John Denero",
},
Object {
"course": "CS 61B",
"teacher": "Paul Hilfinger",
},
Object {
"course": "How to Have 2 Hours of Free Time Per Week",
"teacher": "Anant Sahai",
},
Object {
"course": "CS 61C",
"teacher": "Dan Garcia",
},
Object {
"course": "Data 100",
"teacher": "Josh Hug",
},
]

The first thing we do is add an element to the end using the push function that arrays have. It "pushes" the element on the end.

Below that, we're overriding index 2 with a new course. This will throw away what was there before and set it to be what we've set it to be.

Okay, now, given that, what if we wanted to console.log everything in the array? You already have all the tools to do that? Let's see to do it.

const cities = [
"Seattle",
"San Francisco",
"Salt Lake City",
"Amsterdam",
"Hong Kong",
];

// method 1
for (let i = 0; i < cities.length; i++) {
console.log(cities[i]);
}

// method 2
cities.forEach(function (city) {
console.log(city);
});

Result

"Seattle";
"San Francisco";
"Salt Lake City";
"Amsterdam";
"Hong Kong";
"Seattle";
"San Francisco";
"Salt Lake City";
"Amsterdam";
"Hong Kong";

The first way, using a for loop, we're using that i control variable which gets incremented each loop. We use that i to access each item in the array on each iteration of the loop. We have the loop stop when i gets equal to the length of cities. Very useful pattern. You'll see it a lot.

The second way is using a function that arrays have called forEach. This forEach method takes in a function and that function will be called once on each item of the array. It will pass that item into the function, which is what city is in this situation. Both are useful patterns to know. You'll use both frequently. While you're getting started, just use the one you feel comfortable with. They have different things that make them preferable in different situations but usually you can use either. Method 2 may be a bit more advance but I don't think you should be scared of it.

Spread operator (...):

The spread operator is commonly used to make shallow copies of JS objects. Using this operator makes the code concise and enhances its readability.

let fruits = ["apple", "orange", "banana"];
let another_fruits = [...fruits, "papaya"]; //["apple", "orange", "banana", "papaya"]

Contributors