The Javascript Langauge

In this tutorial we will learn about the core programming language principles and their usage in Javascript. Whenever possible, try entering some of this code into your own dev console to see it in action.

Hint: on mac, a shortcut to open the console is cmd+option+j!

What are programs?

Programs are sequences of steps that are intended to be carried out by a computer. We also call these algorithms. The sequences can branch out to handle different scenarios according to rules of the programmer's choosing.

The steps may involve waiting for inputs from the outside world, and then doing something with them. Examples of inputs:

  1. Mouse => usb cable or bluetooth => computer operating system
  2. Controller => usb cable or bluetooth => video game
  3. HTTP Request from your phone => internet => Web server

The steps may also send outputs back to the outside world. Examples of outputs:

  1. computer operating system processes mouse movement => Mouse position updated on the screen
  2. Video game processes controller button press => Character moves
  3. Web server processes HTTP request => Sends webpage out to the network

When our Javascript is loaded onto a web page, it is called source code. Humans understand source code. The browser "compiles" it to a format the computer can execute, and that humans cannot reasonably understand. Then the browser will (try to) execute the compiled code. If the code has syntax errors that make it impossible to be compiled, an error will appear in the dev console explaining what happened.

Variables and types

Variables are the building blocks of programs. Variables are given a name of our choosing, and a value that they will hold on to until changed again.

Here are two ways to create a variable, by using let and const:

Setting variables in javascript
1//"const" tells the JS interpreter that the following variable can NEVER change.
2const henrys_favorite_color = "blue";
3henrys_favorite_color = "red"; //ERROR! We used const.
4
5//"let" tells the interpreter that the variable CAN change.
6let henrys_favorite_color = "blue";
7henrys_favorite_color = "red"; //We changed the variable!
Note: var is roughly the same as let, but is becoming deprecated. If you ever see instances of var online, just think of it as the old version of let, and use let instead.

Above, we are assigning text in quotes to these variables, which in the programming world are called "strings".

js values complete reference

Data Types in Javascript

There are a few more options than strings we can use when setting up new variables. These options are called Data Types, and only vary slightly from language to language. Below is an example of each data type available to you in JS:

