Skip to content

Instantly share code, notes, and snippets.

@bradwestfall
Last active July 11, 2022 15:09
Show Gist options
  • Save bradwestfall/002312c3628eac9cc215 to your computer and use it in GitHub Desktop.
Save bradwestfall/002312c3628eac9cc215 to your computer and use it in GitHub Desktop.
Beginner JavaScript

Beginner JavaScript

This document is a work-in-progress.

Todo's

  • String Escaping

Table of Contents

Chapter 1: Variables and Primitive Data Types

Javascript has two categories of data types: Primitive and Objects. The primitive category has Booleans, numbers, and strings.

Booleans

Booleans can either hold true or false. Here are two variables created with Boolean values:

var likesSports = true;
var isRetired = false;

Numbers

Numbers in other languages have distinct data types for integers or decimal values (sometimes called "floats" or "double"), but JavaScript only has one data type for these called number. These next two variables are both of the number data type:

var area = 3000;
var pi = 3.14;

Strings

Strings are the data type used for alpha numeric (text) characters and are enclosed by either single or double quotes as the following code indicates:

var name = "Brad";
var age = '56';

Note that the use of quotes to make a variable (as in "age" in this case) will always create a string data type, not a number data type.

Choosing to use double or single quotes is a matter of preference. However, most developers use single quotes since they think it's easier to read.

Type Casting

JavaScript is a "Loosly Typed Language" which means the type of variable is automatically determined when the value gets assigned. JavaScript can figure out what "type" you mean to use just by looking at the syntax. For instance, if you used quotes, JavaScript knows you wanted a string.

Sometimes we might change the value of a variable like this:

var color = 'blue';
color = "red";

We start with a string variable with the value of blue. Then we "re-assign" the variable to have a new value of red. We used double quotes the second time, which makes no difference at all.

When variables get re-assigned with new values, the new value might change the type of the variable, for instance:

var color = 'blue';
color = 23;

In this case the value changed to 23 which is a number, so the data type of the variable also changed to number. Some languages require extra work to change data types, but JavaScript, being loosly typed, also has what's called Implicit Type Casting which means data types can change merely by assigning new values to the variable.

Scope

Note that the var keyword is only needed when initializing the variable. After that we simply refer to the variable name without the var keyword. Actually, using the var keyword is not always required for initialization. You can create a new variable with or without use of var. However you will learn later that variables have something referred to as "scope" which tells your code how many places in your code can access the variable. It's a complex conversation that we're not going to get into now, but just understand that using the var keyword creates the variable in what's called "local scope". Variables created without the var keyword will be considered to have "global scope". As you'll learn later, we generally prefer to have almost all of our variables in the local scope. Therefore it's generally considered best-practice to always use the var keyword when initializing a variable.

Just to be sure that we're clear on this subject though, when a variable is first created it's the use of var at that moment that determines the variable's scope. Once the variable and it's scope are created, we always refer to that variable without the var keyword as the above example shows, and it will still be in the local scope.

Console Log

To peek into a variable and see what value it has in it, we need to do a "console log". Use the console object and the log method to output our variable to the console:

var color = 'red';
console.log(color);

We will explain later the meaning of objects and methods, including the opening and closing parentheses, and that "dot" between the two words. But for now just notice it's syntax and take note that there are no spaces.

Each browser has a slightly different way of viewing the output of our console logs, but for the rest of this guide I will assume you're using Google Chrome. In Chrome, (depending on your Operating System) you can either use the F12 key (Windows or Linux), or you can use Command + Option + I (Mac) to open what's called Chrome DevTools. One of the tabs in DevTools is your Console. Click that tab to see your console output. For the remainder of this guide, we will indicate what the expected output should be with comment marks:

var color = 'red';
console.log(color); // Outputs: red

The usefulness of console logging might not be apparent yet since we just created this variable and we know it's value is red. So what's the point in doing a console log? As you start to get into more complicated code you find situations where you don't know what the value of certain variables are because the value was loaded in a way that is dynamic. At that point you will find the usefulness of console logging to be immense.

