Lesson One: Javascript Basics Notes and Explanations - rociorey/cci-2020 GitHub Wiki

Getting Started with JavaScript

What is Javascript?

What is Javascript?

JavaScript is a programming language you can use to make web pages interactive. It first appeared in 1995 when its developer created it in 10 days as part of the dot com boom. https://en.wikipedia.org/wiki/Dot-com_bubble

So What is a Programming Language?

A programming language is a way that we can write instructions that a computer will understand. Each one is good at different things, which is why we use a language like JavaScript for interaction and HTML for websites.


These are the three main languages we use on websites:

HTML: Website skeleton, responsible for text and content

CSS: Website cosmetics, responsible for making everything look nice

JavaScript: Website interactivity, responsible for sign-ins, animations, buttons, etc.


A lot of languages use similar principles, but the way the rules are written change according to which language you use.

The way that you write instructions in different programming languages is called syntax.

What can you do with Javascript?

Interactive Content such as sign in pages, web applications, animations and VR. You can also use it to communicate between an Arduino (small physical computing device) and the web.

What is the Front and the Back End with Javascript?

On the web, you can use Javascript on the front end of a website. The front end of a web browser is what people see when they interact with the site, like dropdown menus, design, and animations.

The back end of the website is all the behind the scenes stuff that allows the front end to work. This is where the server is.

What is a Server?

A server is a computer that provides data to another machine using a network. So if you try to sign in to moodle, the website sends your login information to a server that it’s connected to in a network. Then, the server checks if the login you entered matches its database. If it does, the server sends a message back to the website that everything is ok and you can continue to the website. If the server does not find a match, either because of a misspelling or incorrect login, it will tell moodle not to let you in. Moodle then sends you an error message that says you have the wrong login.

https://blog.udacity.com/2014/12/front-end-vs-back-end-vs-full-stack-web-developers.html

How Can You Access Javascript on the Web?

Open the console window in a section called “developer tools”.

To open the developer tools on a Mac press command + option + i.

To open them on a Windows PC press control + shift + I;

What are Variables?

What are Variables?

A variable is a stand-in symbol for a value. For example:

y=367.891298458966

What does it Matter?

Variables are super useful because instead of having to write out 367.891298458966 in every single place we need that value in our code, we can just write ‘y’.

All you have to do for a computer to reference that number or value is tell it what ‘y’ stands for. This is usually done in the beginning of the code in a format like this:

Let y = 367.891298458966

Or something similar. This system is also super helpful, because if we ever need to do something like change the value 367.891298458966 to 220 in the code, we don’t need to look through every line to try to find something, which would be a pain. Instead, we can just go up to the beginning of the code and change the value:

Let y = 220

And done! Now everything you wrote in the code that referenced 367.891298458966 will now use 220 instead.

Variables in Javascript:

Variables are used in a lot of programming languages, but JavaScript uses variables a bit differently. In JavaScript variables can hold any data type (next section), including text (also called strings), numbers, arrays or objects.

Three Types of JavaScript Variables:

There are three words you can use to assign variables in JavaScript, also called keywords.

Keyword Syntax
Var keyword var skyColor = "red";
Let keyword let numberOfPidgeons = 10;
Const keyword const tree = "Oak";

Wherever you write these three types, there’s a three-part structure:

Keyword The Catchy Name You Give Your Variable = What The Variable Means
var skyColor = “red”;
let numberofPidgeons = 10;
const tree = “Oak”;

The Keyword is there to tell the computer that you want to define a variable. The super catchy name is there so you can more easily figure out what you are referencing, and also so that the computer knows that whenever you type that super catchy name, it’s meant to use the value, which is that third bit.

The last cool thing that variables do is that they can be changed after they have been assigned a value. For example, if you decided that you wanted the skyColor to start as red but change to another blue later in the code, you can do that.

The only value you can’t do that for is the const, because this quite literally stands for a constant value. So using the example above, the tree would always have to be an oak tree.

