# Programming in JS

Conditions, functions, arrays, loops and objects. The pieces every script is made of.

Multimedia & Creative Technology · 2.1 Webcoding · Lesson 3 · version 1.0.2 · 2026-10-10

Tags: javascript

Slides: <https://slides.mctantwerp.be/en/webcoding/03-programming-in-js>

Speaker notes: <https://slides.mctantwerp.be/en/webcoding/03-programming-in-js.notes.md>

<!-- slide 2 -->

## Agenda

1. Magic Eight Ball
2. Conditionals
3. Functions
4. Arrays
5. Loops
6. Objects
7. Exercises

<!-- slide 3 -->

## 1. Magic Eight Ball

<!-- slide 4 -->

### Greeting and question

```js
const userName = 'Sam';
const userQuestion = 'Will I get dessert twice?';
const randomNumber = Math.floor(Math.random() * 8);

if (userName === '') {
  console.log('Hello!');
} else {
  console.log(`Hello, ${userName}!`);
}

console.log(`${userName} asked: ${userQuestion}`);
```

1. Everything the ball needs, in variables. The random number runs from 0 to 7.
2. An empty name gets a plain hello. Test that case too.
3. Template literals keep the text readable. No plus signs.

<!-- slide 5 -->

### The answer

```js
const randomNumber = Math.floor(Math.random() * 8);
let answer = '';
switch (randomNumber) {
  case 0: answer = 'It is certain'; break;
  case 1: answer = 'It is decidedly so'; break;
  case 2: answer = 'Reply hazy, try again'; break;
  case 3: answer = 'Cannot predict now'; break;
  case 4: answer = 'Do not count on it'; break;
  case 5: answer = 'My sources say no'; break;
  case 6: answer = 'Outlook not so good'; break;
  default: answer = 'Signs point to yes';
}
console.log(`Magic Eight Ball: ${answer}`);
```

<!-- slide 6 -->

**It works. It can be shorter.**

Eight cases for eight sentences. By the end of the arrays chapter the same ball fits in five lines.

<!-- slide 7 -->

### Look it up