Data Types
1//boolean type
2let my_boolean = true;
3
4//int type
5let my_int = 4;
6
7//double type
8let my_double = 3.14
9
10//string type
11let my_string = "i am a string :)"
12
13//array type
14let my_array = ["I","am","an","array","of",8, "elements,",["including ","an ","array! "]]
15//To get the 6th element of this array, we use this syntax: my_array[5].
16//The number in brackets is the position of the element we want, starting at 0.
17console.log(my_array[5]);
18//This will print "elements"
19//To get the 3rd element of the array WITHIN my_array,
20//we use this syntax: my_array[7][2]
21console.log(my_array[7][2]);
22//This will print "array!"
23//To get the total length of an array, we can use the length property
24//included with every array, like so:
25console.log(my_array.length)
26//This will print 8.
27//Arrays have tons more properties similar to "length" that we will use in the future.
28
29//object type (Also known as JSON, which stands for Javascript Object Notation)
30let henry_object = {
31  bio: "I am Henry. I enjoy talking about javascript objects.",
32  age: 28,
33  birthplace: "Washington, DC",
34  current_city: "Brooklyn",
35  lucky_numbers: [9,42,123]
36}
37//To access my birthplace contained in this object, we use
38//this syntax: henry_object.birthplace or henry_object['birthplace'].
39console.log(henry_object.birthplace);
40console.log(henry_object['birthplace']);
41//These will both print "Washington, DC"
42//To access the 3rd value of the array WITHIN henry_object,
43//we use this syntax: henry_object.lucky_numbers[2] or henry_object["lucky_numbers"][2]
44console.log(henry_object.lucky_numbers[2])
45console.log(henry_object["lucky_numbers"][2]
More on arrays hereMore on objects here

Functions

Functions are invaluable tools in programming. Similar to how loops allow us to repeat the same lines of code over and over, functions allow us to give a name to a chunk of code and make it reusable. Let's say we want to make a program that compliments a list of first names.

Compliment program that needs work
1let names = ["Aleyna","Michael","Karim","Esin","Dominik","Paul","Hyerin"];
2console.log(names[0]+ " is awesome!!!");
3//Prints "Aleyna is awesome!!!"
4console.log(names[1]+ " is awesome!!!");
5//Prints "Michael is awesome!!!"
6console.log(names[2]+ " is awesome!!!");
7//Prints "Karim is awesome!!!"
8console.log(names[3]+ " is awesome!!!");
9//Prints "Esin is awesome!!!"
10console.log(names[4]+ " is awesome!!!");
11//Prints "Dominik is awesome!!!"
12console.log(names[5]+ " is awesome!!!");
13//Prints "Paul is awesome!!!"
14console.log(names[6]+ " is awesome!!!");
15//Prints "Hyerin is awesome!!!"

This program works just fine, and exudes very positive vibes, but it has some problems. What if we wanted to change the message? We would have to find every instance in our code of the old message and replace it. While it doesn't seem that hard in this example, it is definitely not a sustainable solution when making more complicated programs.

Here is how we can create a function to improve the situation:

Compliment program: improved with functions
1let compliment = function (student){
2  console.log(student + " is awesome!!!")
3}
4
5let names = ["Aleyna","Michael","Karim","Esin","Dominik","Paul","Hyerin"];
6compliment(names[0]);
7//Prints "Aleyna is awesome!!!"
8compliment(names[1]);
9//Prints "Michael is awesome!!!"
10compliment(names[2]);
11//Prints "Karim is awesome!!!"
12compliment(names[3]);
13//Prints "Esin is awesome!!!"
14compliment(names[4]);
15//Prints "Dominik is awesome!!!"
16compliment(names[5]);
17//Prints "Paul is awesome!!!"
18compliment(names[6]);
19//Prints "Hyerin is awesome!!!"

In this code, we are creating a function called compliment. Inside the brackets is the body of our function. On line 1, student is what we call a function parameter. When defining a function, we may add zero, or one or more parameters that the function expects at the time it is called.

We then execute, or call the function 7 times. To call a function, we write the function name followed by parentheses. If the function expects parameters, they are included inside the parentheses in a corresponding order to the function definition. Each time, we are passing a name to the function from our names array. When the function is run, the student variable within it corresponds to the name we passed in when it was called.

The beauty of functions is we can create mini-programs within our programs, and call them with different inputs. The compliment function doesn't need to know anything about the rest of the code- as long as it is supplied with a student, it will succeed!

Let's add one more parameter to give us a bit more control of our compliments:

Compliment program: function with 2 parameters
1let compliment = function (student,adjective){
2  console.log(student + " is "+ adjective +"!!!")
3}
4
5let names = ["Aleyna","Michael","Karim","Esin","Dominik","Paul","Hyerin"];
6compliment(names[0], "great");
7//Prints "Aleyna is great!!!"
8compliment(names[1], "great");
9//Prints "Michael is great!!!"
10compliment(names[2], "fantastic");
11//Prints "Karim is fantastic!!!"
12compliment(names[3], "fantastic");
13//Prints "Esin is fantastic!!!"
14compliment(names[4], "epic");
15//Prints "Dominik is epic!!!"
16compliment(names[5],"epic");
17//Prints "Paul is epic!!!"
18compliment(names[6], "epic");
19//Prints "Hyerin is epic!!!"
More on functions here

Loops

When a program is run, each step is executed in order. To add up the numbers from 1-100, we could write this program:

Commands: One by one
1let total = 0;
2total = total + 1;
3total = total + 2;
4total = total + 3;
5.......
6total = total + 99;
7total = total + 100;
8console.log(total);

While this program might look crazy, you will find that we need to do repetitive things like this all the time. We may have a line or a couple lines that we want to run over and over.

Luckily there is a much better way to write the above program, which is to use a loop. It's impossible to overstate the importance of loops when programming, so please read this code carefully.

For Loop
1let total = 0;
2for(let i=1; i<101; i++){
3  total = total + i;
4}
5console.log(total);

On line 1, we're setting the total variable to 0. On lines 2 and 4, we are starting and ending a for loop. Because of the design of our for loop, line 3 will run 100 times.

Let's break down line 2, where the for loop is created. There are 3 pieces to it separated by semicolons:

  1. let i=1:

    To start the loop, make a variable that will increment at each "iteration" of the loop. Traditionally this variable is called i, but it can be anything.

  2. i < 101

    For the loop to end, this condition must be met. If i is counting up over and over, we want to the loop to stop as soon as i equals 101.

  3. i++

    After each loop ends, perform this step. i++ is shorthand for i = i+1.

On line 3, we can use the variable i, which will increase by one on each iteration.

To recap, For Loops follow this syntax:

For Loop pseudocode
1for(set looping variable; condition to end the loop; step after each loop){
2    //Code that runs within each loop, in between brackets.
3  }
More on loops here

The Document Object Model, or DOM

So far we've learned about data types, variables to hold them, functions to do repetitive tasks with them, and loops to repeat code over and over.

Let's finally take a first look at how we can use javascript to modify content on our page. Let's take a look at this function:

1let updateMessage = function(content) {
2  let our_message_box = document.querySelector("#message-box");
3  our_message_box.innerHTML = content;
4}

On line 1, we create the function updateMessage that takes content as a parameter.

On line 2, we find a specific div on the page to modify. We use a function, document.querySelector, and pass a query as a parameter. The format of the query matches the format we would use in CSS. The div is assigned to the variable our_message_box.

On line 3, we set the inner content of our_message_box to our message variable.

In other words, this:
<div id="message-holder"></div>
will turn into this:
<div id="message-holder">Hello world!</div>

So what is this document.querySelector() thing? And innerHTML?

These are part of the Document Object Model, or DOM.

The DOM is the intermediary layer between our Javascript, and the HTML elements on the page. Behind the scenes, web browsers create a JS representation of the "tree" of elements on the page.

my image

The DOM has a whole suite of functions that let us grab elements in the tree, inspect them, and modify them. In the above code, we never created the document variable. It was already available to us, because it is our crucial entrypoint to the DOM which is available anywhere we are using JS in the browser. We will encounter many more features of the DOM in the future, but for now, we only need to know what's on lines 2 and 3 in the example above.

Here is an exhaustive overview of what you can do with the DOM.