Introduction to JavaScript

Working With JavaScript

When we work with JavaScript on the front end we have a couple of different ways that we can write it: Inline or External.

Embedded JavaScript
External JavaScript

In this tutorial I will be assuming you are writing the code in a separate file and importing it. This is normally better practice as it allows for caching of the JS file increasing speeds, and also allows for easier debugging and reading!

If you want to run any of these scripts you can simply go to repl.it and create an account which will allow you to run JavaScript in the browser! If you want to run the code natively and not inside of the browser you can use Node.js.

Hello World

Now the most common way to introduce people to a new programming language is to get them to write a "hello world" program. This makes sure that you have your environment set up properly and gives you a little rush because of your success! We can do this is JavaScript by doing the following.

Hello World Example

This should print out "Hello World!" to the browser console. That can be found by pressing F12 or Right Clicking on the page and selecting "Inspect". This will pop-up the developer tools, where we can find the console tab.

This small script is being run from top to bottom, and the code inside of it consists of a single function console.log(); which takes a value (In our case it is a string) and prints it to the screen!

Comments

When we are writing code we often want to document what we are writing. This helps us later on if we try to revisit some code we wrote, or if we are trying to help someone else understand our code! We can create a comment in a JavaScript file in two different ways! Either we can create a single line comment or a multi-line comment.

Single and Multi-Line Comments

Variables

Sometimes we want or need to save a value for later use. To do this we can use a variable! You often run into variables in math! For example, if you are writing the equation y = 2x + 4 we have 2 variables: x and y. You're probably cringing as the PTSD from highschool math comes rushing in, but don't worry; This tutorial has very little to do with math!

Now how can we think of variables in programming? A simple way of imagining them is as a box with a label. When we want to store a value, we can put it inside of the box and give the box a name. From now on when we talk about the name on the box, we are really going to check what item is in the box! Now how does this box idea apply to JavaScript? Well if we wanted to save the value hello world in a variable greeting we could write:

Simple Example of a variable

Ok great! Now what if we want to re-assign that variable? Can we do that? Absolutely! Instead of re-writing the var in front of the the variable, we can simple re-assign the variable to something else using =. We can do this because JavaScript is untyped which means that we do not declare what type of value is going to be inside of the variables!

But wait Nathan, you never told me that there are types! What are you talking about?

Yes sorry, I didn't want to scare you yet. In the same way that english has categories for words, computer has categories for variables. These categories inform the computer how much memory the computer needs to allocate (free-up) so we can store it in memory. Also depending on the language we can set boundaries based on the type set for a variable (You can't add a string and a number).

Well Nathan if we don't have to do it in JavaScript, why would anyone want to do it?

That's a good question, the problem is that computers are dumb. I don't mean to be rude, but they will run everything literally. So, if we tell the computer "Here is a value" and we don't tell the computer if it is text or if it is a number, the computer has to store that value in a way that will be safe for any type because it can't interpret the input. Sound fine right? But the problem is that different types require different sizes, and if we are working with character values (uses 1 byte which is values from 0 to 255 or -128 to 127), the computer may decide to store that value in a memory slot with enough space for a long (8 bytes or -9223372036854775808 to 9223372036854775807). Now if we are writing something that has 10 million characters that need to be stored in memory, we suddenly have to buy 8 times the memory because we didn't define the type. This is exaggerated to make a point.

Well damn Nathan, maybe we shouldn't be using JavaScript?? What possible downsides are there to typed languages?

Well since the untyped languages had issues with the computer making mistakes, the typed languages run the risk of the programmer making a mistake. Types are tricky because if you try to put a long (number with decimal values) into a character, something bad is going to happen right? Because suddenly the computer will try to store 9223372036854775807 in a slot of memory designed to hold up to 255.

Think of this like tupperware. You want to choose the smallest size tupperware to make sure that you don't waste space in the fridge, but if you pick one too small the turkey and gravy will overflow the container and will make a big mess. Anyways, here is how you re-assign a variable in JavaScript:

Re-Assign a Variable

Constants and Block Scope Variables

Sometimes we want to define a variable which is a little more strick about usage. Depending on what you are trying to do we can do this in 2 ways: Constants or Block Scope Variables.

Constants