What are Data Types?

What are Data Types?

Data Types are basically just different types of values, like letters and number. Here are some of the ones we use in JavaScript:

String - the type for text

Strings are data types that act like a storage container for characters or words. A string needs to have either double or single quote marks at the beginning and end.

Number - the type for numbers

This gets a bit trickier. Number includes positive and negative numbers as well as whole and decimals. Decimals are also called floating point numbers because they have a floating decimal. Also part of this type is the Not a Number (NaN), which you get when you try to do numerical operations where the result is not a number, for example if you divide zero by zero (this kind of just blows math’s mind)

Booleans - the type for yes or no questions

Booleans are data types that can only have true or false values. So for example, if you need your code to tell you if the answer to your equation is equal to three or not equal to three.

What are Data Structures?

These are slightly more complex types of data that can hold more information, like Arrays and Objects.

What are Arrays?

An array is a data structure that can hold a bunch of different values. Those values can be a mix of data types, so you don’t need to only use numbers or only use letters.

Syntax: Use square brackets to hold the contents of the array, and separate each element of the array with a comma.

var anArray = ["Sun", 10, True, "Orange"];

How do Arrays work?

Arrays work with a system of index numbers. What that means is that every item in an array has a number assigned to it, based on where it is in the queue. The index numbers start at 0, so the first element of the array is 0, the second is 1, etc.

var anArray = ["Sun", 10, True, "Orange"];

var anArray = [ "Sun", 10, True, "Orange" ];
Index Number 0 1 2 3

If you want to reference a specific element in your array you do this:

anArray[3]; 

//This returns Orange

anArray[1]; 

//This would return 10

Arrays are very flexible because you can add and remove elements from an array once it's been declared. This means you can switch up the order of elements or add more stuff. But that also means that your elements change index numbers:

So if you originally had this:

var anArray = ["Sun", 10, True, "Orange"];

var anArray = [ "Sun", 10, True, "Orange" ];
Index Number 0 1 2 3

And changed it to this:

var anArray = ["Moon", "Sun", True, 10];

var anArray = [ "Moon", "Sun", True, 10 ];
Index Number 0 1 2 3

So even if you reference the same numbers as before, they’ll return different things:

anArray[3]; //This returns 10
anArray[1]; //This would return “Sun”

Arrays in JavaScript?

There are a lot of JavaScript functions you can perform on an array. For example, some functions find out how many characters are in an array (it’s length), and some check if the object is an array.

What are Objects?

Objects are structures that store a bunch of values. I think of it as a labelled container with other stuff inside it, or a folder that has subfolders of information. You can use a ton of different functions with objects as well.

How Do Objects Work?

Objects work by storing values with a system called a key/value pair. A key/ value pair is basically the name of the type of information (key) followed by the actual information (value).

The way you write a key/value pair is by writing the key, then a colon, then the value in quotation marks, and then a comma if you want to add another value:

Key : “value”,

Key : “value”

So in practice:

author: "David M Berry",

//Key : “value”,

Or

date: "2011",

//Key : “value”,

How Do You Structure an Object?

To create an object, you give it a name that tells you what kind of information is going to be in the container. For this example, because we’re using information that will be in a book, let’s call it “book”.

var book = {

Then you place an equals sign and a curly bracket next to the name. On the next line, you start placing the different key/value lines that belong to that object.

 title: "The Philosophy of Software; Code and Mediation in the Digital Age",

author: "David M Berry",

publisher: "Palgrave",

date: "2011",

pages: 200

When you’re done listing, you put a closing curly bracket and a semicolon.

};

So all together now:

var book = {

title: "The Philosophy of Software; Code and Mediation in the Digital Age",

author: "David M Berry",

publisher: "Palgrave",

date: "2011",

pages: 200

};

How can we Use Objects?

You can use objects by calling on a key to get its value. Basically what that means is you can write a bit of code that tells your programme to find a particular object, then look for a particular key, and then give you the value.