String Concatenation

Strings can be concatenated in JavaScript, which means more than one string can be combined. This example shows two strings being combined into one:

var text1 = 'Hello';
var text2 = 'World';
var combined = text1 + text2;
console.log(combined); // Outputs: HelloWorld

Notice that the + plus sign is used to concatenate the two string variables. The result is assigned to the combined variable before it is logged. But did you notice that the output for "HelloWorld" has no space? Let's change the code a bit to add the space:

var text1 = 'Hello';
var text2 = 'World';
var combined = text1 + ' ' + text2;
console.log(combined); // Outputs: Hello World

In this case we're building the combined string by using variables and an extra small string (of one empty space).

Let's do it again but a different way:

var text1 = 'Hello'
var combined = text1 + ' ' + 'World';
console.log(combined); // Outputs: Hello World

This one doesn't use a variable for "World" but it works the same. But it's a little strange to have the string with the space be separate from the last string with "World". Let's do it again:

var text1 = 'Hello'
var combined = text1 + ' World';
console.log(combined); // Outputs: Hello World

The main point of showing these examples is to show how expressive your code can be. There are many ways to do the same thing and it's good to see a variety of them to get a sense of how things work.

The + plus sign that we've been using is called a "concatenating operator". There are types of operators which we'll go over in the next section.

Operators

Operators allow us to perform operations on our variables. In the last section the concatenating operator was introduced. It's used to combine strings. There are also arithmetic operators for addition, subtraction, multiplication and other math operations. Here is a code example:

var x = 5 + 2;
var y = 7 - 1;
console.log(x - y); // Outputs: 1

This example shows addition and subtraction but there are many more for you to learn. Note that the + plus sign can either be a string concatenating operator, or an addition operator for math depending on the context which it is being used. See the next section for more on this.

Operators and Type Casting

Operators can have an impact on casting data types. Let's start with an example:

var x = '5';
var y = '2';
var result = x + y;
console.log(result); // Outputs: 52

In this case we have two variables, each is a string. It's very important to know that these are string values and not number values. If they had been made without quotes then they would have been number values, but they weren't.

The + plus operator is used but are we trying to do math or string concatenation? JavaScript will do string concatenation when either of the two parts is a string. This next example shows this further:

console.log('6' + '4'); // Outputs: 64
console.log('6' + 4);   // Outputs: 64
console.log(6 + 4);     // Outputs: 10

The + sign has these special rules because we can use it for both math and string concatenation. This is unusual for a programming language. Most languages use the plus sign for math and use a different character for concatenation.

With the other math operators and strings it's not as complicated:

var x = '5';
var y = '2';
var result = x - y;
console.log(result); // Outputs: 3

For math operators (other than the plus sign), JavaScript will perform a math operation if the two strings contain only numbers. In this case JavaScript uses it's implicit type casting to automatically convert the strings to numbers. But it's also important to know that this type casting only happens for the operation and for the result. The x and y variables will remain strings after this code is ran.

Not a number

In some cases you might end up creating a NaN value which stands for "Not a Number". This can happen in situations where you try to do math operations on values that are not numbers and cannot be cast as numbers:

var x = 'a';
var y = '2';
var result = x - y;
console.log(result); // NaN

NaN is a special variable type. It's not a string and it's not a number type either. It's sole purpose is to represent a value that is, simply not a number.

Chapter 2: Arrays

Primitive types can hold one value at a time, and while that value might change over time, the primitive types can only hold one.

However, there is a way to make a different data type which can hold more than one value at a time. This Chapter will focus on Arrays data types which are under the category of Objects.

This code shows us an array called list which holds two values. Notice that the values being held are primitive values; a string and a Boolean:

var list = new Array('blue', false);

To create an array, we can type new Array() and then we can provide the array some values separated by commas. A console log of the list variable shows square brackets with the values separated by commas. This is the console's way of showing us that the variable is an array:

console.log(list); // Outputs: ['blue', false]