- **[01 Search for one thing](https://developer.mozilla.org/en-US/docs/Web/JavaScript)**: MDN has every function with an example you can run. Search engines find it with "mdn" in front of your question.
- **02 Ask AI targeted questions**: "How do I get the number of letters in a string in JavaScript?" One question, one answer you understand.
- **03 Not the whole exercise**: A full solution from AI is an exercise you did not do. Fine by me, but the exam is the first time you find out.

> [!NOTE]
> Most of today works the same as in C#. The braces, the if, the loops. What is different gets its own slide.

<!-- slide 8 -->

## 2. Conditionals

<!-- slide 9 -->

### if, else, else if

```js
let number = 5;

if (number === 5) {
  console.log('The number is 5');
}
```

*if*

```js
let number = 5;

if (number === 5) {
  console.log('The number is 5');
}
```

*else*

```js
let number = 5;

if (number === 5) {
  console.log('The number is 5');
} else {
  console.log('The number is not 5');
}
```

*else if*

```js
let number = 5;

if (number === 5) {
  console.log('The number is 5');
} else if (number > 5) {
  console.log('Bigger than 5');
} else {
  console.log('Smaller than 5');
}
```

<!-- slide 10 -->

### One chain or separate ifs

#### Separate ifs

```js
if (number === 5) {
  console.log('The number is 5');
}
if (number > 5) {
  console.log('Bigger than 5');
}
if (number !== 5 && number <= 5) {
  console.log('Smaller than 5');
}
```

#### One chain

```js
if (number === 5) {
  console.log('The number is 5');
} else if (number > 5) {
  console.log('Bigger than 5');
} else {
  console.log('Smaller than 5');
}
```

<!-- slide 11 -->

### And, or, not

```js
const age = 19;
const hasTicket = true;

if (age >= 18 && hasTicket) {
  console.log('Come in');
} else {
  console.log('Sorry');
}
```

*&&*

```js
const age = 19;
const hasTicket = true;

if (age >= 18 && hasTicket) {
  console.log('Come in');
} else {
  console.log('Sorry');
}
```

*||*

```js
const day = 'sun';

if (day === 'sat' || day === 'sun') {
  console.log('Weekend');
} else {
  console.log('Lessons');
}
```

*!*

```js
const hasTicket = false;

if (!hasTicket) {
  console.log('Buy a ticket first');
}
```

<!-- slide 12 -->

### Truthy and falsy

```js
const name = '';

if (name) {
  console.log(`Hello, ${name}!`);
} else {
  console.log('Hello!');
}
```

*empty name*

```js
const name = '';

if (name) {
  console.log(`Hello, ${name}!`);
} else {
  console.log('Hello!');
}
```

*zero*

```js
const score = 0;

if (score) {
  console.log('Scored ' + score);
} else {
  console.log('No score');
}
```

> [!NOTE]
> Falsy: `false`, `0`, `''`, `null`, `undefined` and `NaN`. Everything else is truthy.

<!-- slide 13 -->

### The short if

- *Ternary*

  ```js
  const age = 16;

  const label = age >= 18 ? 'adult' : 'minor';
  ```
- *Same thing with if*

  ```js
  const age = 16;

  let label;
  if (age >= 18) {
    label = 'adult';
  } else {
    label = 'minor';
  }
  ```

> [!WARNING]
> `number === 5 ? true : false` is just `number === 5`. The comparison already gives true or false.

<!-- slide 14 -->

### switch

```js
const day = 'sat';

switch (day) {
  case 'sat':
    console.log('Saturday');
    break;
  case 'sun':
    console.log('Sunday');
    break;
  default:
    console.log('A weekday');
}
```

*with break*

```js
const day = 'sat';

switch (day) {
  case 'sat':
    console.log('Saturday');
    break;
  case 'sun':
    console.log('Sunday');
    break;
  default:
    console.log('A weekday');
}
```

*break missing*

```js
const day = 'sat';

switch (day) {
  case 'sat':
    console.log('Saturday');
  case 'sun':
    console.log('Sunday');
  default:
    console.log('A weekday');
}
```

<!-- slide 15 -->

### const score = 0; if (score) { console.log('Scored') } else { console.log('Nothing') }. What shows up?

- A. Scored
- B. Nothing
- C. Both
- D. An error

**Answer:** B. Nothing

0 is falsy, so the if takes the else. To check whether there is a score at all, compare: score !== undefined.

<!-- slide 16 -->

## 3. Functions

<!-- slide 17 -->

### A function

```js
function greetWorld() {
  console.log('Hello world!');
}

greetWorld();
```

<!-- slide 18 -->

### Parameters

```js
function greetCountry(country) {
  console.log('Hello ' + country);
}

greetCountry('Belgium');
greetCountry('Japan');
```

<!-- slide 19 -->

### return or console.log

```js
function double(n) {
  console.log(n * 2);
}

const result = double(21);
console.log('result is', result);
```

*console.log*

```js
function double(n) {
  console.log(n * 2);
}

const result = double(21);
console.log('result is', result);
```

*return*

```js
function double(n) {
  return n * 2;
}

const result = double(21);
console.log('result is', result);
```

<!-- slide 20 -->

### Default values

#### Checking by hand

```js
function greetCountry(country) {
  if (typeof country === 'undefined') {
    return 'Hello World';
  }
  return 'Hello ' + country;
}

greetCountry(); // 'Hello World'
```

#### A default value

```js
function greetCountry(country = 'World') {
  return 'Hello ' + country;
}

greetCountry();   // 'Hello World'
greetCountry(''); // 'Hello '
```

<!-- slide 21 -->

### Functions are values

```js
const rocketToMars = function () {
  return 'BOOM!';
};

console.log(rocketToMars());
console.log(typeof rocketToMars);
```

<!-- slide 22 -->

### Four ways to write it

```js
function double(n) {
  return n * 2;
}

console.log(double(21));
```

*declaration*

```js
function double(n) {
  return n * 2;
}

console.log(double(21));
```

*function in a variable*

```js
const double = function (n) {
  return n * 2;
};

console.log(double(21));
```

*arrow*

```js
const double = (n) => {
  return n * 2;
};

console.log(double(21));
```

*short arrow*

```js
const double = n => n * 2;

console.log(double(21));
```

<!-- slide 23 -->

### Arrow functions

```js
numbers.map(function (n) {
  return n * 2;
});

numbers.map((n) => {
  return n * 2;
});

numbers.map(n => {
  return n * 2;
});

numbers.map(n => n * 2);
```

1. In full. This is what we write.
2. The arrow replaces the word `function`.
3. One parameter, the brackets may go.
4. One expression: no braces and no `return`.

<!-- slide 24 -->

### What we write

| Where | Write |   |
| --- | --- | --- |
| A named function | `function double(n) { }` | A declaration |
| A function you hand over | `forEach(function (item) { })` | In full, with return |
| A method in an object | `describe() { }` | Never an arrow |
| An arrow you find online | `item => item * 2` | Read it, rewrite it in full |

<!-- slide 25 -->

**Use once, skip the name.**

A function you only need in one place does not need a name: function (item) { ... }. You hand it to another function, which calls it for you. That is a callback, and the next chapters are full of them.

<!-- slide 26 -->

### function add(a, b) { console.log(a + b) }. What does console.log(add(2, 3)) show?

- A. 5
- B. 5, then undefined
- C. undefined
- D. An error

**Answer:** B. 5, then undefined

add logs 5 itself, but returns nothing, so the outer console.log gets undefined. With return a + b you would see 5 once.

<!-- slide 27 -->

## 4. Arrays

<!-- slide 28 -->

### An array

```js
const numbers = [100, 200, 300, 400];

console.log(numbers[0]);
console.log(numbers[1]);
console.log(numbers.length);
```

*index*

```js
const numbers = [100, 200, 300, 400];

console.log(numbers[0]);
console.log(numbers[1]);
console.log(numbers.length);
```

*the last one*

```js
const numbers = [100, 200, 300, 400];

console.log(numbers[numbers.length - 1]);
console.log(numbers[4]);
```

<!-- slide 29 -->

### Adding and removing

```js
const cart = ['apple', 'orange'];

cart.push('pear');
cart.push('kiwi', 'lime');

console.log(cart);
```

*push*

```js
const cart = ['apple', 'orange'];

cart.push('pear');
cart.push('kiwi', 'lime');

console.log(cart);
```

*pop*

```js
const ingredients = ['eggs', 'flour', 'chocolate'];

const last = ingredients.pop();

console.log(last);
console.log(ingredients);
```

*includes*

```js
const cart = ['apple', 'orange'];

console.log(cart.includes('apple'));
console.log(cart.includes('pear'));
```

<!-- slide 30 -->

### A const array still changes

```js
const cart = ['apple'];

cart.push('pear');
console.log(cart);

cart = ['banana'];
console.log(cart);
```

<!-- slide 31 -->

### Anything goes in

```js
const numbers = [0, 1, 2, 3];
const names = ['Alice', 'Bob', 'Carl'];
const mixed = [1, 'chicken', false];
const grid = [[1, 2], [3, 4]];
```

> [!TIP]
> Possible is not the same as a good idea. Keep one kind of value per array.

<!-- slide 32 -->

### Magic Eight Ball, again

```js
const answers = [
  'It is certain',
  'It is decidedly so',
  'Reply hazy, try again',
  'Cannot predict now',
  'Do not count on it',
  'My sources say no',
  'Outlook not so good',
  'Signs point to yes',
];
const index = Math.floor(Math.random() * answers.length);

console.log(`Magic Eight Ball: ${answers[index]}`);
```

<!-- slide 33 -->

### const letters = \['a', 'b', 'c'\]. What is letters\[letters.length\]?

- A. 'c'
- B. undefined
- C. 3
- D. An error

**Answer:** B. undefined

length is 3, and index 3 does not exist: the last item is at index 2. Reading a spot that does not exist gives undefined, not an error.

<!-- slide 34 -->

## 5. Loops

<!-- slide 35 -->

### while and do...while

```js
let roll;

do {
  roll = Math.floor(Math.random() * 6) + 1;
  console.log('You rolled ' + roll);
} while (roll !== 6);
```

*while*

```js
let lives = 3;

while (lives > 0) {
  console.log('Lives left: ' + lives);
  lives--;
}
```

*do...while*

```js
let roll;

do {
  roll = Math.floor(Math.random() * 6) + 1;
  console.log('You rolled ' + roll);
} while (roll !== 6);
```

<!-- slide 36 -->

### for

```js
for (let i = 0; i < 4; i++) {
  console.log(i);
}
```

- **01 let i = 0**: Runs once, before the first round.
- **02 i < 4**: Checked before every round. False, and the loop stops.
- **03 i++**: Runs after every round.

<!-- slide 37 -->

### for over an array

```js
const songs = ['Intro', 'Verse', 'Chorus', 'Outro'];

for (let i = 0; i < songs.length; i++) {
  console.log(i + ': ' + songs[i]);
}
```

<!-- slide 38 -->

### forEach

```js
const numbers = [28, 77, 45, 99, 27];

numbers.forEach(function (number) {
  console.log(number);
});
```

*function*

```js
const numbers = [28, 77, 45, 99, 27];

numbers.forEach(function (number) {
  console.log(number);
});
```

*with index*

```js
const numbers = [28, 77, 45, 99, 27];

numbers.forEach(function (number, i) {
  console.log(i, number);
});
```

*arrow*

```js
const numbers = [28, 77, 45, 99, 27];

numbers.forEach(number => {
  console.log(number);
});
```

<!-- slide 39 -->

### filter

```js
const randomNumbers = [4, 11, 42, 14, 39];

const bigOnes = randomNumbers.filter(function (n) {
  return n > 12;
});

console.log(bigOnes);
console.log(randomNumbers);
```

*function*

```js
const randomNumbers = [4, 11, 42, 14, 39];

const bigOnes = randomNumbers.filter(function (n) {
  return n > 12;
});

console.log(bigOnes);
console.log(randomNumbers);
```

*short arrow*

```js
const randomNumbers = [4, 11, 42, 14, 39];

const bigOnes = randomNumbers.filter(n => n > 12);

console.log(bigOnes);
console.log(randomNumbers);
```

<!-- slide 40 -->

### map

```js
const finalists = ['Taylor', 'Natasha', 'Bobby'];

const announcements = finalists.map(function (name) {
  return name + ' joined the contest.';
});

console.log(announcements);
```

*function*

```js
const finalists = ['Taylor', 'Natasha', 'Bobby'];

const announcements = finalists.map(function (name) {
  return name + ' joined the contest.';
});

console.log(announcements);
```

*short arrow*

```js
const finalists = ['Taylor', 'Natasha', 'Bobby'];

const announcements = finalists.map(name => name + ' joined.');

console.log(announcements);
```

<!-- slide 41 -->

### Which one

|   | Gives back | Use it to |
| --- | --- | --- |
| `for` | Nothing | Count, or loop a fixed number of times |
| `forEach` | Nothing | Do something with every item |
| `filter` | A new, shorter array | Keep the items that pass a test |
| `map` | A new array, same length | Turn every item into something else |

<!-- slide 42 -->

### What does \[1, 2, 3\].map(function (n) { return n \* 2; }) give?

- A. \[1, 2, 3\]
- B. \[2, 4, 6\]
- C. 12
- D. undefined

**Answer:** B. \[2, 4, 6\]

map builds a new array with what the function returns for every item. Every number comes back doubled. The original array stays \[1, 2, 3\].

<!-- slide 43 -->

## 6. Objects

<!-- slide 44 -->

### An object

```js
const apple = {
  color: 'Green',
  price: { bulk: '€3/kg', small: '€4/kg' },
};

console.log(apple.color);
console.log(apple.price.bulk);

apple.color = 'Red';
console.log(apple.color);
```

<!-- slide 45 -->

### Adding and deleting

```js
const student = {
  name: 'Sheldon',
  score: 100,
  grade: 'A',
};

student.year = 2;
delete student.score;
student.grade = 'F';

console.log(student);
console.log(student.scroe); // typo: undefined, no error
```

<!-- slide 46 -->

### Square brackets

```js
const mobile = {
  brand: 'Samsung',
  model: 'Galaxy S25',
};

for (const key in mobile) {
  console.log(`${key}: ${mobile[key]}`);
}
```

*for...in*

```js
const mobile = {
  brand: 'Samsung',
  model: 'Galaxy S25',
};

for (const key in mobile) {
  console.log(`${key}: ${mobile[key]}`);
}
```

*dot or brackets*

```js
const mobile = {
  brand: 'Samsung',
  model: 'Galaxy S25',
};

const key = 'brand';
console.log(mobile[key]);
console.log(mobile.key);
```

<!-- slide 47 -->

### Methods

```js
const engine = {
  start(adverb) {
    console.log(`The engine starts up ${adverb}...`);
  },
  sputter() {
    console.log('The engine sputters...');
  },
};

engine.start('noisily');
engine.sputter();
```

<!-- slide 48 -->

### this

```js
const cat = {
  name: 'Pipey',
  age: 8,
  describe() {
    return this.name + ' is ' + this.age;
  },
};

console.log(cat.describe());
```

*method*

```js
const cat = {
  name: 'Pipey',
  age: 8,
  describe() {
    return this.name + ' is ' + this.age;
  },
};

console.log(cat.describe());
```

*arrow*

```js
const cat = {
  name: 'Pipey',
  age: 8,
  describe: () => {
    return this.name + ' is ' + this.age;
  },
};

console.log(cat.describe());
```

<!-- slide 49 -->

### An array of objects

```js
const students = [
  { name: 'Amira', score: 14 },
  { name: 'Ben', score: 9 },
  { name: 'Chloé', score: 17 },
];
const passed = students.filter(function (student) {
  return student.score >= 10;
});
const lines = passed.map(function (student) {
  return `${student.name}: ${student.score}/20`;
});
console.log(lines);
```

*function*

```js
const students = [
  { name: 'Amira', score: 14 },
  { name: 'Ben', score: 9 },
  { name: 'Chloé', score: 17 },
];
const passed = students.filter(function (student) {
  return student.score >= 10;
});
const lines = passed.map(function (student) {
  return `${student.name}: ${student.score}/20`;
});
console.log(lines);
```

*arrow*

```js
const students = [
  { name: 'Amira', score: 14 },
  { name: 'Ben', score: 9 },
  { name: 'Chloé', score: 17 },
];

const passed = students.filter(s => s.score >= 10);
const lines = passed.map(s => `${s.name}: ${s.score}/20`);

console.log(lines);
```

<!-- slide 50 -->

### const key = 'color'; const car = { color: 'red' }. Which line logs red?

- A. console.log(car.key)
- B. console.log(car\[key\])
- C. console.log(car\['key'\])
- D. console.log(car.(key))

**Answer:** B. console.log(car\[key\])

Square brackets take the value of the variable, so car\[key\] is car\['color'\]. car.key and car\['key'\] both look for a property called key, which does not exist, so they give undefined.

<!-- slide 51 -->

## 7. Exercises

> [!NOTE]
> The intention is not for us to become syntax / JavaScript experts, but to have a basic understanding of the syntax and be able to understand everything.

<!-- slide 52 -->

### Ask the user

```js
const name = prompt('What is your name?');

console.log('Hello ' + name);
```

*prompt() → `Sam`*

*text*

```js
const name = prompt('What is your name?');

console.log('Hello ' + name);
```

*prompt() → `Sam`*

*a number*

```js
const answer = prompt('How old are you?');

console.log(answer + 1);
console.log(Number(answer) + 1);
```

*prompt() → `19`*

*cancel*

```js
const name = prompt('What is your name?');

if (name === null) {
  console.log('No name, no hello');
}
```

> [!WARNING]
> prompt() always gives back a string. Use `Number(answer)` before you calculate with it.

<!-- slide 53 -->

### How it works

- At least **two exercises per topic**. More is better.
- One folder per topic, with an `index.html` and your JavaScript in a `<script>` at the end of the body, opened with Live Server.
- Stuck for more than ten minutes? Ask a classmate, ask on Discord, then look at the solution.

<!-- slide 54 -->

### Task: Conditionals

Use prompt() for the input and console.log for the output.

1. Ask for an age. Say whether the person is of legal age or a minor.
2. Ask for two numbers. Say which one is the largest, or that they are equal.
3. Ask for a number. Say whether it is even or odd (the remainder: `%`).
4. Ask for an age. Say child (under 12), teenager (12 to 17) or adult.

> [!TIP]
> **Conditionals**
>
> *Legal age*
>
> ```js
> const age = Number(prompt('How old are you?'));
>
> if (age >= 18) {
>   console.log('You are of legal age');
> } else {
>   console.log('You are a minor');
> }
> ```
>
> *Largest*
>
> ```js
> const a = Number(prompt('First number?'));
> const b = Number(prompt('Second number?'));
>
> if (a > b) {
>   console.log(`${a} is the largest`);
> } else if (b > a) {
>   console.log(`${b} is the largest`);
> } else {
>   console.log('They are equal');
> }
> ```
>
> *Even or odd*
>
> The remainder of a division by 2 is 0 for every even number.
>
> ```js
> const number = Number(prompt('A number?'));
>
> if (number % 2 === 0) {
>   console.log(`${number} is even`);
> } else {
>   console.log(`${number} is odd`);
> }
> ```
>
> *Child, teen, adult*
>
> The chain stops at the first match, so the second condition does not need to check age >= 12 again.
>
> ```js
> const age = Number(prompt('How old are you?'));
>
> if (age < 12) {
>   console.log('Child');
> } else if (age < 18) {
>   console.log('Teenager');
> } else {
>   console.log('Adult');
> }
> ```

<!-- slide 55 -->

### Task: Functions

Call every function a few times with different arguments, and log what it returns.

1. A function that takes two numbers and returns their product.
2. A function that takes a sentence and returns the number of words in it. Look up `split`.
3. A function that takes an array of numbers and returns the average.
4. Your Magic Eight Ball, rewritten with functions: one for the greeting, one that returns an answer.

> [!TIP]
> **Functions**
>
> *Product*
>
> ```js
> function multiply(a, b) {
>   return a * b;
> }
>
> console.log(multiply(6, 7));
>
> // The arrow version you will find online
> // const multiply = (a, b) => a * b;
> ```
>
> *Words*
>
> split cuts a string into an array at every space. trim first, or a space at the end counts as an extra word.
>
> ```js
> function countWords(sentence) {
>   if (sentence.trim() === '') {
>     return 0;
>   }
>   return sentence.trim().split(' ').length;
> }
>
> console.log(countWords('Write less, do more'));
> ```
>
> *Average*
>
> ```js
> function average(numbers) {
>   let sum = 0;
>   numbers.forEach(function (n) {
>     sum += n;
>   });
>   return sum / numbers.length;
> }
>
> console.log(average([12, 15, 9, 16]));
> ```
>
> *Magic Eight Ball*
>
> ```js
> const answers = ['It is certain', 'Ask again later', 'My sources say no', 'Outlook good'];
>
> function greet(name) {
>   return name === '' ? 'Hello!' : `Hello, ${name}!`;
> }
>
> function shake() {
>   const index = Math.floor(Math.random() * answers.length);
>   return answers[index];
> }
>
> const name = prompt('What is your name?');
> const question = prompt('What do you want to know?');
>
> console.log(greet(name));
> console.log(`${name} asked: ${question}`);
> console.log(`Magic Eight Ball: ${shake()}`);
> ```

<!-- slide 56 -->

### Task: Arrays

Make up your own arrays, and test with an empty array too.

1. An array of numbers. Log the largest number in it.
2. An array of words. Log the longest word.
3. A to do list: add three items with push, take the last one off with pop, and log how many are left.
4. An array of names. Log only the names longer than four letters, with filter.

> [!TIP]
> **Arrays**
>
> *Largest*
>
> Start with the first item as the largest so far, then compare every other item with it. Math.max(...numbers) does it in one line, but then you learned nothing.
>
> ```js
> const numbers = [4, 11, 42, 14, 39];
> let largest = numbers[0];
>
> numbers.forEach(function (n) {
>   if (n > largest) {
>     largest = n;
>   }
> });
>
> console.log(largest);
> ```
>
> *Longest word*
>
> ```js
> const words = ['tram', 'bicycle', 'scooter', 'train'];
> let longest = '';
>
> for (let i = 0; i < words.length; i++) {
>   if (words[i].length > longest.length) {
>     longest = words[i];
>   }
> }
>
> console.log(longest);
> ```
>
> *To do*
>
> ```js
> const todo = [];
>
> todo.push('Exercises conditionals');
> todo.push('Exercises functions');
> todo.push('Watch the series');
>
> const done = todo.pop();
>
> console.log(`Dropped: ${done}`);
> console.log(`${todo.length} left`);
> ```
>
> *Long names*
>
> ```js
> const names = ['Ann', 'Bram', 'Charlotte', 'Daan', 'Elise'];
>
> const longNames = names.filter(function (name) {
>   return name.length > 4;
> });
>
> console.log(longNames);
> ```

<!-- slide 57 -->

### Task: Loops

1. Log the numbers from 1 to 10 with a for loop.
2. Keep asking for a number with a while loop and say whether it is even or odd. Stop when the user enters 0.
3. Log the first 10 numbers of the Fibonacci sequence: 0, 1, 1, 2, 3, 5 and so on. Every number is the sum of the two before it.
4. Keep asking for a password with a do...while loop until it is abc123. Say whether every try is right or wrong.
5. Calculate the sum of an array of numbers with a for loop.

> [!TIP]
> **Loops**
>
> *1 to 10*
>
> ```js
> for (let i = 1; i <= 10; i++) {
>   console.log(i);
> }
> ```
>
> *Even until 0*
>
> Ask once before the loop, and again at the end of every round. Otherwise the 0 itself gets called even.
>
> ```js
> let number = Number(prompt('A number? 0 stops'));
>
> while (number !== 0) {
>   if (number % 2 === 0) {
>     console.log(`${number} is even`);
>   } else {
>     console.log(`${number} is odd`);
>   }
>   number = Number(prompt('A number? 0 stops'));
> }
> ```
>
> *Fibonacci*
>
> Keep the last two numbers in variables and shift them up every round.
>
> ```js
> let a = 0;
> let b = 1;
>
> for (let i = 0; i < 10; i++) {
>   console.log(a);
>   const next = a + b;
>   a = b;
>   b = next;
> }
> ```
>
> *Password*
>
> ```js
> let password;
>
> do {
>   password = prompt('Password?');
>   if (password === 'abc123') {
>     console.log('Correct, welcome');
>   } else {
>     console.log('Wrong password');
>   }
> } while (password !== 'abc123');
> ```
>
> *Sum*
>
> ```js
> const numbers = [28, 77, 45, 99, 27];
> let sum = 0;
>
> for (let i = 0; i < numbers.length; i++) {
>   sum += numbers[i];
> }
>
> console.log(sum);
> ```

<!-- slide 58 -->

### Task: Objects

1. A person with a name, an age and a job. Log the name.
2. A pet with a name, a breed and an age. Log the name and the breed in one sentence.
3. A student with a name, an age and a class, and a method that logs all of it.
4. A car with a brand, a model and a year, and a method that returns how old the car is.
5. An array of three movies with a title and a year. Log the titles of the movies from before 2000.

> [!TIP]
> **Objects**
>
> *Person*
>
> ```js
> const person = {
>   name: 'Lotte',
>   age: 21,
>   job: 'Developer',
> };
>
> console.log(person.name);
> ```
>
> *Pet*
>
> ```js
> const pet = {
>   name: 'Minnie',
>   breed: 'British Shorthair',
>   age: 3,
> };
>
> console.log(`${pet.name} is a ${pet.breed}`);
> ```
>
> *Student*
>
> ```js
> const student = {
>   name: 'Yusuf',
>   age: 19,
>   className: '2MCT1',
>   describe() {
>     console.log(`${this.name}, ${this.age}, in ${this.className}`);
>   },
> };
>
> student.describe();
> ```
>
> *Car*
>
> new Date().getFullYear() gives the current year, so the answer stays right next year.
>
> ```js
> const car = {
>   brand: 'Volvo',
>   model: 'EX30',
>   year: 2024,
>   age() {
>     return new Date().getFullYear() - this.year;
>   },
> };
>
> console.log(`${car.brand} ${car.model}: ${car.age()} years old`);
> ```
>
> *Movies*
>
> ```js
> const movies = [
>   { title: 'The Matrix', year: 1999 },
>   { title: 'Spirited Away', year: 2001 },
>   { title: 'Jurassic Park', year: 1993 },
> ];
>
> const old = movies.filter(function (movie) {
>   return movie.year < 2000;
> });
>
> old.forEach(function (movie) {
>   console.log(movie.title);
> });
> ```

## Glossary

- **else if**: Adds another condition to an if. JavaScript checks them top to bottom and runs only the first block that matches, the rest is skipped. (slide 10)
- **Logical operators**: && is and, || is or, ! turns true into false and the other way around. They glue several conditions together into one. (slide 11)
- **Truthy and falsy**: What a value counts as inside an if. false, 0, '' (an empty string), null, undefined and NaN are falsy. Everything else is truthy, even '0' and an empty array. (slide 12)
- **Ternary operator**: condition ? valueIfTrue : valueIfFalse. An if that gives back a value, handy to pick one of two values for a variable. One line, no blocks inside. (slide 13)
- **switch**: Compares one value with a list of cases. Every case needs a break, or the code of the next case runs too. default catches everything else. (slide 14)
- **Function**: A named piece of code you can run as often as you like by calling it: greetWorld(). Declaring it runs nothing, calling it does. (slide 17)
- **Parameter**: The name between the brackets when you declare a function, like country in function greet(country). The value you pass when you call it is the argument. (slide 18)
- **return**: Hands a value back to the code that called the function and stops the function right there. Without a return, a function gives back undefined. (slide 19)
- **Default parameter**: A value a parameter gets when you leave the argument out: function greet(country = 'World'). It only kicks in for undefined, an empty string stays an empty string. (slide 20)
- **Function declaration**: A function with the word function and a name in front: function double(n) { ... }. The way to write a named function. (slide 22)
- **Anonymous function**: A function without a name, stored in a variable or passed straight to another function. Used for code you only need in one place. (slide 21)
- **Arrow function**: A shorter way to write a function: (a, b) => a \* b. With one expression and no braces, the result is returned on its own. You will read them everywhere. In this course you write function in full. (slide 23)
- **Callback**: A function you hand to another function, which calls it for you later or once per item. The function in numbers.forEach(function (n) { ... }) is one. (slide 38)
- **Array**: A list of values in one variable, between square brackets. Every item has an index, starting at 0. (slide 28)
- **Index**: The position of an item in an array, starting at 0. The last item is at array.length - 1, an index that does not exist gives undefined. (slide 28)
- **push and pop**: push adds one or more items at the end of an array, pop takes the last one off and gives it back. Both change the array itself. (slide 29)
- **do...while**: A loop that checks its condition after the block instead of before, so the block always runs at least once. (slide 35)
- **for loop**: A loop with a counter: a start, a condition to keep going and a step after every round, all in one line. The one to use when you know how many rounds you need. (slide 36)
- **forEach**: Runs a function once for every item of an array. Gives nothing back, it is for doing something with each item. (slide 38)
- **filter**: Makes a new array with only the items for which your function returns true. The original array stays the same. (slide 39)
- **map**: Makes a new array of the same length, with whatever your function returns for every item. The original array stays the same. (slide 40)
- **Object**: A group of values that belong together, each with a name: { name: 'Minnie', age: 3 }. Between curly braces, key and value separated by a colon. (slide 44)
- **Property**: One key with its value inside an object. You read it with a dot, cat.name, or with square brackets, cat\[key\]. (slide 44)
- **Bracket notation**: Reading a property with the key as a string: mobile\['brand'\], or mobile\[key\] when the key is in a variable. The dot only works with the name typed out. (slide 46)
- **for...in**: A loop over the keys of an object. Every round puts the next key in a variable, and you read the value with square brackets. (slide 46)
- **Method**: A function that is a property of an object: engine.start(). Written as start() { ... } inside the object. (slide 47)
- **this**: Inside a method, the object the method was called on. In an arrow function it is not, so write methods with the short start() { } syntax. (slide 48)
- **prompt()**: Opens a browser dialog with a question and a text field. Gives back the text as a string, or null when the user clicks Cancel. Fine for exercises, never on a real site. (slide 52)

## Links and sources

### In the deck

- [Search for one thing](https://developer.mozilla.org/en-US/docs/Web/JavaScript) (slide 7)
- [kdgmt.be/discord](https://kdgmt.be/discord) (slide 59)

### Sources

- [JavaScript Guide: Control flow and error handling](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling)
- [JavaScript Guide: Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)
- [Arrow function expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)
- [JavaScript Guide: Loops and iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)
- [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
- [JavaScript Guide: Working with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_objects)
- [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy)
- [Window: prompt() method](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt)