For example, using our book object from above, if you wanted the programme to tell you what the title of the book is, you’d write:

book.date;

What it translates to is this:

object.key;

And what the computer sees is this:

Look for the object called “book” and the key called “date” and tell the user the value next to “date”, which in this case is “2011”.

So the computer will give you the value “2011”.

Another option you have is to use square brackets around your key value. This is super useful when you want to get a value dynamically.

book["date"]; //returns 2011

Exercise!

Copy the contents of 01_js.html into index.html, read through the code, see the results on the screen and make the suggested changes.

What are Operators?

JavaScript operators are used to perform actions such as multiplying or dividing. Basically what we tell the computer to let it know what kind of computing it needs to do.

Some of the operators are:

Arithmetic - The ones for maths

Name Function Example
Add + e.g. 1 + 1; // 2
Subtract - e.g. 7 - 3; //4
Multiply * e.g. 2 * 2; // 4
Divide / e.g. 8 / 5; // 1.6
Modulus % e.g. 12 % 5; // 2 (it is the remainder of a division)
Incriment ++
Decriment --

Assigment - The ones that tell the computer which variables mean which values

Example Outcome
var x = 5; // the value in x is 5;
var y = 12 //the value in y is 12;
var z = x + y //the value in z is 17;

Comparison - The ones that compare different values

Example data set

var x = 12;

var y = 10;

var z = 12;

var a = "12";

Equality Operator

x == y; //false x == z; //true x == a; //true

Strict equality operator (===)

x === a; //False

Inequality operator (!==)

x != y; //true

x != z; //false

x != a; //false

x !== a; //true

What are Functions?

What Are Functions?

Functions are small enclosed sections of code that do something specific. They can perform an action or return a value.

How do we write JavaScript Functions?

There a few different ways to write functions in JavaScript. One way is to do this:

This example starts by using the function keyword or function declaration, which is what you say to let the computer know it’s a function.

function

Then, you write the function name. In this case, it’s the add function, and you can use that name so you can call the function in your code.

function add

After that, you write the arguments. These are values that you can pass to the function that it can use.