Next, if we want to gain access to specific parts of that array, we can do so by referring to the parts of the array by their numeric order in the Array as follows:

console.log(list[0]); // Outputs: blue
console.log(list[1]); // Outputs: false

When we create arrays, each item in the array is tracked by a numeric "index" which starts at zero. By default, the numbers will increase as we add more items to the array. So in this case, if we want to access the first value of the array, we'll have to refer to the array's 0 index. Notice how before when we console logged the list variable we got an output that showed everything in the list? This time the use of square brackets and passing the index value inside will allow us to log specific values within the array.

It's very important to also know that we have lots of terminology in programming. Knowing the correct terminology means we'll be able to communicate more effectively. For this array, we can either say that it holds two "items" or two "values". Either way "items" and "values" are both correct ways of referring to the items of this Array. The numeric ordering system that JavaScript has used so we can access certain items are called "Indexes". So we might say that...

"The list array has two items. The item at the index of 0 is 'blue'. The item at the index of 1 is 'false'"

If an array already exists (like the one above) and we want to add more values to it, we can do so as follows:

list[2] = true;
console.log(list); // Outputs: ["blue", false, true]

Notice this syntax shows us adding a new item at the index of 2. We do this by using square brackets as well. Before this line of code, the index of 2 didn't exist. JavaScript will create a new item at index 2 in this case and it will have a value of true.

We can add values to our array by picking an index that doesn't exist yet. We can also edit values with a similar syntax.

list[0] = 'red';
console.log(list); // Outputs: ["red", false, true]

Notice this time we used 0 which already exists. This is how we can edit the value of an already existing index.

Lets start a new array to show some different examples:

var data = Array();

Notice that in this case we are making a variable called data which has an array data type. However, unlike the example from before, this array is being created with no initial values. That's okay, as you saw before, we can set the values afterwards like this:

data[0] = 'Arizona'
data[1] = true;
data[2] = 104;

Let's see what our new Array looks like:

console.log(data); // Outputs: ["Arizona", true, 104]

So far it's what we might expect. But what if we then do this

data[6] = false;
console.log(data); // Outputs: ["Arizona", true, 104, 6: false]

It's important to know that the Array's indexing scheme can have gaps. At first we had the Array filled with three values and we explicitly indexed those values to be 0, 1, and 2. Then we made a fourth value but we gave it an index of 6.

Notice that the output from the above console log indicates that we have an item that is not an 3, it is 6. The console log shows us this gap in it's output. This is okay for us to do, it's not so important that we understand why this might happen at this point, as long as we understand that it can happen and it doesn't break any rules.

Lets make yet another array. Only this time we're going to use a new way of filling the Array:

var results = new Array();
results.push('Arizona');
results.push(true);
results.push(104);
results.push(false);

console.log(results); // Outputs: ["Arizona", true, 104, false]

Notice this time we're using a method called .push() to push values onto the end of the Array. This is nice because we don't have to remember what the last index was. And if we want to ensure that we don't have any gaps, this method will ensure that for us because it does the indexing for us.

The last value, the false in this case, is at index 3 and not at index 6. We know this because the console log isn't indicating any gaps.

Array Literals

There is a short-hand way of making Arrays that some programmers prefer. We'll use this "Array Literal" shortcut now to make the exact same array as before:

var results = [];
results.push('Arizona');
results.push(true);
results.push(104);
results.push(false);

console.log(results); // Outputs: ["Arizona", true, 104, false]

Notice that the only thing that changed here is the fact that we're not saying "new Array()"? The opening and closing square brackets is a short-hand way. It's important to note that there is no technological advantage to either syntax. It's simply less to type which is why some prefer it. This short-hand way is called an "Array Literal"

We can start Array Literals as empty arrays, as we saw above, or we start them with some initial values:

var list = ['blue', 'false'];

Now that you've learned several details about arrays, let's look at four ways of starting and filling arrays that all lead to the exact same output:

var list = new Array('blue', false);
list[2] = 104;
console.log(list); // Outputs: ["blue", false, 104]

