14/October - Basic knowledge of Javascript

js-vscode-image

Preparations


Class Curriculum

Section content Expected time (mins) Pre - Requirements
Lesson Agenda and Goals 5 minutes ❌
Live demo on basic JS 45 minutes Preparations section
Review of the Activity task as a whole class 10 minutes ❌
Class break 10 minutes ❌
JS Activity (in smaller groups) 45-60 minutes VsCode and Git installed

Lesson Goal

To gain familiarity with what JavaScript is, what it can do, and how it fits into a web site.

Hint about using code snippets

Code snippets look like the box below. Please note that the full contents of the snippet are hidden if there's a lot of code. In this case, please click on the 3 dots at the bottom-left of the box to expand it and see the full code.

 1/*
 2This code snippet
 3is
 4
 5
 6
 7
 8
 9
10
11
12
13
14HUGE!!
15*/

Javascript - What is it?

JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else. (Okay, not everything, but it is amazing what you can achieve with a few lines of JavaScript code. Here is a PacMan game you can play using your webcam, a 3D home design website and a cool 3D demo of a ball in water, all of which are made using mostly JavaScript and push the edges of what you can do in your browser with JavaScript) It is the third layer of the layer cake of standard web technologies.

web-tech-cake

  • JavaScript is a lightweight interpreted programming language.
  • JavaScript can both be used as a client-side and server-side programming language. This means it can run on your browser on your desktop or mobile device and can also run inside "Node" on a web server.
  • JavaScript is an untyped programming language. This means you don't need to specify the type of a variable when you declare it but it is understood based on the value you assign to the variable.
1<p>Player 1: Chris</p>
1p {
2  font-family: 'helvetica neue', helvetica, sans-serif;
3  text-align: center;
4  border: 2px solid rgba(0,0,200,0.6);
5  color: rgba(0,0,200,0.6);
6  display: inline-block;
7  cursor: pointer;
8}
1const para = document.querySelector('p');
2
3para.addEventListener('click', updateName);
4
5function updateName() {
6  let name = prompt('Enter a new name');
7  para.textContent = 'Player 1: ' + name;
8}

What can JavaScript do

js-execution

The core client-side JavaScript language consists of some common programming features that allow you to do things like:

  1. Store useful values inside variables.

  2. Operate on text pieces to form new text pieces

  3. Running code in response to certain events occurring on a web page.

  4. Dynamically modify HTML and CSS to update a web page ( with the DOM API)

  5. Retrieves geographical information ( with the Geolocation API )

  6. Create animated 2D and 3D graphics (with the Canvas and WebGL APIs)

  7. Play audio and video right in a web page, create audio and video calls ( with the Audio and Video APIs like HTMLMediaElement and WebRTC)

  8. And much,much more!

How do you add JavaScript to your page

There are typically 3 ways we do that to include JS in a HTML Page ( just like CSS):

  1. Inline JS. This is typically not used or should not be used because it makes your HTML harder to read and maintain (and it goes against the principle of separation of concerns - HTML should just dictate your page structure and should be contained in the .html files, while the JavaScript code which makes it dynamic should be in separate .js files)
1<!--Here the onclick="..." part is JavaScript and it is embedded in the HTML-->
2<button onclick="javascript:alert('You clicked me!')">Click me!</button>
  1. Internal JS. This is similar to using a style tag in the case of Internal CSS. The position of the script tag is important as it determines when the JavaScript code is executed.
1<head>  
2    <script>
3        let counter = 1;
4        counter++;
5        alert("Counter is now:", counter);
6    </script>
7</head>
  1. External JS. Here the JavaScript code is written in a separate file with the extension .js
1<head>  
2    <script src="script.js" defer></script>
3    <script src="script-independent.js" async></script>
4</head>

Ways of loading JS scripts

  1. If your scripts should be run immediately and they don't have any dependencies, then use async.
  2. If your scripts need to wait for parsing and depend on other scripts and/or the DOM being in place, load them using defer and put their corresponding <script> elements in the order you want the browser to execute them.

Basic JS Guide

Functions

JavaScript functions are named pieces of code which can be used to achieve a particular functionality. For example, in order to show up a pop-up with the text Hello World!, the following snippet of code can be used

1alert('Hello World!');