function add(a, b){

Keep in mind that a function doesn't need to have arguments, if there aren't any you just have empty smooth braces.

function()

So now we’ve told the computer to open a function. To actually write what we need to do, we need to use curly braces to open the body of the function and close it again. The code carried out by the function is between these braces.

function add(a, b){

   var c = a + b;

   return c;
   
}

This function returns a value based on what you asked it to do. In this case, we asked it to add “a” and “b”. When you call this function, you have to assign a new variable to the answer it gives you. Here, we used “c”. What that basically amounts to is just telling the function that “a” + “b” = c

  var c = a + b;

   return c;

However, before we finish up here, we need to know what a and b stand for. In order to tell the computer what it even needs to be adding, we write what the variables are in this format. The numbers in the brackets correspond to the letters a and b, so a = 7 and b = 8

var addUp = add(7,8);

So all together now, the full calling of the function looks like this:

var addUp = add(7,8);

function add(a, b){

   var c = a + b;

   return c;
   
}

What are Arrow Functions?

Arrow functions were introduced in ES6. They are basically a more compact way of writing anonymous functions. Anonymous functions are functions which do not have a specific identifier. They can only be called once or a limited amount of times, and are used as part of larger functions.

var add = function(x, y) {

  return x * y;

};

Instead of writing that, we can write it much more simply using ES6

// ES6
const add = (x, y) => { return x * y };

What is console.log()?

What is console.log()?

console.log(); is a JavaScript function that prints whatever is inside the brackets on the Javascript console. The Javascript console is one of the development tools on websites and browsers (See Joel’s lecture from week one for notes on how to access it). You can print a lot of things with console.log, including text, number or an array.

Why do we use console.log()?

Console log is really useful when developing an application because you can use it to check if a function is working properly.

When you write the console.log() command under a function, if the function is working, it will send you a specific message that you can see on the JavaScript Console.

For example, you can write this in your code:

     function log(){

        console.log('this is a console log');

      } 

And when you go into the JavaScript console, if the function is working, you should be able to see the message:

this is a console log

You can also use it to call numbers. So for example, if you called this function, you could console log the return value that is stored in the variable addUp:

//function

let addUp = add(12,3);

//console.log()

console.log(addUp);

In the console you should be able to see the return value of the addUp, so 15.

You can also chain link things in the console, which is also called concatenation. This means you can ask the console log to tell you what you are seeing For example, instead of just writing a number with no context for the previous example, you can ask:

console.log("This is the return value of addUp(12, 3) " + addUp);

And receive the result:

This is the return value of addUp(12, 3) 15

What is Scope?

The scope of an element is where the code can access, see, and use that element. So for example, if you create a variable inside a function, that variable only works inside that function, and if you try to use it outside that specific function, you will get an error message.

function num(){

  var x = 5;

  console.log(x); 

}

So in this example, x = 5 only works inside this num() function.

If you create a variable without the var keyword it becomes a global variable. This can also cause an error because other code that you thought was out of the scope of that variable could change it.

So when you write a function, these two x variables are different. The computer might override the x = 5 variable below with an x = 10 variable because it thinks it’s the same thing.

var x = 10;

function num(){

  var x = 5;

  console.log(x); 

}

console.log(x); //10

console.log(num());

Exercise!

Copy the contents of 02_functions.html into index.html, read through the code, see the results on the screen and make the suggested changes.

#Expressions and Statements

Expressions are any piece of code that the computer can use to return a value to you. For example:

10;

23 + 109;

"Hello";

"Hello " + "there";

9 < 10; //This evaluates to true as 9 is less than 10

A statement is code to perform an action, such as creating a variable or function. It's when you are asking for something to happen.

You should add a semi colon at the end of a statement, like in these examples;

var temp = 10;

add(325, 21);  

Conditional Statements

In JavaScript, code can be executed in different ways. For example, it can be activated when someone clicks on an HTML element on a website. It can also be activated when a particular thing happens, for example if a certain value is equal to another. To let the code know what it should do when it finds these certain values, we have to use conditional statements.

How do we Use Conditional Statements?

There are different types of conditional statements including if statements, if/else statements and if/else, else statements.

Conditional statements basically just tell the computer what to print/do/say when it reaches a certain value.

For example:

var day = "Wednesday";

if(day === "Sunday"){
  console.log("Happy " + day);
} 

There would be nothing logged to the console because the code sees that the day is equal to Wednesday, not Sunday.

However, we don’t have to write an entirely new conditional statement for every match or mismatch, that would take forever. Instead, we can use else statements. After the first conditional statement tells the computer what it’s meant to match, these tell the computer what to print/do/say if it doesn’t match.

For example:

if(day === "Sunday"){
  console.log("Happy Sunday");
} else {
  console.log("Today is not Sunday, happy " + day);
} 

Like the code we had before, the day is still Wednesday. So using this else statement, the console log would write “today is not Sunday, happy Wednesday”

You can do something similar with a chain of else statements. These are statements which you can write to introduce multiple different instructions to one conditional statement. If there is more than one alternative, so more than one else, you should write else if;

For example:

if(day === "Sunday"){
  console.log("Happy Sunday");
} else if (day === "Saturday"){
  console.log("Yay its Saturday");
} else {
  console.log("It's not the weekend yet");
}

For this chain of else statements, we first asked the computer to check if the day was Sunday and if it was, to print “Happy Sunday”. Next, we added an else if statement that told the computer to check if it was Saturday. If it was, we told it to print out “ Yay, it’s Saturday!” Lastly, we added an else statement that tells the computer if there’s any other value than Saturday or Sunday, print “It’s not the weekend yet”.

How do we use Syntax in Conditional Statements?

There are three ways to use equals signs, and they all mean different things.

When you use one equals sign, you assign a value to a variable:

var day = "Wednesday";

When you use two equals signs, you are asking if the value is equal. So in this case, both of these values are 12, even though one is a number and one is a string.

var z = 12;
var a = “12”;
Z == a //true

When you use three equals signs, you are asking if the value and the type is equal. So in this case, these two statements are not equal because even though they are the same number, they are different types.

var z = 12;
var a = “12”;
z === a //false

How do we Check Values in Conditional Statements?

You can also check more than one value in a single line. For example, you could check if it's the week or the weekend by using the || symbol between two values.

if(day === "Saturday" || day === "Sunday"){
  console.log("It's the weekend, its " + day);
} else {
  console.log("It's a weekend day, its " + day);
}

You can also use && to check if the day has two values, for example if a day of the week is both Saturday and sunny.

You can also use !== to check if one value doesn't equal another.

You can also check if a value is greater than >, less than <, greater or equal to >==, or less than or equal to <==, for example:

var x = 14;

if (x < 14){  //In this case false
console.log(x); //This wouldn't be printed to the console.
}

if (x > 14){ //In this case false
  console.log(x); //This wouldn't be printed to the console.
}

if( x <= 14){ //This is true
  console.log(x); //14 will be printed to the console
}

if( x >= 14){ //This is true
  console.log(x); //14 will be printed to the console
}

In these cases, because the console.log is instructed to print (x), it only prints x if it is true.

Loops

Loops are commands you can use when you want a function to keep going until you reach a certain value. The loop will keep looping until a condition becomes true or false. This can be useful to create a counter or to check through an array.

In JavaScript there are two kinds of loops: for loops and while loops.

For Loops

In a for loop, the loop starts with the “for” function. In the example below, there are three arguments in the function var i = 0, i < 10, and i++.

for(var i = 0; i < 10; i++){

  console.log(i); //the console will write 10 lines from 0 to 9

}

What this means is that there is an original variable value: var i = 0.

Then there is a boolean (true or false) condition that checks if i is less than 10: i < 10.

Then there is a command which adds 1 to the value of the variable “i” every time the loop runs: i++.

This means that the loop starts counting “i” the first time it runs, and then it adds one and checks if i is less than 10. The loop keeps adding 1 until “i” becomes 10, and every time the loop runs, it prints the new “i” value (so, 1, 2, 3, 4, 5, 6, 7, 8, 9)

While Loops

While loops work with a similar principle. The types of loops are used specifically for when we don’t know how long the loop will go on for.

var x = 0;

while( x < 10){

  console.log(x);

  x++;

}

https://techdifferences.com/differenece-between-for-and-while-loop.html

Exercise!

Copy the contents of 03_loops_conditionals.html into index.html, read through the code, see the results on the screen and make the suggested changes.

Indira’s Coding Tips

  1. Write small pieces and test them frequently. If something isn't working, comment out the code and bring it back in line by line to see where the problem is.
  2. Remember to simplify and check
  3. Usually, if your code is really complicated, it’s probably the wrong solution
  4. Think about how you would write something without code. What is the logical progression of what you are trying to do? Once you have the logic, it’s easy to find the right syntax to learn it.
  5. Take breaks!!! If something isn’t working, take a breath and come back to it later
  6. Don’t be afraid to use sites like Stack Overflow, Mozilla, or P5.js tips. You won’t be able to remember everything, and there’s a huge community of coders out there who have written things to help you.
  7. Get a good list of resources you like to check and use those. One problem with finding answers on the internet is that they are not always right.

Examples

Awwwards - Good animation examples

The Carbonation

1917 Film Site

Jam3

Star particles

A tutorial to make the stars

100,000 stars

The making of 100,000 stars

Particles

Some JavaScript Libraries

3D - Three.js

3D - Babylon.js

2D Animation simple components - mo.js

SVG Animation - Vivus

2D Animation - Greensocks

Data Visualistions - D3.js

References

JavaScript basics

How JavaScript is executed

JavaScript intro

Stack overflow

Arrow functions