var list = new Array();
list[0] = 'blue';
list[1] = false;
list[2] = 104;
console.log(list); // Outputs: ["blue", false, 104]

var list = [];
list[0] = 'blue';
list[1] = false;
list.push(104);
console.log(list); // Outputs: ["blue", false, 104]

var list = ['blue', false];
list.push(104);
console.log(list); // Outputs: ["blue", false, 104]

Again, it's not important just yet to understand why there are so many different ways, just understand that they are available.

Chapter 3: Objects

While arrays are a nice way of storing lists of information, they do have their limitations. For instance, let's say we wanted to store information about a person in an array:

var person = ['Dave', 'Mesa', 31, true];

If we asked you to make a welcome message with the person's first name, you might do

var message = 'Welcome ' + person[0];

With the values of our array, it's pretty easy to tell that "Dave" is the first name of the person. But you only knew that because Dave is a common first name. Can you tell what "Mesa" is? Is it Dave's last name or is it his city? Can you tell what "true" is supposed to represent?

Arrays create simple lists but they're actually pretty bad at knowing what each item's meaning is. Plus, what if the order of the values in the array changes? This can happen in software engineering when code gets re-factored. Another software engineer might create this array but in a different order. What if they put the first name in the third position and you did your welcome message anticipating the name is in the first position? This would be a problem because the index of 0 would not be the name.

Objects can solve this problem. Object's are meant to group information that all belongs to each other. A person has information and all the information belongs to one thing: the person. Here is the syntax for creating the same person but with an object:

var person = {'name': 'Dave', 'city': 'Mesa', 'age': 31, 'likesSports': true};

Using curly braces to create an object is called an Object Literal. Later on we'll explain how to start objects in a non Object Literal syntax, but for now we will continue to show all objects as being created using the Object Literal syntax.

Objects are different from arrays in that they have keys instead of indexes. So whereas arrays use a numeric index to identify each item, objects use keys to identify each property. In this object, name, city, age, and likesSports are the object's keys.

With objects, we can access specific properties with square brackets (like we did with the array). Only now we'll use keys to identify which property we want. Take note that they keys are passed into the square brackets as strings:

console.log(personObject['age']); // Outputs: 31

The syntax for an Object Literal is a bit more than an array, but we won't have to worry about the order anymore which is one of many advantages. Even if the object gets re-factored and the properties end up being in a different order, our way of accessing properties with keys ensures we'll get the right information.

Just keep in mind that Objects are good for storing multiple pieces of information about one thing. Object's describe "something", be it a person or a car or a computer. At the beginner level, think of it this way; we typically use "objects" to represent things that are nouns. On the other hand, arrays are lists. They can hold a list of simple things like numbers, or they can hold a list of objects; imagine objects inside an array the same way 1, 2, and 3 could be inside an array. We'll go over this more in a bit

Object Literals can also be initiated with no properties, just as Arrays can with no items:

var person = {};

Wheather the object was started out empty or not, we can fill them with square bracket syntax as follows:

var person['name'] = 'Brad';
var person['city'] = 'Mesa';
var person['age'] = 31;
var person['likesSports'] = true;

Note that filling an object (and accessing certain properties) uses square brackets similar to how arrays do it. If we want to access a certain item of this object, we can do so as follows:

console.log(person['age']); // Outputs: 31

Both arrays and objects allow us to use "Bracket Notation" to get or set values.

objects cannot use the .push() method to add new values

This example shows how we can set new properties to our object, and then get them:

// Set a new property
person['occupation'] = 'Web Developer';

// Access our new property
console.log(person['occupation']); // Outputs: Web Developer

Dot Notation

There is another notation for getting and setting object properties. It's called "dot notation". The following code shows how to do the previous example but with "dot notation" this time:

// Set a new property
person.occupation = 'Web Developer';

// Access our new property
console.log(person.occupation); // Outputs: Web Developer

Arrays do not have "dot notation" to access their items, only objects can do this. Also notice that we don't use square brackets or the quote marks for they key in "dot notation".