Here alert is a function or piece of code available when you use JavaScript in a normal browser window. A function is called or executed by adding an opening and closing parantheses () after the name of the function. If the function takes any parameters, those are specified between the parantheses. Calling a function could change the state of the system (e.g. show a pop-up using alert) or simply return a value (e.g. return a random number between 0 and 1 in the case of Math.random).

You can also define your own functions to achieve some functionality and to be able to reuse this functionality. You can define a function as follows:

1function name(parameter1, parameter2, parameter3) {
2    console.log(parameter1);
3}

The above function only prints a message in the JavaScript console. You can also create functions which return a value, you can use the return keyword. For example, the below piece of code returns the sum of the parameters passed to the function.

1// Function definition
2function sum(a, b) {
3    return a + b;
4}
5
6// Calling the function and printing the value.
7// This statement should print the value 8
8console.log(sum(3,5));

Variables

Variables are named memory locations where you can store some data. Think of variables as similar to labeled boxes which can store data.

Variables can be declared using the let or var keywords. The difference between the two is where the declared variable remains accessible or valid. A variable declared using var can be accessed anywhere in the program. However the validity or accessibility of a variable declared using let is limited to the scope (between the curly brackets) where it is defined.

If the value of a variable does not need to change once it's assigned, you can use the const keyword to declare the variable.

1var name = "JavaScript" 
2const PI = 3.14
3let lastName = "Language"

There are several reasons you might want to use variables:

  • To store the result of any function call whose value changes each time you call it (e.g. Date() or Math.random()).
  • To make your code readable by splitting long statements. This is illustrated with an example below
1// Long and hard to read
2console.log(document.getElementById('element').value);
3
4// Easier to read and debug if something goes wrong
5const element = document.getElementById('element');
6const value = element.value;
7console.log(value);
  • To avoid having to call the same function many times. Calling a function is expensive (i.e. it takes time to execute) but getting the value stored in a variable is cheap.

Data Types

Variables can contain different types of values and data types. Below is a code snippet showing the simple or primitive types

 1// Any type of numerical data belongs to the Number data type
 2let age = 23;
 3let percentage = 30.5;
 4let loss = -10.0;
 5// Any textual data is stored as a String data type
 6// Strings can be defined by putting the text between single or double quotes
 7let name = "John Doe";
 8let other = 'Jane Doe';
 9// Booleans store true or false values.
10// They are useful to make decisions in your code
11let isMale = true;
12// undefined is a type used to indicate that the variable is not defined
13let iAmNotDefiningThis;
14// The above variable will have the data type undefined since we did not assign a value
15// Undefined can also be assigned explicitly
16let explicitUndefined = undefined;

Apart from the above, there is an Object type which can be used to store more interesting data. There are primarily two sub-types which are interesting to us: Arrays and Objects.

Arrays can be used to store ordered lists of any primitive data types. Let's say you want to store the names of the top 5 largest countries in the world, in the order of their size. An array is the perfect data type for this use case.

1countries = ['Russia', 'Canada', 'China', 'United States', 'Brazil'];

The advantage of an array is that it also let's you access the value stored at a particular location. The only catch is that the numbering starts at 0, not at 1. So to access the value stored at the 1st location, use 0, for the 2nd location use 1 and so on. Accessing the values in an array by their position or index is called array indexing. You can perform array indexing by using the name of the array, followed by the required index in square brackets []. For the above example, the below code snippet demonstrates how you can do array indexing

1console.log(countries[0]); // Prints Russia
2console.log(countries[1]); // Prints Canada
3console.log(countries[2]); // Prints China
4console.log(countries[3]); // Prints United States
5console.log(countries[4]); // Prints Brazil

Objects can be used to group information relevant to a single real-life entity in the code. For example, let's say you want to store the details of a person in the code. The below code snippet shows how you can do this using objects and compares it to the alternative.

 1// Approach 1: Without objects
 2var name = 'John Doe';
 3var age = 45;
 4var address = '21 Elm Street, 5201 London, UK'
 5
 6// Approach 2: With objects
 7var person = {
 8    'name': 'John Doe',
 9    'age': 45,
10    'address': '21 Elm Street, 5201 London, UK'
11}
12
13// There are two ways to access the values stored in an object
14// The first is to specify the property you are trying to access between []
15// This way of accessing properties is called the Bracket notation
16console.log(person['name']);
17
18// The second is to specify the property you are trying to access using a .
19// This way of accessing properties is called the Dot notation
20console.log(person.age)

As can be seen above, holding the data in objects makes it easier to define and access this data.

Operators

If you have variables, you can use them to perform different kinds of operations. To do so, you need operators.

Basic

1+ β€” //Addition
2- β€” //Subtraction
3* β€” Multiplication
4/ β€” Division
5(...) β€” Grouping operator, operations within brackets are executed earlier than those outside
6% β€” Modulus (remainder )
7++ β€” Increment numbers, i.e. increase the value by 1
8-- β€” Decrement numbers, i.e. decrease the value by 1

Comparison

== β€” Equal to (e.g. 3 == "3")
=== β€” Equal value and equal type (e.g. 3 === 3)
!= β€” Not equal (e.g. 3 != "4")
!== β€” Not equal value or not equal type (e.g. 3 !== "3")
> β€” Greater than (e.g. 4 > 3)
< β€” Less than (e.g. 3 < 4)
>= β€” Greater than or equal to (e.g. 3 >= 3)
<= β€” Less than or equal to (e.g. 3 <= 3)
? β€” Ternary operator

Logical

&& β€” Logical and
|| β€” Logical or
! β€” Logical not

Comments

1/*
2    Comments are important because they help other people understand 
3    what is going on in your code.
4    We already used a lot of comments in the examples above.
5    Go back and try to identify them ;)
6    This is a multi line comment
7*/
8
9// This is a single line comment

If...else statement

Let's say you have to ask an input from the user and show a pop-up window which says "Equal to 50", "Less than 50" or "Greater than 50" depending on the value entered by the user. This requires making a decision based on the value entered by the user. This is where you can use an if...else statement.

A simple if statement is shown below. The condition can be a variable or any expression which is a boolean data type. The code inside the curly braces is evaluated only if the value of the boolean expression is true.

 1if (condition) {
 2    // code goes here
 3}
 4
 5// Below are some examples of valid Boolean expressions
 6x === 50
 7x < 50
 8x > 50
 9x != 50
10
11// Below is a complete if statement with some code
12if (x === 50) {
13    // You can put any code here which should execute if x is equal to 50
14    console.log("Equal");
15}

If there is a situation where you want to execute some code when the condition is true and some other code when the condition is false, you can use an if...else statement, which is demonstrated below

1if (x === 50) {
2    // You can put any code here which should execute if x is equal to 50
3    console.log("Equal");
4} else {
5    // You can put any code here which should execute if x is not equal to 50
6    console.log("Not Equal");
7}

If there are multiple different conditions you need to evaluate and execute code accordingly, you can use the if...else if...else construct

1if (x === 50) {
2    console.log("Value and type are equal");
3} else if (x == 50) {
4    console.log("Value is equal");
5} else {
6    console.log("Neither value nor type are equal");
7}

The code snippet below shows how the scenario mentioned earlier can be coded.

 1/* prompt is a function which shows a pop-up asking for user input
 2The parameter passed to the function is the message displayed on the pop-up */
 3var userInput = prompt("Enter a number");
 4
 5/* The output from the prompt function is a String
 6To convert it to a Number, you can just pass it as a parameter to Number() */
 7var num = Number(userInput);
 8
 9/* An if statement 
10*/
11if (num === 50) {
12    alert("Equal to 50");
13} else if (num < 50) {
14    alert("Less than 50");
15} else {
16    alert("Greater than 50");
17}

Events

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.

An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

  • An HTML web page has finished loading
  • An HTML input field was changed
  • An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

You can specify what code to execute by using the addEventListener method of an element. The below snippet shows how to handle a click event on a button to show a popup. The first parameter to addEventListener is the type of event. Here since we want to respond to someone clicking on the button, the event type is click. The second parameter is the actual code to execute. This could be provided as a function declaration inline or as the name of a function declared elsewhere. The code or function which is called is referred to as the event handler, since it handles the event in some way.

1<input type="button" id="show_popup">Show popup</input>
 1var btn = document.getElementById('show_popup');
 2btn.addEventListener("click", function() {
 3    alert("Here's a popup");
 4});
 5
 6// Alternative way of specifying the event handler
 7btn.addEventListener("click", showPopup);
 8
 9function showPopup() {
10    alert("Here's a popup");
11}

Activity

Try to create the guessing game mentioned in this link. You can fork the code on this repo to get started.

Extra resources

Next class preparation

Practical lesson JS