# Welcome

This page is still a WIP, but feel free to jump straight in to the [JavaScript course](/html/intro-to-js).


# The Basics

What is HTML?

Hyper-Text Markup Language (HTML) is one of the main languages of the web. The main one, even.

HTML is what Web Browsers (like Google Chrome, or Safari) use to build and display web pages to us. HTML is stored in files and are composed of a number of "tags". These tags tell the browser what to do with the information inside the tags, and what sort of information it is. According to the [HTML Specification](https://www.w3.org/TR/html52/), a basic "valid" HTML document might look something like this:

```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
</head>
<body>
  
</body>
</html>
```

This will display a blank page, which isn't too exciting, but there is still a bit going on here which we will explore more in the following pages. For now, the important thing to take note of is the tags. A tag is essentially anything wrapped in angled brackets (`<>`).

There are two types of tags. Normal Tags, and Self Closing Tags.

A normal tag is one in which there is an opening and closing tag, like this

```
<title>Document</title>
```

{% hint style="info" %}
This Tag tells the browser what the title of our page is, which then gets displayed on the tab in the browser
{% endhint %}

This is a `title` tag, as we can see from the name in between the angled brackets. The first part (`<title>`) opens the tag, and the second part (`</title>`) closes the tag. Everything in between is the content (in this case, the word `Document`)

The other kind of tag is Self Closing tags. These are ones which fulfil whatever their role is without content, and so simply exclude it. The do not have a closing tag, because they self terminate, like so:

```
<meta charset="UTF-8" />
```

{% hint style="info" %}
This Tag tells the browser what our character-set encoding is, so that it can display our text correctly.
{% endhint %}

We will explore more about tags and their role in web development in the coming pages.


# Getting Started

Intro to JavaScript

## JavaScript?

JavaScript (JS) is traditionally regarded as the language of the Web. Pretty much all browsers support JavaScript to varying (extensive) degrees. As it stands, [more than 94 percent](https://torquemag.io/2018/06/why-millions-of-developers-use-javascript-for-web-application-development/) of sites on the internet utilise JS in some form. That's a lot of JavaScript.

Over 10 million developers worldwide use JS, making it the most popular programming language worldwide at the moment.

## Step 0

Before we get properly down to business, it is important to clarify a few terms. The two main things that you will need in order to follow along with this content is a *browser* and an *editor*.

A (web) browser is an application which allows you to navigate the internet. You supply an address, and a *server* will send your browser the files needed to render the webpage you requested. For this workshop, I suggest sticking with [Google Chrome](https://chrome.google.com)

You can also write and edit your own files for the browser to render, which is where the editor comes in. a Code Editor is an application not too different from a word processor, but instead of being focused on typesetting, code editors instead provide tools to help you write code for computers to interpret.

In this case, we will use [Brackets](http://brackets.io/)

## Step 1 - The web page

We are going to start things off by making a folder to keep your work in. You can do this on the desktop or anywhere else that makes sense for you.

Open up your code editor (Brackets), and add the folder that you just created `File > Open Folder`

Next up, make a file called index.html inside the folder (right click inside the folder, and select `New File`)

You are going to need to add the following markup into the document. This will act as the scaffolding of your web page.

```
<html>
    <head>
        <title>My First web page</title>
    </head>
    <body>
        <h1>my heading</h1>
        <p>My paragraph</p>
    </body>
</html>
```

### 🤔 What is happening here?

> Web pages are made up of a few different types of file. the most common ones which you will find in almost every site are Hyper Text Markup Language (HTML), Cascading Style Sheets (CSS), and JavaScript (JS).
>
> The above snippet is HTML, and it consists of a number of `tags` used to "markup" the text. The tags indicate to the browser what type of content the contained text is. For example, our `h1` tag tells the browser that we are dealing with a Level 1 Heading, and the `p` tag indicates that we are working with a paragraph. The current HTML5 standard includes around 150 tags, but a lot of them are very niche, and you certainly don't need to remember each and every one. For a good reference about different tags, [look here](https://www.w3schools.com/html/html_elements.asp)

## Step 2 - The good stuff, JavaScript

Now we are going to add some actual code to make magic happen. To do this we are going to need to add a script to our web page. The easiest way to do this is to add a new tag into the body of your HTML document. After your `p` tag, but before the closing `body` tag, add the following:

```
<script>
    console.log('Oh look, some JavaScript');
</script>
```

When the browser reaches a `script` tag, it will run all the code contained within before continuing on. Because of this, we tend to put the script tags at the bottom of the page most of the time, so that they won't slow down the loading of the page too much.

### ⚡️ console.log

> console.log is a function which tells the browser to display some information in the dev tools console. this is super hand for debugging issues and check whats what as you write your code. To see the fruits of you labour, right click somewhere on your page, and select `inspect`. In the new window that pops up, go to the `console` tab, and you should see the output of your script.

Console logging is all well and good, but it is more for developers and debugging. Most of your users won't see it. lets do something that the users will actually be able to see. replace your `console.log` with `alert` so that the contents of your script tag reads like

```
alert('Oh look, some JavaScript');
```

and then save and reload your page.

## External script files

As you start writing more and more code, you will want to keep it in separate files so that everything stays tidy. This also has the benefit of keeping your code separate from your markup, and letting you reuse the same code in multiple different pages without having to rewrite it each time.

Lets do this now.

make a new file in your folder called `script.js` and move the contents of your script tag into this file.

You will now have an empty script tag in your html file, and we are going to change it so that it load the content of external file. Change your pair of script tags to be like this:

```
<script src="script.js"></script>
```

Now when you save and refresh, everything should still be exactly the same. Good.

## Comments

Comments allow us to write lines which will be ignored by the computer. This might sound weird, but it can actually be very useful. A lot of time spent coding is actually spent reading other people's code, and having comments can help explain what is happening, and why. Think of it like sticky notes for your code.

There are two kinds of comment in JS

```
// Single line comments which start with a double slash
```

and

```
/*

Multiline comments, which allow you to write blocks of comment without having to put slashes at the start of every line.

This can be handy for writing explanations and documentation, or for temporarily stopping certain blocks of code from running while your are debugging.

This type of comment is denoted by the slash-asterisk asterisk-slash seen at the top and bottom of this block.

*/
```

HTML also has comments. they start with `<!--` and end with `-->`

```
<!--  Simply surround the comment with those tags, and it will be ignored by the browser -->
```


# The Basics

This section will provide you with the fundamental knowledge you need in order to work through the rest of this content. We will cover the fundamentals of JavaScript, giving you the tools you need to build your own applications.


# Values

Values are the raw data of your application. A value is a representation of an entity, which the program can manipulate. They are generally atomic units of data, but in some cases can be more complex, and even composed of other values.

There are multiple different sorts of values, and they are differentiated by what is known as a `type`. Examples of common types are:

### Strings

A string is a piece of text. Strings are denoted by words wrapped in quote marks. In Javascript, you can use three different kinds of quote marks

#### Single Quotes & Double Quotes

strings wrapped in `'single quotes'` and `"double quotes"` have not special behaviour to them and ultimately the choice between them comes down to the situation at hand, and style preferences

#### Backquotes

strings wrapped in backquotes have special behaviour in JavaScript in that they allow you to inject other values or [variables](/javascript/js-basics/variables) into your strings by wrapping them with `${}`. This is called a template string and it looks like this:

```
var myVariable = 'This is some text which I can inject';
var templateString = `My text is: ${myVariable}`;
```

### Numbers

#### Integers

Integers are full numbers with no decimals places

#### Floats

Floats are numbers with a decimal place, followed by a fraction. Floats are used when more precision is required

### Booleans

Boolean values are those which are either `true` or `false`. They are binary, and are often used for [conditional statements](/javascript/js-basics/conditional-statements)

### Arrays

an array is basically a list of other values. Arrays are denoted by the square brackets which surround them. the items in an array can be of any type, like so `['some text', 1, 2, 3.14, 'some more text']`. The comma separates each of the items, so in this case, the array contains 5 items.

### Objects

an Object is a collection of properties, where a property is an association between a name (or key) and a corresponding value. for example, consider the following: `{ myKey: 'my Value' }`. The values can be of any type, such as the ones listed above here. There are some limitations around what you can use as a key, but generally speaking if you stick with a short, descriptive (of the purpose of the value) word, You will generally do okay.

###


# Variables

Variables are an important part of programming. They let as give a name to values, which makes code easier to understand, easier to write, and easier to reuse.

There are a few different types of variables which we can create and they are all similar, but have some distinct differences.

### Var

The first (and oldest) type of variable we can make are those defined with the `var` keyword. These variables get hoisted. Hoisting is JavaScript's default behaviour of moving all declarations to the top of the current scope (to the top of the current script or the current function). This means that the following code will work

```
x = 5; // Assign 5 to x

console.log(x) // use the value inside x

var x; // Declare x
```

### Let

Variables defined with the `let` keyword will work almost the same as `var` but they will not be hoisted, so the following will NOT work.

```
y = 5; // Assign 5

console.log(y) // use the value inside

let y; // Declare
```

This will throw an error like `Uncaught ReferenceError: Cannot access 'y' before initialization`

Even though it may seem odd, this is generally preferred behaviour, because it forces the dev to write more deliberate, thoughtful code. Being able to use variables before you declare them can make things confusing and hard to debug.

### Const

Variables defined with `const` are called "constants" and just like those declared with `let` , they are NOT  hoisted. They also have another behaviour, which is that they cannot be reassigned. Once the variable has been declared, the value stored inside it cannot be replaced. Again, this might seem like odd restrictive behaviour, but it is also often desired - more often than not.

Having a built in guarantee that your values aren't going to get replaced somewhere in the code is sort of like a comforting safety net, and removes something which you might otherwise have to worry about when working with less strict variables. You can always declare more variables if you need to, there is rarely a need to reassign an existing one, but when there is, we can always use `let`.


# Functions

A function is a named block of code that performs a specific task as described by its name. They can take inputs (called *arguments*) and return a value. Sometimes they won't return a value though and that's okay. If a function doesn't return a value, we say that it "returns void" or "is void".

The value returned by a function can be assigned to a variable, and used by other bits of code.

`console.log` is a function. It writes some data to the console, but doesn't return a value for us to use, so it returns void

You can make your own functions too, like this:

```
function doubleNumber(number) {
    var doubled = number * 2;
    return doubled;
}

var myNumber = doubleNumber(4);

alert(myNumber);
```

In the above example, we have created a function called `doubleNumber`. The name is arbitrary, we could have named it whatever we want, but generally speaking it is a good idea to name the functions something sensible which clearly describes what the code inside will be doing. In this case it will be returning 2 times the value provided as an argument, so `doubleNumber` is a simple, appropriate name.

Our function also takes an argument. The argument name is also arbitrary, and we could have named it whatever we want as well. In this case, I have called it `number` for simplicity. The most important thing when naming variables and functions is that their purpose and usage can be accurately guessed by someone else reading the code, just by looking at the name.

When we define a function, the function gets assigned to a variable with the same name as the function. There is an important distinction to make here. Using the above function as an example, if we use `console.log` to examine it, look at what happens.

```
console.log(doubleNumber)
ƒ doubleNumber(number) {
    var doubled = number * 2;
    return doubled;
}
```

Because we have passed in the *variable* containing the function, `console.log` is showing us the definition of the function. It shows us what the variable contains, but it does not execute or "call" the function.

If we want to call the function, we need to suffix it with parenthesis and pass in a value for any arguments we have defined for the function. In this case, we have specified that `doubleNumber` takes a single argument, so in order to call it and get a value back we can do something like this:

```
const newNumber = doubleNumber(4);
console.log(newNumber); // this will output 8
```

#### Summary:

* Defining a function creates a variable containing our code
* To call the function, we need to use the variable name suffixed with a pair of parenthesis `()`&#x20;
  * We can pass any arguments we have specified between these parenthesis
  * Make sure you don't have any spaces or unexpected characters between the function name and the parenthesis

#### [Activity: Greeter Function](/javascript/activities/greeter-function)


# Operators

Operators are a type of construct which represents an action or relationship. We can use them to compare  and modify values. You are already familiar with some of the more common operators, such as the ones commonly used in mathematical expressions.

### Math Operators

* `+` Addition
* `-` Subtraction
* `*` Multiplication
* `/` Division
* `%` Remainder
* `**` Exponent

These work largely the same as their math counterparts, and can be used to combine values into new values resulting from the expressions you write.

```
var sumOfNumbers = 1 + 3;
alert(sumOfNumbers);
```

### Comparison Operators

While the previous operators are used to create and modify values, these ones are used to compare values. The most common ones are:

* `==` Equal to
* `===` Identical to
* `>` Greater than
* `<` Less than
* `>=` Greater than or equal to
* `<=` Less than or equal to

There is an important distinction between `==` and `===` which is that the "equal to" operator essentially only compares that two values are equivalent, while the "identical to" operator checks that the identity of the values is also the same. What this means is that the "identical to" operator also checks the type of the variable.

Because of this, the following occurs:

`"1" == 1; // true` . This is true because the values are equivalent when not considering the types

`"1" === 1; //false` . This is false, because even though the values are equivalent, they are different types (string vs number) so they are not identical


# Conditional Statements

Conditional statements allow you to run a bit of code if a certain condition is satisfied. Conditional statements are an important part of [structured programming](https://en.wikipedia.org/wiki/Structured_programming) and let us make much more dynamic software.

There are a number of [operators](/javascript/js-basics/operators#comparison-operators) that help use make certain conditions, and these conditions will result in a boolean value for us to evaluate.

NOTE: the assignment operator `=` is different to the conditional operator `==`. event though they look similar, the single one is for assigning values, and the double one is for comparing values.

consider the following code:

```
var userAge = window.prompt('How old are you?');

if (userAge >= 18) {
    alert('You are an adult');
} else {
    alert('you are legally a child');
}
```

Conditional statements make use of the if/else keywords to set up control flow.

If the condition inside the parenthesis next to the `if` keyword evaluate to `true`, then that block will run, otherwise the `else` block will run if present (you don't need to include an else block)


# Arrays

An array is like a list. They are good for storing collections of data.

To define an array, we can use square brackets `[]` and place the values we want to include in between the brackets, separated by commas, like so `[1, 2, 3, 4]`

You do not need to include spaces after your commas, but they make things a bit more readable, so i like to include them. You can store any value inside an array, including objects and other arrays. This makes them very powerful for storing data. As with most types in JavaScript, arrays expose a number of builtin function we can use to manipulate the data stored inside them.&#x20;

To call these builtin functions, we can access them like properties on the array.

Here are a few of the common ones.

### forEach

The builtin forEach function will loop over every item in an array, and execute your provided function once for each item. The function will get the item as its first argument.

```
const animals = ['dog', 'cat', 'frog'];
animals.forEach(function(animal) {
    console.log(animal);
});
```

In this example, we are passing in an anonymous function (because we haven't given it a name) and telling it it takes 1 argument (`animal`), because as we know, `forEach` will pass each item in the array into the function. We will now be able to access this item from the `animal` variable.

## Working with arrays

If we have an array of names and we want to get (or replace a specific one) we can target a specific item in the array by using what is called `bracket notation`. consider the following:

```
var names = ['Scott', 'Christina', 'Joel'];
var joelName = names[2];
alert(joelName);
```

NOTE: remember, in programming the first number is always 0, so if you want the 3rd item, that is going to be number 2.

We can also add new items to an array by using the `push` method built in to the array, like so:

```
var animals = ['rabbits', 'cats', 'dogs'];

animals.push('chickens');

console.log(animals);
```

We say that an array is "iterable" because we can "iterate" over it with loops and functions.


# Loops

A loop is a construct which lets us execute the same code multiple times with slightly different parameters each time.

There are two main types of loops.

### While Loop

These loops will run until a condition is no longer met. Be careful with this, as they can run forever!

```
var count = 0;
while(count < 10) {
    console.log(count);
    count = count + 1;
}
```

### For Loops

These loops will run a set number of times, according to the counter declared in the statement

```
for (var i = 0; i < 10; i = i + 1) {
    console.log(i);
}
```

#### 🤔 What is happening here?

> The statement (the bit in between the brackets) has 3 parts. those parts are separated by the semi colons `;`. The first part sets up the counter for the loop, the second part defines the condition for the loop to execute until, and the third part is responsible for iterating the counter at the end of each iteration.

We can use this to iterate through an array, too. for example:

```
var animals = ['Cats', 'Dogs', 'Geese'];

for(var i = 0; i < animals.length; i++) {
    var animal = animals[i];
    if (animal === 'Geese') {
        console.log('I do not love ' + animal);
    } else {
        console.log('I love ' + animal)
    }
}
```

##


# Intro to the DOM

## What is the DOM

> The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can connect to the page. - [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction)

### 😱 Again in English, please.

Basically, we have seen HTML, which is what we write in order to define the *structure* of our page. The DOM is an abstraction of this structure we have defined, presented in a way which programming languages can easily interact with (as Objects, which we looked at last time)

## Working with the DOM

So how do we interface with the DOM? If we can do this, It will allow us to make much more dynamic pages than if we used just HTML and CSS.

Well, in JavaScript (when it is running in a browser) we have a global variable called `document` which exposes the DOM API for us to play with.

> ⚡️ A global variable is basically one which already exists, which all levels of our program can access
>
> ⚡️ An API is an `Application Programming Interface`, and is basically just a set of functionality one system exposes for other systems to use.

If we wanted to get all the paragraph tags in our HTML page, we could use the DOM API to do this by calling the `getElementsByTagName` function.

> 🤓 [Element Finding Example](https://codepen.io/cpave3/pen/poJzJoE?editors=1010)

Now, let's use what we learned here for a little activity:

> 💪 [Element Finding Activity](https://codepen.io/cpave3/pen/QWbWYqb?editors=1010)

There are a number of different functions / methods on the `document` object which we can use to find the DOM node we are looking for. Some common ones are:

* `write("string")` - Writes the given string to the end of the DOM
* `writeln("string")` - Writes the string to the dom and then a newline
* `getElementById()` - Target a node based on its `id` attribute
* `getElementByTagName()` - Target nodes based on their tag
* `getElementsByClassName()` - Target nodes based on their `class` attribute

### Adding Nodes

We can use the DOM API and some of the above functions to maniupulate our `document` and control what the user sees. remember, the role of JavaScript in the web is primarily for adding interaction and logic to pages, which are presented visually by a combination of HTML and CSS.

Because of this, depending on what we want to change, we can manipulat one of these two areas for the desired result. Let's look at an example.

> 🤓 [Node Adding Example](https://codepen.io/cpave3/pen/MWwWoQB?editors=1010)

So what is happening in the above example? You will notice in the HTML on the left, The heading is simple `'My List of …'`, and the unordered list (`<ul id="list"></ul>`) is empty, yet, in the output at the bottom we can see clearly there is more content than we would expect. We are using the DOM API to add content to the HTML document.

In the JS on the right, we define some variables which will act as our content later on.

Then, using the document methods mentioned above, we are able to find specific dom nodes by using their unique `id` attributes. Now that we have the nodes, and the content, we can combine them to add our new content to the page.

Populating the list is a bit more complex, as we need to create new nodes from scratch. We create an `<li>` node, and a text node, and append the text node to the `li` node, and then append the `li` node to the list node. We do this inside of a loop, so that we do it once for each item in our array.

> ⚡️ According to the HTTP spec, only 1 element per page should have a given ID, so they should be unique.

### Removing Nodes

We can also use the DOM API to remove nodes. This is done by calling the `remove()` method on the node we want to remove. Let's take a look at a basic example of this now.

> 🤓 [Node Removal Example](https://codepen.io/cpave3/pen/eYNYEdq?editors=1010)

### Event Listeners

Sometimes you want to trigger some code when a certain event or action happens. We can use event listeners for this. An event listener is essentially a function which will be called whenever a certain event occurs. Check out the following example for the basics of event listeners

> 🤓 [Event Listener Example](https://codepen.io/cpave3/pen/KKpKXra?editors=1010)

### Exercise:

Using what we have learnt in this session, try to make the following A shopping list application, with the following:

* text field for adding items
* button for adding the typed item to the list
* a list for display the items the user has added
* (bonus) add a button to each list item which when click, will delete the item from the list


# Working with the DOM

We looked at the Document Object Model a bit last time, but this is an important part of what we do in JavaScript, so it warrants additional focus.

## Reminder:

[Syntax is important](https://www.w3schools.com/js/js_syntax.asp). Syntax is like the grammar of programming languages. it is the distinct structure that keywords, constructs, values, and variables must be invoked with in order to have a running program.

For example, when calling or invoking a function, you would do something like `myFunction();`. The `()` at the end tell the interpreter that you want to call - as a function - whatever is stored at the variable `myFunction`. If you were to place a space between the two parts like `myFunction ();` you will get an error, as this is a syntax violation.

A lot of it is trial and error early on, but Javascript is pretty forgiving with things like semicolons and commas, which cause a lot of problems in other languages when they are left out.

Thankfully using advanced code editors like Brackets and Visual Studio Code helps solve this problem, because the code editors can highlight these issues to us.

## Styles and CSS

As mentioned previously, Cascading Style Sheets are what give visual styling to our websites. Generally speaking, CSS only changes the visual representation of our content, but without it, our sites look very bland. The power of styling is immense, as CSS has the ability to override the built in rules of HTML when it comes to layout and presentation. this means that with sufficiently advanced CSS, your website may not actually look like what you would expect it to by reading the HTML.

For an example of the power of CSS, check out [CSS Zen Garden](http://www.csszengarden.com). All of these pages have the same HTML, and only the CSS is different, yet they are all visually distinct. CSS is powerful.

While we don't technically need CSS if we focus purely on functional JS, CSS is an important skill to have and understand, so let's take a look at the basics of styling a page.

### Examples

Let's take a look at [An example of some of the things we can do with CSS](https://codepen.io/cpave3/pen/PoqmwJK)

## Manipulating CSS with JS

Now that we can see the power of styling, we can look at controlling these styles with JavaScript. By bringing together visual presentation and logic, we can make some truly cool stuff. Interactions which respond to the user with visual feedback, which is an essential part of the experience in any web app.

[See this example](https://codepen.io/cpave3/pen/ExjmjQW?editors=1111)

## Data Attributes

Data Attributes are special attributes or properties on HTML tags which let us store arbitrary information. This is useful for building dynamic applications because it allows us to bind information to our HTML, which as we know, defines the data and structure of the page. This opens up a whole bunch of opportunities for us.

According to the HTML spec, even though most attributes are defined in the spec and have specific purposes, prefixing an arbitrary attribute with `data-` makes it considered a valid data attribute, and can be used to store information on HTML elements.

We will take a look at some examples of how this can be of benefit.

[See this example](https://codepen.io/cpave3/pen/yLNbojG?editors=1010)

### Activity

Let's use some of what we have gone over today to do the following:

Make a program which does the following:

* From an array of colors, display a list of colors, and store the color name as a data attribute on the dom node
* when the user clicks on one of the colors, get the name of the color from its data attribute
* use the name you got from the above step to change the background-color of the entire HTML document (or a small part of it if you prefer) to the color chosen by the user

Things you will need to use for this (probably):

* event listeners
* creating dom nodes dynamically
* storing data on dom nodes
* manipulating styles with JS


# Activities


# Text Summariser

In this activity we will look at writing a basic text summariser using JavaScript

The goal of this activity is to create a script which will accept a block of text as input and summarise the text based on our algorithm. The algorithm that we will use to do this is outlined below:

1. Break our text into sentences
2. Break out sentences into words
3. filter out stopwords (a starter list of stopwords will be provided)
4. normalise the words
   1. remove any punctuation
   2. make everything lowercase
5. index how many instances of each word we have
6. iterate through the sentences
   1. assign each sentence a base score according to how early it appears in the text (earlier sentences are weighted higher)
   2. add to the base score according to the cumulative scores of all of the words in the sentence (we will use our index for this)
   3. store the sentence and its score
7. fetch the 5 highest scoring sentences
8. display them

This basic algorithm will provide us with a summary of the input text based on how frequently words in the sentence appeared, and how early the sentence occurred.&#x20;

Let's get started 🚀


# Getting the words

Here we will look at what we need to do to break up and filter our words in preparation for scoring

The first thing we will need is some text to play with. For this, I am going to use the text from [www.lipsum.com](https://learning.pavey.dev/javascript/activities/text-summariser/www.lipsum.com) which explains what lorem ipsum is. I will be storing it in a template literal so that I can just paste it in and not have to worry about linebreaks or anything like that.

```javascript
const text = `

What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.

`;
```

Our goal is to take this text and extract a 5 sentence excerpt from it which will give us the gist of the content without needing to read the whole thing. To do this, word frequency will play a big part in determining the "value" of a word (for example "lorem" and "ipsum" will likely occur a lot, and are therefore assumed to be important). Unfortunately, stopwords also occur a lot. We don't want to unfairly rank a sentence based on having a lot of words like "if", "the", "and", etc, so we will need to disregard these. You can use this pre-prepared excerpt to help identify stop words.

```javascript
const stopwords = ['i','me','my','myself','we','our','ours','ourselves','you','your','yours','yourself','yourselves','he','him','his','himself','she','her','hers','herself','it','its','itself','they','them','their','theirs','themselves','what','which','who','whom','this','that','these','those','am','is','are','was','were','be','been','being','have','has','had','having','do','does','did','doing','a','an','the','and','but','if','or','because','as','until','while','of','at','by','for','with','about','against','between','into','through','during','before','after','above','below','to','from','up','down','in','out','on','off','over','under','again','further','then','once','here','there','when','where','why','how','all','any','both','each','few','more','most','other','some','such','no','nor','not','only','own','same','so','than','too','very','s','t','can','will','just','don','should','now'];
```

{% hint style="info" %}
For this exercise, I recommend making an account on [repl.it](https://repl.it) and using that, but if you want to run it in node on your own device that would work too.
{% endhint %}

So to get started, we need to break our text down into sentences and then words and filter out any stopwords. To get the sentences, we can split the text on any common sentence terminators. In the text we are targeting, we are going to assume that a sentence ends with one of `['.', '!', '?']` followed by any amount of whitespace (namely a "space" or "linebreak")

One fairly simple way to do this is with Regular Expressions (Regex). Regular Expressions let us match sequences of text based on a pattern. For the purposes described above, I am going to use this pattern.&#x20;

$$
/(.+?\[.?!]\[\s\r])/mg
$$

{% hint style="info" %}
If you are not familiar with Regex, this might look confusing,  but it should work for now. For a primer on Regular expressions, [check out this link](https://www.regular-expressions.info/quickstart.html). Regexr is also a great resource for playing around and experimenting with different patterns. I use it every time I work with Regex. [Check it out here](https://regexr.com).
{% endhint %}

To use our pattern to extract the sentences, we can use the String function `match` with a provided pattern to get an array of all matching segments. This will look something like this:

```javascript
const sentences = text.match(/(.+?[.?!][\s\r])/mg);
```

We can use this array of words to calculate our "word stems", which will be an index of how often each word appeared in the overall text (which we will use to score how "important" a given sentence is"). Before we can calculate this though, we need to split up the sentences, remove stopwords, and clean up any punctuation. Here is how I did it.

```javascript
const stems = {}; // make an object to store the stems

sentences.forEach((sentence) => {
    const words = sentence.split(' ');
    words
    .map((word) => {
        const cleanedWord = word.match(/([a-zA-Z]+)/);
        return cleanedWord && cleanedWord[0]; // remove any punctuation
    })
    .filter((word) => {
        return word && !stopwords.includes(word); // make sure it isn't a stopword or null
    })
    .forEach((word) => {
        if (stems[word]) {
            stems[word] += 1; // if there is already a stem, increment
        } else {
            stems[word] = 1; // if it is a new word, record it
        }
    });
    
});
```

After this code runs, `stems` should now be an object keyed by each given word, where the values are the number of times each word occurred in the text.

Next up we will look at how to use this object to assign scores to our sentences.


# Ranking the sentences

Using our word stems from the last section, we will give some scores to our sentences

Our next step will be to go through the sentences we have, and give them a score (the higher the score, the more important the sentence) based on how many frequent words they contain. We will also "weight" the scores based on how early in the text the sentence appeared.

To do this, we will need to do some very similar stuff to what we did to compute the stems. In this case, we are going to duplicate some code, which is often regarded as a bad practice, but here it will help us solve the problem simply. After we have the code working we can go back and refactor it.&#x20;

We will define a new array to store the sentences and their scores in, much like how we did with the stems object. After this, we will iterate through the sentences again, this time assigning them an ever decreasing base score according to how early the occur in the text.

&#x20;We can then use the same `map` and `filter` statements from before to clean up our words again, and finally, use a `reduce` function to enumerate the total score for the sentence.

{% hint style="info" %}
the array reduce function in JavaScript will iterate through the array. On each pass, it will carry over the return value from the previous iteration (on the first iteration it will use the second parameter provided to it as a starting point) as well as the current item from the array. this lets us "reduce" arrays of data to a single value (the return value from the final iteration).

In this case, will will "reduce" the array down to the score of all the words in the array.
{% endhint %}

Finally, we will push an object to our new array containing the sentence and its associated score.

```javascript
const ranked = [];

for (index in sentences) {
  const sentence = sentences[index];
  let baseScore = sentences.length - index;

  score = sentence
    .split(' ')
    .map((word) => {
      const cleanedWord = word.match(/([a-zA-Z]+)/);
      return cleanedWord && cleanedWord[0]; // remove any punctuation
    })
    .filter((word) => {
      return word && !stopwords.includes(word); // make sure it isn't a stopword or null
    })
    .reduce((acc, curr) => {
      return acc + stems[curr];
    }, baseScore);

  ranked.push({
    sentance,
    score,
  });
}

```

Now that we have scored each sentence, we will get the `n` highest score sentences and return them as our summary.


# Getting the summary

We will first need to sort our ranked sentences by their score. To do this we can use the array sort method and a fairly common numerical comparator.

```javascript
const sorted = ranked.sort((a, b) => {
  if (a.score < b.score) {
    return 1;
  } else if (a.score > b.score) {
    return -1;
  }
  return 0;
});
```

This will compare the scores and put the entries in the correct order. Once we have done this, all we need to do is take the `n` first items, where `n` is the number of sentences we want, in this case, I will take 5.

```javascript
const top5 = sorted.slice(0, 5);
console.log({ top5 });
```

And with that, you should now have a 5 sentence summary of the block of text you provided as input 🎉


# Greeter Function

An introduction to making your own functions

### Task:

Make a function which accepts a single argument - a person's name - and uses this name to greet them by printing to the console.

For example, I might expect to use the function like this:

```
greetByName('Cameron Pavey');
Hello Cameron Pavey, how are you today?
```

### Bonus:

If the name provided is YOUR name, make it give you a special greeting


# Fizz Buzz

Count from 1 to 50 and print the numbers out:

* If a number is a multiple of three, print ‘Fizz’.
* If it’s a multiple of 5, print ‘Buzz’.
* If it’s a multiple of 3 and 5, print ‘FizzBuzz’.

For everything else, print the number itself. Note: You may wish to use arithmetic operator remainder (%):


# Temperature Converter

In this activity we will look at making an application together, step by step

For this exercise, we are going to make a little application which takes an input value from the user in one of three units of temperature measurement (Celsius, Fahrenheit, or Kelvin) and converts it into one of the other two units of measurement.

Using Codepen (or your own environment, if you'd like) we are going to create the following simple layout

![The basic layout we are going to create](https://395930486-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M135Uv3F0rSbp9rtXKr%2F-M6lQtkX13NMoPCtm_lC%2F-M6lR9aGpLXgmqoKeUA4%2FScreen%20Shot%202020-05-08%20at%209.20.02%20am.png?alt=media\&token=06eaa3ee-3c10-4f11-b382-72d4ba19b38f)

{% hint style="info" %}
While there is nothing stopping you from copying and pasting the code from the examples (except maybe some accidental errors on my part), I highly encourage you to go through and type it out manually, and curiously question every line, to help understand what is going on.
{% endhint %}

### Getting Started

To start things off, we are going to want to put our HTML elements on the screen so that we have something to work with. For the layout I am going to go with, I'm going to put down two input fields, two select boxes, and a button. Let's do that now:

```markup
<div>
  <input type="number" id="from-temp" placeholder="Convert From">
  <select name="from-unit" id="from-unit">
    <option value="c" selected>Celsius</option>
    <option value="f">Fahrenheit</option>
    <option value="k">Kelvin</option>
  </select>
</div>
<div>
  <input type="number" id="to-temp" disabled placeholder="Convert To" >
  <select name="to-unit" id="to-unit">
    <option value="c">Celsius</option>
    <option value="f" selected>Fahrenheit</option>
    <option value="k">Kelvin</option>
  </select>
</div>
<div>
  <button id="convert">Convert</button>
</div>
```

This is what I am going to start with. This will give us just the basic elements we need to get something working, and we can always come back and make it pretty later. There are a few things going on here which we might not have covered yet, and I will touch on them briefly now.

* Input type number - our two `input` elements (the text fields) have an attribute on them called `type` with a value of `number`. What this does is tell the web browser that i want to make sure the use is only able to put numeric values in these fields. This saves us a bit of effort in validating the user's input (after all, we can't convert text into temperature)
* Input placeholder - The placeholder attribute lets us specify what text to show to our users inside the field before they enter a value. This is a nice simple way to prompt the user with what type of value they should provide
* select element - The select element lets us specify a number of `option` elements inside it which then get displayed as dropdown selections for the user to choose pre-configured responses from
  * option element selected attribute - the `selected` attribute lets us specify which options should be selected by default

### Connecting our JavaScript

Now that we have a basic layout to work with, we can start connecting some JS to our HTML. We are going to need to assign all 5 controls to variables, and make a function to run when we click our button. For now, we will just make the function copy the "from" value into the "to" field, without converting it. Once this is working, we can look at converting the value.

To do this, I am going to use `document.getElementById` to target my 5 elements, and store them inside variables, like so:

```javascript
const fromTemp = document.getElementById('from-temp');
const fromUnit = document.getElementById('from-unit');
const toTemp = document.getElementById('to-temp');
const toUnit = document.getElementById('to-unit');
const convertButton = document.getElementById('convert');
```

Next, let's make that function. For now, just something simple to get the data flowing. I will make and use the function like this:

```javascript
const handleClick = () => {
  const temperature = fromTemp.value;
  toTemp.value = temperature;
}

convertButton.addEventListener('click', handleClick);
```

Now, if we enter some numbers into our "from" field and then click the convert button, the value will be written into the "to" field.

Now, time for the fun stuff.

### Converting to other systems

The next thing we need to work on is the functions to actually convert between units of measurement. There are many different ways we could do this. The approach I am going to take is to convert Fahrenheit and Kelvin values into Celsius, and from there, convert it into the desired unit. At most this will take 2 steps, but it will reduce the number of different functions we need, as instead of handling from each unit, to each other unit (3 x 3 = 9) we only need to do from Fahrenheit and Kelvin to Celsius, and back again (only 4 functions). The formulas that we need to make&#x20;

#### Celsius to Fahrenheit:

$$
(100°C × 9/5) + 32 = 212°F
$$

#### Celsius to Kelvin

$$
100°C + 273.15 = 373.15K
$$

Let's implement these two functions now:

```javascript
const celsiusToFahrenheit = (celsius) => (celsius * 9/5) + 32;
const celsiusToKelvin = (celsius) => celsius + 273.15;
```

Now, we will also implement the inverse functions to convert from these units to celsius.

```javascript
const kelvinToCelsius = (kelvin) => kelvin - 273.15;
const fahrenheitToCelsius = (fahrenheit) => (farenheit - 32) * 5/9;
```

With these four functions, we should now be able to convert from any unit, to any other (via a few steps, if necessary)

### Hooking things up

Next, we need to use those `select` elements to determine which operations to perform on the value, and convert the value before inserting it into the output field. To get the value out of the select elements, we can use a couple of DOM API properties. Specifically, select elements have an `options` property which will give us an array of its options as DOM nodes, and a `selectedIndex` property, which will return an integer signifying the index of the selected option. by combining these, we can get the currently selected option element, and extract its `value` property. Doing so would look something like this:

{% hint style="danger" %}
Don't include this in your code, it is just an example of how to access items from a select element.
{% endhint %}

```javascript
const value = element.options[element.selectedIndex].value
```

Using this, let's make a pair of functions. One for getting the user's input converted to celsius, and one for converting that celsius value to whatever the user has selected. These will make use of the functions we made above.

```javascript
const getInputAsCelsius = () => {
  const input = parseFloat(fromTemp.value);
  const unit = fromUnit.options[fromUnit.selectedIndex].value;
  
  if (unit === 'f') {
    return fahrenheitToCelsius(input);
    
  } else if (unit === 'k') {
    return kelvinToCelsius(input);
  }
  
  return input;
}

const convertCelsiusToUnit = (celsius, unit) => {
  if (unit === 'f') {
    return celsiusToFahrenheit(celsius);
    
  } else if (unit === 'k') {
    return celsiusToKelvin(celsius);
  }
  
  return celsius;
}
```

Now, we can use these two new functions to orchestrate the conversion for our user. To do this, lets replace our original conversion function with this:

```javascript
const handleClick = () => {
  const celsius = getInputAsCelsius();
  const unit = toUnit.options[toUnit.selectedIndex].value
  const outputTemp = convertCelsiusToUnit(celsius, unit);
  toTemp.value = outputTemp;
}
```

This will do the following:

* get the user's provided value, converted to celsius
* get the desired unit to convert to
* convert the celsius value to the desired unit
* replace the value in the output field with this new converted value.

That's it. Give it a go. There are still a few things which can be improved. For example, some conversions will result in long numbers with lots of trailing decimal places, and it could do with some CSS to make it pretty, but the fundamentals are there.

### Homework:

* [ ] Add some styles to the HTML. Give it some personality
* [ ] Make sure the converted value gets rounded down to 2 decimal places (hint: `Math.round(100.10)` will return `100`, so to preserve 2 decimal places, you could do something like `Math.round(num * 100) / 100`