We can use a constant when we have a value that should never change. This will throw an error like the following: TypeError: invalid assignment to const `myVariable'. For example if we create a connection to a database, we don't want to take the chance that we accidentally overwrite that connection with our greeting!

Example of When we Need Constants

That would be a disaster! But by using a constant we can catch our mistake earlier! There are also some performance benefits as the compiler doesn't have to assume that the variable could change. The only thing is that a const variable only stops you from reassigning or re-declaring, it does not keep you from modifying the contained value by the pointer.

Block Scope Variables

Block Scope Variables allow you to define a variable that is only accessible inside of a code block, or for loop. This may not make sense now, but what this allows us to do is keep variables contained in a specific section of code so that we don't accidentally overwrite other variables in different sections of code. This code should print out the numbers from 0 - 9 and then 22. Although we re-assigned the value in the loop, the inner i variable stays separate from the outer i.

Operators

Now that we understand a bit about variables, what if we want to do operations on those variables? Maybe we want to add or subtract variables, or check to see if the variables are the same or different? We can do this through operators!

Operators

Conditional Statements

Now we can get to the flow control of programming. Since we don't always want to run all the code, we can use conditional statements to control which code is run. There are a couple different conditional statements that we can use: If/Else statements or Switch Statements. An if statement checks the validity of the statement (for example, is your age is less than 16?) then runs the inner code if true (If you are less than 16 you cannot drink or drive). Now we can use an else if statement to check an additional condition only if the original statement was false (if you are less than 19 but greater than 16, the inner code will run as if you were less than 16 it would have been caught by the initial if statement). Finally if we want to run some code if all other statements fail, we can use the else statement (if you are not less than 19 you can drive, and you are also allowed to drink).

if/else Statement

We can also use what is called a Switch Statement which compares a bunch of possible outcomes for a variable and runs sections of code depending on the variable. For example, if we want to do the same check as the last section, we can use the following code!

Bad Switch Statement

This is immensely inefficient, which is why we would normally use an if statement for this kind of problem. But if we were comparing types of fruits, it may make more sense to use a switch statement (as it is a finite problem):

Better Switch Statement

Loops

Have you ever tried to spam your friend? Sitting there sending messages to them over and over again. Well instead of doing it by hand, why not program it away and go enjoy the sun! Before I could begin to explain how to write that program, we need to understand loops. There are 2 main types of loops (for & while), and a couple of variations which help us work with data.

While Loop

The while loop has 3 main components:

  1. Initialization
  2. Evaluation
  3. Increment

We must first declare a variable which will be checked, then we need to evaluate that variable in some statement to see if it is true or false, then finally we modify the variable so it gets closer to completing the goal. In our case we are trying to print out numbers from 0 - 9 so we

  1. Initialize: i = 0 which is our starting value
  2. Evaluate: Is i less than 10? If so, run the code
  3. Increment: Once we have run all the code, increment i by 1 using i++
For Loop

The next main loop is the for loop. The for loop has the same components of the while loop but is packed inside one line. It states that for all that are true (all of the i values that are less than 10) run the code inside the loop, then at the end of each loop, increment the value by 1 (i++). This is more commonly used when you are iterating through an array.

for/of Loop

A for of loop works on objects that are iterable, for example an array or a string! We can see that we instead initialize the looping variable to be the current value in the array instead of the position. This is useful if we don't care about changing the value in the array.

for in Loop

The for in loop allows us to work with objects in JavaScript or what is considered to be a dictionary in Python. The for in loops through the "Keys" of the object, which can then be used to obtain the values for those keys.

do while

The do while is the same as a regular while loop, but it runs the code before performing the evaluation. This snippet should print out the numbers from 0 - 9.

Data Structures

Now that we have discussed basics of programming and programming flow, we need to discuss data storage and manipulation. Most of the time when we write a program, there is some information that we need to store and possibly manipulate. For example, if we have a website that has a login screen, and we need to look up someones username and password, how can we/should we store that information so we can consistently and easily find it.

For now, we will discuss volatile "storage" techniques, where we are storing the data in RAM which will be cleared once the program has completed. Contrary to non-volatile storage techniques like writing the data to the disk or tapes. In another article I will discuss the use of databases which are the conventional way of storing information in a non-volatile format.

Array

Probably the most common data structure is the Array. An array is essentially a chunk of memory that has been allocated to store a certain number of objects. An array of size 10 would allow you to store 10 objects of a certain size, and allows you to access them by passing in the index (position) of the value you want. Now a word of caution, most programming languages start with the value 0 not 1. So, if you want to get the first value in the array, you want to pass in 0. In this example we have a couple of possible functions for an array in JavaScript, there are many others.

Stack

Now we can simulate the use of a stack in JavaScript by using the pop and push functions. A stack in programming is a structure that only allows you to add to the top or pop the value off the top. Think of this as a stack of pancakes, you can either put a pancake on top or eat the top pancake. You cannot eat the bottom pancake, or the middle pancakes. This is called FILO or first In Last Out in programming.

Queue

A queue works in the opposite way that a stack works, where the first element in is the first element out (FIFO). Think of this in terms of a queue at a store. When you get in line, you have to wait until everyone who was already in line goes before it is your turn. And you cannot cut in line or go to the counter unless you are first! This is achieved using the push and shift functions for the array in JavaScript.

Functions

Now the last big thing is going to be functions. Now functions are used in programming to allow for simple code re-use. Functions take some value, and return a value based on the input. This is not always necessarily true, as you can have empty functions but it is generally the case that it will have at least 1 input. The input(s) for a function are called parameters. We can specify any number of required inputs for a function.

Function

As you can see, we can use the return call to return data from the function, as we cannot access the variables that are inside of the function outside of the function. This is useful as we can re-use the same code over and over again without having to re-write it!