# 4. Javascript

## 4. Javascript

## Lesson objectives

* Students self learn through UDACITY course: <https://classroom.udacity.com/courses/ud803>
* Students understand how to find help on the internet
* Understand variables
* Understand basic javascript syntax (if, for loops)
* Understand functions
* Understand how to use the browser console and debugger

## Lesson time to deliever:

2 days (6 sessions, 9hrs)

## Teacher instruction

This is a relatively easy 2 days for the teacher: The students will mostly self learn through the udacity course&#x20;

* Students go through udacity course (<https://classroom.udacity.com/courses/ud803>)
* In every 1.5 hr session, give students roughly 1h15m to go through course. Then spend 15 mins checkpointing them to ensure they stay on track. Mini quiz (e.g. [multiple choice questions](/thebeta/lesson-plans/4.-javascript.md#example-multiple-choice-questions)), go over bits that class is struggling with.
* At end of wednesday 1 or start of Thursday give them the [Fizz buzz](/thebeta/lesson-plans/4.-javascript.md#class-ex-fizz-buzz) challenge (see below). Should take 30 mins-1hr to complete. This tests their knowledge of selection (if statements) and iteration (for loops).&#x20;
* Order to cover lessons:

| Session     | Lesson                                                                                                                                                                                                                                                                                                                                    |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Wednesday 1 | <p><a href="https://classroom.udacity.com/courses/ud803/lessons/e98aae00-9563-4fca-b91c-a4e79ca79c27/concepts/last-viewed">Lesson 1 - What is JavaScript?</a></p><p>and <a href="https://classroom.udacity.com/courses/ud803/lessons/74007e2e-2a0a-4de3-a8a6-5c2ec4275773/concepts/last-viewed">Lesson 2 - Data Types & Variables</a></p> |
| Wednesday 2 | [Lesson 3 - Conditionals](https://classroom.udacity.com/courses/ud803/lessons/3ace947b-b5f6-40c1-bc11-3ec98fd1d936/concepts/last-viewed) - don't cover switch statement                                                                                                                                                                   |
| Wednesday 3 | [Lesson 4 - Loops](https://classroom.udacity.com/courses/ud803/lessons/1234cec0-179b-40b6-9435-f10263c7de33/concepts/last-viewed)                                                                                                                                                                                                         |
| Thursday 1  | [Fizz buzz](/thebeta/lesson-plans/4.-javascript.md#class-ex-fizz-buzz) challenge/ Catch up                                                                                                                                                                                                                                                |
| Thursday 2  | [Lesson 5 - Functions](https://classroom.udacity.com/courses/ud803/lessons/a7c5b540-51a6-44dc-b2f2-515c9dd6ca4f/concepts/last-viewed)                                                                                                                                                                                                     |
| Thursday 3  | <p><a href="https://classroom.udacity.com/courses/ud803/lessons/378e7ff7-f7e5-4487-b5c4-fdf9b5c351d9/concepts/last-viewed">Lesson 6 - Arrays</a>. If have time cover Objects too.</p><p><em>May need to teach this one using material below rather than using udacity course due to time constraints</em></p>                             |

{% hint style="danger" %}
You need to cover an estimated 2hr lesson in effectively 1h15m in each session. Encourage students to go through lessons quickly. Give students homework if unable to do in time
{% endhint %}

There is some additional material below:

* Go through basics (see below: Arrays, objects, selection, for loops) and explain difference between let and var (prefer let), and == vs === (prefer ===) Then cover functions in javascript
* Cover getting help:\
  \- Stackoverflow\
  \- I use this for JS reference <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference>
* Datatypes: Cover this sparingly and more through examples. Don't cover bigInt, or the max and min of number (Never hit those limits myself)

## History of Javascript

![](/files/-MUZEg_UAEroqAdJPchz)

#### JS has a very interesting history so try to get that across:

* It was invented in weeks. Most languages are invented in months or years
* It was named Javascript to steal from the popularity of Java which was the hottest language at that time. Backfired now as JS is most popular language in the world and Java is gaining the benifits of that...
* The browser wars. Can make it into a cool game
* JS didnt change in 10 years. Can talk about the drama between Mircosoft (supported by Yahoo on the commitee) that had its own browser scripting language (JScript) vs the other 4 members of the committee. But best thing for JS as people invented tools to fill in its gaps and it was really stable when JScript and Flash it's main competitors were constantly changing.&#x20;
* Ajax - Asynchronous programming. Got invented for JS by open source projects. Now used in most other languages
* End with Modern js frameworks which we will cover in the future (React.js, vue.js, angular)

## Course materials

* Slide deck by emmanuel.
* Image on history of JS
* Youtube video
* <https://javascript.info/> - Chpt 2: JS fundamentals
* <https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics>
* <https://classroom.udacity.com/courses/ud803> - Student excerises

### Code pen

<https://codepen.io/>\
My favourite html/js playground. Tons of work people have done

### Debugging

Enuse you: **Cover opening the browser debugger by pressing F12. Chrome is recommended browser as it is the easiest for debugging.**

Then execute the js code in the browser console so students get used to it. But also switch to html file + js file so don't forget that.

```javascript
debugger; // This line of code causes execution to stop here when debugger open
```

### JS Basics:

Open browser. Press F12. Now have developer console. Can run js code

```javascript
// Set a variable
var a = "Hello World";  // Strings can be '' or "". Pick one and stick to it for your code
console.log(a); // Note console almost always there (but not always)

// Create an object
var it = { a: 20, b: "Test" }
console.log(it.a)

// semi-colons (;) are optional. Js will automatically fill for you

// this is also a dictionary
console.log(it["a"])

// Arrays
var myArr = ['a', 'b', 'c'];

// This is equivalent to a list in C#
console.log(myArr[0]);   // 'a'
myArr.push(10) // Not typed, so can add anything
myArr[2] = "Testing the world";
console.log(myArr);


// Selection
let b = 10
if(a === 2){
  // will discuss == vs === in a sec
  console.log("b is 2");
} else if(b > 0) {
  console.log("b Positive");
} else {
  console.log("b is negative");
}

// For loop
let str = '';
for (let i = 0; i < 9; i++) {
  str = str + i;
}

console.log(str);

// Can do a For each on an array
var array1 = ['a', 'b', 'c'];

array1.forEach(function(x){ console.log(x)});

// new ES2015 way with function shorthand
array1.forEach(element => console.log(element));
```

#### == Vs ===

<https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons>

```javascript
"0" == 0; // True
"0" === 0; // False

// Quirk of js
"abc" == new String("abc")       // true
"abc" === new String("abc")      // false
// because ...
typeof "hello world"             // "string"
typeof new String('hello world') // "object"
```

As a general rule always use === and never ==

#### let vs var vs const

If don't use a keyword, variable is declared on Global scope. Aka global variable. Bad!

"var" original way of declaring a variable. Behaves a bit funkily at times

"let" is new way - Prefer over var. Difference is around how they behave within scopes. E.g. a for loop. If you have programmed before "let" behaves the way you are used to. "var" is different

"const" - Constant. Value is not allowed to change (aka be set again) (Prefer this over let when can use)

```
let a = 10;
var b = 10;
const c = 10;

// Let variable is not visible outside of the loop
for(let i = 0; i <10; i++){
  // ...
}
console.log(i); // undefined

// But var variable is
for(var j = 0; j <10; i++){
  // ...
}
console.log(j); // 10
```

#### No strong types in javascript

```javascript
var mycar = {
  brand: "Honda",
  model: "Accord",
  year: 1998
};
```

### Functions

```javascript
function myFunc(theObject) {
  theObject.brand = "Toyota";
}

/* Pass object reference to the function */
myFunc(mycar);

// other way to define a function
var myFunction = function() {
  theObject.brand = "BMW";
}

// or with this way. In stack traces when error get a better error message (but no one does this way)
var myFunction = function namedFunction(){
    statements
}

myFunction(mycar);
```

####

#### Arrow functions (save for full course)

The arrow function expression (=>). Very similar to C#

```javascript
(t) => { console.log(t); }
```

#### Self invoking functions (save for full course)

```javascript
(function() {
    statements
})();
```

The function invokes as soon as the script is loaded. See it alot in jquery

```javascript
$(function () {
  // code to run once all view elements are initialised
})();
```

#### Function hoisting  (save for full course)

Scripted but functions get read first so can call them from anywhere in script

## Teacher Recommendations

#### What worked well in the past

#### What hasn't worked well in the past

## Class Ex: Fizz buzz

HW Fizz Buzz -Fun drinking game and teaching tool for division for kids.\
&#x20;Count from 1 to 100. For each number output "This is X out of 100"\
&#x20;Any number divisible by three is replaced by the word fizz and any number divisible by five by the word buzz. Numbers divisible by 3 and 5 become fizz buzz.

Sample output:

> This is 1 out of 100\
> &#x20;This is 2 out of 100\
> &#x20;Fizz\
> &#x20;This is 4 out of 100\
> &#x20;Buzz\
> &#x20;Fizz\
> &#x20;This is 7 out of 100\
> &#x20;...

## Example Multiple choice questions

What you want to do here is create questions that inform you of the gaps in their knowledge. For example:

1. What happens here?

```javascript
da === 3
```

\
a. da is now 3 *(if answer this know need to spend more time explaining variable assignment)*\
b. We are comparing da to 3

```javascript
if(da [?] 3){
    // do something
}
```

2\. What should be in \[?]\
a. = *(if answer this know need to spend more time explaining variable assignment)*\
b. == *(if answer this know need to spend more time explaining == vs ===)*\
c. ===

3\. What happens if I pass in more parameters to a function than it has slots?\
4\. What happens if I pass in less?


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tbhp.gitbook.io/thebeta/lesson-plans/4.-javascript.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