It might not be clear right now as to why we would have two notations, but stay tuned to learn more about why later in this guide. The important thing to take away at this point is to know that we can do it two ways. Learn more about dot notation

With or without quotes

Take note that object keys can be created with or without quotes:

var person = {'name': 'Dave', 'city': 'Mesa', 'age': 31, 'likesSports': true}
var person = {name: 'Dave', city: 'Mesa', age: 31, likesSports: true}

We can omit the quote marks for keys in most cases. There are some key names that must be quoted but you're not likely to run into those soon. Whether you use quotes or not on the keys is up to you, just try to be consistent in style.

Beautify

The longer syntax of making Object Literals can make them harder to read if the object contains many properties. As programmers we often do something called "Beautifying" our code. By using hard returns, we can make our code easier to read. Our person object can also be written as follows:

var person = {
	name: 'Brad',
	state: 'Arizona',
	age: 31,
	likesSports: true
}

Notice that we didn't change one character (except that we're using hard-returns to break the code down to multiple lines). Some people find this way of writing code easier to read but the choice is yours. Also notice that we still need those commas to separate the properties, we don't need a comma after the last property though.

If the person object were written with quotes on the keys, it would look like this.

 var personObject = {
 	'name': 'Brad',
 	'state': 'Arizona',
 	'age': 31,
 	'likesSports': true
 }

Remember it's a matter of preference.

Object Collections

You will find times when you want a collection of objects. In computer science terminology, a collection just means a list.

Let's say we want a collection of people. We already know how to make one person object, but let's make two:

var person1 = {name: 'Dave'};
var person2 = {name: 'Sally'};

As you can see we'll need to make different variables in order for this to work. Doing things this way will become cumbersome when we have lots of people or we want to have a dynamic list of people. Keep in mind that when we write code, we want to write it in such away that it can handle dynamic data. Code should be able to sustain itself when more data becomes available in your system. The code we just wrote only assumes we'll ever have just two people. This is very limiting.

The correct way to store numerous people as a collection is to put the objects inside of an array. Maybe that sentence just confused you. It's okay because this is complex to grasp at first. But think of objects as just being variables just like any other variable. Remember when we made an array with several variables assigned to it comma delimited? We can make an array this way and give it objects:

var people = [{name: 'Dave'}, {name: Sally}];

It looks complex at first but if you look closely, this code doesn't introduce any new concepts that we haven't gone over already. It's an Array Literal with two values being passed in when the array is initialized. Those two values just happen to be objects. If it makes it easier for you, we can create the array this way:

var people = []; // An empty array
var people[0] = {name: 'Dave'};
var people[1] = {name: 'Sally'};

The above code creates the exact same array.

Or we could use .push:

var people = []; // An empty array
var people.push({name: 'Dave'});
var people.push({name: 'Sally'});

These three previous examples all create the same array that holds two objects. Remember when we said you can't use .push() on objects? We'll in this case we're not. We're using .push() to add to the array. The values we're adding just happen to be objects instead of Primitive Values.

Do you remember how to access an index of an array with its number? In this new example, the "value" of the item at index:1 is an object. So doing people[1] gives us that object:

console.log(people[1]); // Outputs: Object {name: "Sally"}

Because the value of our array at index:1 is an object, doing a console log will output the contents of the entire object. But what if we wanted to dig deeper and get contents from that object, like the second person's name? We would do this:

console.log(people[1]['name']); // Outputs: Sally

Wow! What is going on here? We're using bracket notation on the array to get the second person (the index of 1 is the second person). This gives us an object. Then we're using square bracket syntax again to get inside the object. Just keep in mind that we could have used dot notation for the key "name" like this:

console.log(people[1].name); // Outputs: Sally

Remember this is because with objects, we can use the two types of notation. The choice is yours. We cannot, however, use dot notation for the array like this:

// THIS DOESN'T WORK
console.log(people.1.name);
@KDragos
Copy link

KDragos commented Feb 6, 2015

Thanks, Brad!

@EvanAlto
Copy link

This git is legit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment