Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Boolean Coding Weekend Intro to JS

The document outlines a coding weekend event focusing on an introduction to JavaScript, detailing its significance, features, and how it operates within web browsers. It covers essential programming concepts, data types, and the historical context of programming languages, including the differences between compiled and interpreted languages. Resources and session objectives are provided to enhance learning and engagement during the event.

Uploaded by

julia.miramazsa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Boolean Coding Weekend Intro to JS

The document outlines a coding weekend event focusing on an introduction to JavaScript, detailing its significance, features, and how it operates within web browsers. It covers essential programming concepts, data types, and the historical context of programming languages, including the differences between compiled and interpreted languages. Resources and session objectives are provided to enhance learning and engagement during the event.

Uploaded by

julia.miramazsa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 162

Coding Weekend: Jan 22nd -

24th

Session 2: Intro to JS

1
HTML Intro

Welcome

Get yourself comfy.

How to get the best from this session?

2
Here’s your companion resource

https://boolean-uk.github.io/coding-weeken
d/

Links
- Slides
- Other resources
- recordings
- feedback form
Here’s a sneak peek at yesterday’s and
today’s sessions..
HTML Intro

Session Objectives: Intro to JS

● Explain that JavaScript is a programming language


that helps us solve problems

● Translate a problem domain into JavaScript and solve


it

● Use documentation to learn and apply new knowledge


HTML Intro

Software Developer - Course Map

https://boolean-uk.github.io/coding-weekend/2022/jan/course-map.html

6
Intro to JavaScript

7
Intro to JavaScript

JavaScript

8
Intro to JavaScript

Why JavaScript?

Today JavaScript is everywhere! You use it to program things from toasters to spaceship apps,
frontends, backends and pretty much anything you can think of

However, it is still the only language that is natively run by browsers, and so, it allows you to do
some unique things, like:

- Create, read, update and delete elements on the page


- React to user events (clicks, scrolls, etc)
- Validate data entered by the user
- Check which browser is being used
- Check the current size of the screen
- And more…

These features allow us to create entire applications within the browser

9
Intro to JavaScript

What do we need to start writing JavaScript?


A text editor A browser

Looks familiar?

10
Intro to JavaScript

What do we need to start writing JavaScript?


Like with CSS, we can either write our JavaScript:

In-line OR External file

<!DOCTYPE html> <!DOCTYPE html> console.log('Hey there!');


<html lang="en"> <html lang="en"> // console.log() will display
<head> <head> what we put inside the
<meta charset="UTF-8" /> <meta charset="UTF-8" /> parentheses in the browser
<title>Document</title> <title>Document</title> console
<script> <script src="./index.js"> // this is a comment, btw,
console.log('Hello!'); </script> and has no effect on the code
</script> </head> itself!
</head> <body></body>
<body></body> </html>
</html>

index.html index.html index.js

11
But How?

How does this


work?
Intro to JavaScript

What is a programming language?


It is a formal language that specifies a group of input instructions that
can be used to produce an output

formal language
a series of symbols that respect grammatical and syntactical rules

input instructions
by knowing the rules we can generate instructions to be executed

an output
by following our instructions, the computer can produce a visible output

13
Intro to JavaScript

What is a programming language?

Language

Input instructions Computer Output result

14
Intro to JavaScript

The analytical machine


A bit of history - how we got to where we are today

What now appears to be a simple concept was definitely not in the 19th century:
in full industrial revolution, specialized machines were built following the dictates of Taylorism (and then Fordism)

In 1837, Charles Babbage designed a very complicated machine


the size of a room and powered by a large steam chamber, a machine
that was not specialized but could be programmed by a technician to
perform always different calculations, with the following characteristics:

● An instructional language created by Ada Lovelace (the first


programmer in the world)

● A system for giving instructions through punch cards

● An output system consisting of a printer and a series of


needles to make graphs to write the result

15
Intro to JavaScript

Punch cards
How code was once written

Punch cards for the analytical machine Programmers using a punch card machine in 1970

16
Describing the world

JavaScript describes the world

Numbers: Number, BigInt


Words, letters: String
Lists Array
Relationships Object
Operations: Operators
On/Off Boolean
Continuing processes Loops and iterators
Outcomes that depend on conditions If / else

17
Intro to JavaScript

Representing information
Binary code

We have information such as numbers, text, images and sounds that we want to be
able to represent and process in a computer

At a basic level, a computer works only with the values 0 and 1

This basic element of representation is called a bit (binary digit)

With a bit, we can already represent any kind of information that is made up of 2 states

Like:

Day or True or
Night False

On or Right or
Off Wrong

🌝 🌚 ✅ ❌
18
Intro to JavaScript

Representing information
Counting in binary

A good way to think about binary is to think about counting

In a decimal system, we have 0 to 9, we go: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13...etc

See what happened when we reached our last single digit? We just added a 1 on the left, and went back to 0 on the right to
represent the next number.

Now, if we had 0 to 1 instead, what would counting look like?


0 1 2 3 4 5 6 7 8
0, 1, 10, 11, 100, 101, 110, 111, 1000, etc…

Another way to think about it is: from right to left, each number is worth double the previous one if it’s on (1)
128 64 32 16 8 4 2 1
0 0 0 0 0 0 0 0

Q: What number is 10011? What’s the highest number you can reach with 8 digits (00000000)?

19
There are 10 types of people in this world:
those who understand binary,
and those who don’t.

20
Intro to JavaScript

Representing information
Binary code

To be able to represent more values, we can use a sequence of bits

1 bit gives us 2 values: 0, 1

2 bits gives us 4 values: 00, 01, 10, 11

3 bits gives us 8 values: 000, 001, 010, 011, 100, 101, 110, 111

How many values will 4 bits give us? How about 8 bits?

4 bits are called a 8 bits are called a


1 is called a bit
nibble byte
21
Intro to JavaScript

Representing information
Binary code

1 Bit Bit = 0 or 1

1 Byte Byte = 8 bit

1 Kilobyte KB = 1024 bytes

🔍 1 Megabyte

1 Gigabyte

1 Terabyte
MB

GB

TB
=

=
1024 KB

1024 MB

1024 GB

1 Petabyte PB = 1.024 TB

22
Intro to JavaScript

Representing information
Binary code

23
Intro to JavaScript

Representing characters
ASCII: (American Standard Code for Information Interchange) is a
code used for character encoding.

The ASCII standard was published by the American National


Standards Institute (ANSI) in 1968. Decimal Binary Character
Each character is encoded using 8 bits (or a byte).
65 1000001 A
Although ASCII has 8 bits, one of those bits is used for error
checking, leaving it with 7 available bits to represent characters.
66 1000010 B
Q: How many characters can be represented using ASCII?
67 1000011 C
UTF-8 is another character encoding format that uses between 1
and 4 bytes and can represent all possible 1,112,064 unicode 90 ??? ???
characters available. UTF-8 is the most popular encoding on
the web, being used by 96% of all websites.

24
Intro to JavaScript

Representing images

Images are represented by pixels

A pixel is the smallest single point in an image

Pixels can be represented using fewer of more bits

25
Intro to JavaScript

Representing images

Q: If we used a single bit to represent a pixel,


how many colors would our image have?

26
Intro to JavaScript

Representing images

That’s right, 1 bit gives us only 2 colors to choose from

So we’d pretty much be stuck with black and white pixels

27
Intro to JavaScript

Representing images

With 8-bits (or a byte) we get 256 colors

We can already do a bunch of cool things with that

Because of how cheap it is to store 8-bit images, this format was


widely used in game graphics for a while, and it’s still super
popular today for those of us who enjoy a bit of nostalgia

28
Intro to JavaScript

Representing images

Monitors use RED, GREEN and BLUE lights for each


pixel

Each color light gets a byte to tell it from 0 to 255 how


bright it should be

Combined, they use 24 bits per pixel, which means


each pixel can produce a total of 16,777,216 colors

29
Intro to JavaScript

Representing images

From afar, these pixels combined create just the right illusion for us

30
Intro to JavaScript

Boolean algebra
Logical networks are the basic architectural elements of computers, and of all digital
processing equipment

Together with the concepts of Boolean algebra, they are the basis of every computer, from
the very first version to the latest processors of modern days

Here are the 3 main operators of Boolean algebra:

X NOT X Y AND X Y OR

0 1 0 0 0 0 0 0

1 0 0 1 0 0 1 1

1 0 0 1 0 1

1 1 1 1 1 1

31
Intro to JavaScript

A CPU

Several ANDs and ORs later...

32
Intro to JavaScript

Programming languages
Programming languages are a convenient way for us humans to deal with those 1s and
0s and tell the computer what we’d like it to do

According to Wikipedia there’s currently over 700 programming languages available

We can group them into 2 main categories (kinda):

- Compiled (turning code to 1s and 0s before the program can run)


- Interpreted (turning code to 1s and 0s as the program is running)

Compiled Interpreted
● ADA ● PHP
● C ● Javascript
● C++ ● Ruby
● Pascal ● Basic
● Fortran ● Python

33
Intro to JavaScript

Programming languages
Compiled languages

The instructions written by the programmer, or source code, is given to a program


called a compiler, which translates the code into machine code (binary!) ahead of
time and produces an executable file that the current machine can run

Compiled
Source code Machine Output
Machine code

34
Intro to JavaScript

Programming languages
Interpreted languages

The source code here is given to a program called an interpreter that runs it line by
line and tells the machine what to do in real time, with no compilation step
required, but generally much slower than compiled code

Interpreter
Source code Output
Machine

35
Intro to JavaScript

Programming languages
So, which is better?

Well, allow me to introduce the answer that you will very likely hear (and say) a million
times (sometimes per day) as a developer:

It depends
Like many things in the programming world, there is no right or wrong, just trade-offs

However, we can say that, in general, compiled languages perform better than their
interpreted counterparts

On the other hand, interpreted languages are more portable, i.e. they work on
multiple operating systems without having to be rewritten or recompiled, and can be
modified while they are running

Also, as you will learn, some languages live somewhere between interpretation and
compilation

36
Variables and Data Types

37
Types and expressions

Data types
From text and numbers to lists, people and actions, everything in JavaScript can be represented
using data types. Here are the most important ones to we’ll be going through to begin with:

Primitive types: These are units that cannot be broken down any further

Data Type Examples Purpose

Boolean true, false Answer yes or no questions

Number -10, 0, 1, 100, 12.5, etc Represent numeric things and do math

String "Hello there!" Represent text

Null null Represent explicit nothingness

Undefined undefined Represent implicit nothingness

38
Types and expressions

Data types
Composite types: These are units that can be broken down further

Data
Examples Purpose
Type

{
name: "Nico",
Represent any object with multiple properties
Object age: 33, using keys and values
hungry: true
}

[1, 2, 3]
["Buy milk", "Cook dinner", "Sleep"]
[
Array { name: "Nico", age: 33 }, Represent lists of things
{ name: "Serg", age: 28 },
{ name: "Rico", age: 27 }
]

39
Types and expressions

Booleans
There’s really not much we can do with a boolean by itself, yet, as we will see later on, they are
crucial to programming

We usually get true or false as a result of asking our program a question, like:

5 > 3: Is 5 greater than 3? true

5 > 10: Is 5 less than 10? false

We can use these answers to branch our logic, for example, it will allow us to turn these kind of
phrases into actionable code:

If the user is older than 18, let them in, otherwise, tell them to come back when they’re
older.

You can flip a boolean by adding an exclamation mark right before it:

!true becomes false


!false becomes true

40
Types and expressions

Booleans
Another cool thing that we can do with booleans is chain them together in a logical sequence or
ANDs and ORs. In JavaScript:

- && represents AND


- || represents OR (these are 2 vertical bar characters, not 2 lowercase Ls!)

Here’s are some examples

1) true && true


2) true && false
3) true && true && true && false
4) true || false
5) false || true
6) false || true || false

Q: What will each of those evaluate to?

41
Types and expressions

Numbers

Alright, let’s dig into our first data type. As you might expect, anything that you can usually do with
numbers you can do in JavaScript:

Addition: 10 + 10 gives you back 20


Subtraction: 10 - 11 gives you back -1
Multiplication: 10 * 10 gives you back 100
Division: 10 / 10 gives you back 1
Exponentiation: 10 ** 2 gives you back 100 (10 to the power of 2)
Modulos: 12 % 10 gives you back 2 (the remainder of 10 / 2)

42
Types and expressions

Numbers

As you’ve seen, we can also compare numbers to get a boolean back:

Is equal to: 10 === 10 gives you back true


Is not equal to: 10 !== 10 gives you back false
Is greater than: 10 > 10 gives you back false
Is less than: 10 < 10 gives you back false
Is greater or equal to: 10 >= 10 gives you back true
Is less or equal to: 10 <= 10 gives you back true

Finally, you are not limited to a single operation at a time, and you can also group operations together
with parenthesis:

1+2*3 gives you back 7 (multiplication takes precedence)


(1 + 2) * 3 gives you back 9 (with the (), we force addition to happen first)

43
Types and expressions

Numbers
Every data type in JavaScript gives you access to some useful properties, and number is no
exception, although there aren’t a lot of them.

To access these properties, you can add a dot . in front of the data type. When working with raw
numbers, since adding a dot might be interpreted as just trying to add decimals to our number, we
need to wrap the number in parenthesis to let JS know our true intent:

A couple of useful properties for numbers are .toFixed() and .toString() try them out in the console!

Q: What do they do? What type do they each return?

44
Types and expressions

Expressions
All those numbers and calculations we’ve seen so far are called expressions

An expression is just a bunch of code that results in a value when evaluated:

1 is an expression that results in 1


1 + 1 is an expression that results in 2
55 % 10 is an expression that results in 5
53 % 10 % 2 is an expression that results in 1
(10 + 10 + 10) * (20 + 20 + 20) is an expression that results in 1800

Etc…

As you see, an expression can be just a single number, or huge bunch of sub-expressions. What
matters is that you can consider them a unit of code that will give you back a value when
evaluated.

Q: What would happen if you typed 1 2 3 in the console?

Think and have a guess before trying it out, then check to see if your assumption was correct!

45
Types and expressions

Expressions
Now, let’s say that I have two calculations that depend on each other. For example:

- Sarah works full-time, and I know that she makes £50,000 a year
- Now, I want to know how much she makes each week
- And then how much she makes per working day

There’s 52 weeks in a year, so:

50000 / 52

Cool, that returns 961.5384615384615 (what’s with the long number? What would 10 / 3 return?)

Now I want to know how much she makes a day, knowing each week has 5 working days.

How would you do it?

46
Time for a quick
exercise
Solve that problem using the REPL

47
Types and expressions

Variables

If you managed to get the result, you may have thought that the process could have been smoother.
You probably either had to:

- Copy and paste the initial answer


- Write the same calculation twice and add the next operation

Q: What would have made it better?

48
Types and expressions

Variables
So far, we’ve been writing expressions in the console and getting a result back, but we haven’t had
any way to actually store the result of our expression so that we could refer to it later

As you might have guessed by now, JavaScript, pretty much like almost every other programming
language out there, has a mechanism that allows us to to just this: Variables

Here’s how it works. First let’s type:

const x = 50000 / 52

Now, let’s type:

x / 5

Awesome, so that worked just the same, but we didn’t have to repeat ourselves or copy paste stuff!

Now… before we move on, I’d like to tell you just one thing...ready?

49
NEVER USE
VARIABLE NAMES
LIKE “X”!!!!

50
Unless it actually makes
sense…
Which is… almost NEVER!

We can use pretty much anything for our variable name, as


long as it doesn’t start with a number or has any spaces
in between. So don’t be shy, make them descriptive!

51
Types and expressions

Variables
Now, if you all just typed variables in completely different ways every time, life would be chaos, so
programmers have come up with naming conventions to keep things consistent

Here are some of the popular ones:

snake_case 🐍 (hissssss!)

kebab-case 🍡 (this is a yummy Japanese dango, but you get the point)

camelCase 🐪 (bumpy!)

While the Python community loves their snake_case (makes total sense, right?), 99.9999999999%
of JavaScript users stick with camelCase, soLetsStickWithThatConventionToo!

Note: One more rule for naming variables is, you are not allowed to use reserved JS keywords because
JS already uses those words for other things

52
Types and expressions

Variables

Let’s talk a little more about variables:

const is short for constant, which means, once a variable has been declared using const, we won’t
be able to change it later on

Should you need to change a variable, there’s another keyword you can use instead: let

const age = 10
const age = 20 // ❌ cannot redeclare a variable
age = 20 // ❌ cannot reassign a constant

let age = 10
let age = 20 // ❌ cannot redeclare a variable
age = 20 // ✅ reassigning a *let* variable is perfectly fine!

Q: What kind of values do you think we can store in a variable?

53
Types and expressions

Variables

So, any valid JS data type can be stored in a variable. In some languages, we are forced to
specify the type of variable we are creating, like:

const age: number = 33


const name: string = "Nicolas"

However, in plain JavaScript, we don’t have to, in fact, we can’t even if we wanted to!

Q: Is that a good or a bad thing? Why?

54
Types and expressions

Variables

There are 3 terms to learn when dealing with variables: declare, initialize, and assign

Declare means to create a variable for the first time, using the const or let keywords

Initialize means to create a variable with an initial value.

Assign means to give a new value to an existing variable

We can declare a variable without assigning it an initial value, but this will only work with let

let age // ✅ perfectly valid statement! (declared, but not initialized)


const age // ❌ nope, error (consts must be initialized)

Q: What will be the value of age in the first statement?

55
Types and expressions

Variables

Many times, we want to reassign a value by using the value itself. For example, if we want to
increment the value by 10, we can do this:

let age = 20
age = age + 10

See? We are saying reassign age to be the current value of age plus 10

This is such a common operation, that JS gives us a shortcut for it:

age += 10

There’s also -=, *=, /=, %= and **=, they all work the same way

56
Types and expressions

Variables

In fact, there’s one particular operation that is so common that it got its own operator to make things
even shorter:

let age = 20
age++

And
let age = 20
age--

Q: What do you think these are doing?

57
Types and expressions

Variables

In fact, there’s one particular operation that is so common that it got its own operator to make things
even shorter:

let age = 20
age++

And
let age = 20
age--

Q: What do you think these are doing?

58
Types and expressions

Variables

Now you know that we can store values in variables for later use, keep it in mind, because we will be
using variables a lot in programming!

59
Strings

60
Types and expressions

Strings

Great, so now we know that we can store values in variables for later use. Keep that in mind, because
we will be using variables a lot in programming! Now let’s move on to the next data type: strings!

Strings are simply how we represent text within our programs, from a single character to a
whole book. In JS, we can create a string by wrapping our characters in single, double or back
quotes

"hey there!" // ✅
'hey there!' // ✅
`hey there!` // ✅

Q: Why might you prefer one over the other?

61
Types and expressions

Strings
Double and single quote strings are pretty much the same thing, but beware of:

'Hi I'm Nicolas'


Uncaught SyntaxError: Unexpected identifier

"She said "yes"!"


Uncaught SyntaxError: Unexpected identifier

See what happened there? One way to fix this is to use another kind of quotes to wrap it:

"Hi, I'm Nicolas"


'She said "yes"!'

Another way is to escape the quotes:

'Hi, I\'m Nicolas'

Using the backslash, we can let JS know that the character that comes next should not be taken
literally, but it’s just another character.

62
Types and expressions

Strings
We can add strings together by using the plus “+” operator. This is called concatenation:

"Hello" + "there!"

Q: What will be the result of that expression?

Here’s two ways you could fix it:


"hello" + " " + "there!"
"hello " + "there!"

But why do we care about the plus when we could just do the whole thing in a single string?
Well, take a look at this:
const teacher = "Nicolas"
"Hello" + teacher + "!"

Adding variables to a string is called interpolation, and you’ll be doing this a lot!

63
Types and expressions

Strings
One limitation of these kind of strings is they won’t allow you to go to the next line, meaning this will
happen:

"nice
one"
=> Uncaught SyntaxError: Invalid or unexpected token

There’s two ways to fix this: we can escape the newline character:

"nice \
one"
=> "nice one"

Or concatenate separate strings:

"nice " +
"one"
=> "nice one"

64
Types and expressions

Strings

If you actually wanted to go to the next line within your string, and not just the code, you can use the
special \n newline character:

"nice\none"
=> "nice
one"

Top tip

There are several special characters that need to be escaped in strings, go check them out on MDN

MDN is an awesome documentation site run by Mozilla, the people behind Firefox

65
Types and expressions

Strings

As a side note, while some languages are strict and won’t let you mix types together,
JavaScript is totally cool with it:

const age = 30
const name = "Maria"
name + " is " + age + " years old!"
=> "Maria is 30 years old!"

Although this may lead to unexpected behaviour in some cases, so use with care and always test!
"Hey " + {} + "!"
=> "Hey [object Object]!"

66
Types and expressions

Strings
Finally, we have strings wrapped in back quotes (or backticks), the technical term for this kind of
string is template literal:
`Hello there, person!`

These are a modern addition to JavaScript (2015), and they behave like regular strings for the most
part, but they have a couple of cool super powers! Watch this:
`nice
one`
=> "nice
one"

const yourName = "Nicolas"


`Hey there, ${yourName}!`
=> "Hey there, Nicolas!"

In short, they accept newlines without having to use \n, and they also have a special interpolation
syntax ${}, which can make things look much cleaner sometimes!
67
Types and expressions

Strings
Strings have a TON of useful properties, here’s a couple of really useful ones, but feel free to explore
more in the console!

"Nicolas".length
=> 7

"Nicolas".toUpperCase()
=> "NICOLAS"

Q: What do they do? What types do they return? Is the syntax for getting both properties the same?

Top tip
If you are ever unsure about what something does in JavaScript, google the mdn + term
I.e.: mdn touppercase (properties are case-sensitive, but google isn’t!)

68
Types and expressions

Strings
To wrap up strings for now, know that you can also compare strings, like you do with numbers:

"Nicolas" === "Nicolas"


=> true

"Nicolas" === "nicolas"


=> false // it’s case-sensitive

"a" > "b"


=> false

"b" > "a"


=> true

"a" > "A"


=> true // mmm, why? ASCII yourself that question

69
Arrays

70
Arrays and iteration

Arrays

So far we’ve been dealing with single values. An age variable is a single number, a name variable
is a single string. But what if we wanted to have not one, but several names stored for later?

Q: How would you do it with what you’ve learned so far?

71
Arrays and iteration

Arrays
We could certainly try something like this:

const name1 = 'Nicolas'


const name2 = 'Sergio'
const name3 = 'Steven'

And it may work for a while, but it will get increasingly hard to work with our data, and if we have to
manually create a new variable every time, soon things will become unmanageable. What if we
don’t even know how many names we have?

Instead, for this purpose JavaScript gives us a convenient data type: the array! Arrays are a single
data type used to represent a list of things

const names = ['Nicolas', 'Sergio', 'Steven']

You can see how we now have all 3 names under a single variable

72
Arrays and iteration

Array CRUD

Let me introduce you to a term you will see mostly when dealing with databases, but I think
conceptually we can apply it to many situations, and it makes things easier to remember: CRUD
It stands for:

Create (adding things)


Read (getting things)
Update (changing things)
Delete (removing things)

This is about managing resources. In this case, imagine our array is a box, and the elements
within an array are the resources we want to manage

73
Arrays and iteration

Array CRUD

So, let’s create an array:


const instructors = ['Sergio']

Creating in this context means adding a new element to the array. We do this by using helper
properties of our array: .unshift() and .push()

Using unshift, we can add elements to the start of the array:


instructors.unshift('Nico')
=> ['Nico', 'Sergio']

Using push, we can add elements to the end of the array:


instructors.push('Steven')
=> ['Nico', 'Sergio', 'Steven']

74
Arrays and iteration

Array CRUD

Reading means getting an element from the array. We can get a single element by using
array[index] syntax, or multiple by using the .slice() property

Using array[index], we can get a single element at that exact location:


instructors[0] // indices start at 0, not 1!
=> 'Nico'

Using .slice(firstIndex, lastIndex), we can get a segment of the array:


instructors.slice(1,3) // careful: last index is NOT INCLUDED
=> ['Sergio', 'Steven'] // this is a copy, the original array still has all 3

Q: What does each operation return? Why? What would we get back if the index didn’t exist?

75
Arrays and iteration

Array CRUD

Updating means replacing an element in the array. This works similarly to how reassigning a
variable does:

Using array[index] = newValue, we can swap the element at a specific location:


instructors[1] = 'Nathan'
=> ['Nico', 'Nathan', 'Steven']

76
Arrays and iteration

Array CRUD

Deleting means removing an element from the array. Similar to adding an element, we can
remove an element from the start or end of the array using .shift() and .pop()

Using shift, we can remove elements from the start of the array:
instructors.shift()
=> ['Nathan', 'Steven'] // Nico is gone!

Using pop, we can remove elements from the end of the array:
instructors.pop()
=> ['Nathan'] // And now Steven, too (although, in reality, this isn’t true)!

77
Arrays and iteration

Array CRUD

In addition to removing an element, shift and pop also return the removed element, so you can
do something handy like:

const instructors = ['Nico', 'Nathan', 'Steven'];


const instructor = instructors.pop();
console.log(instructor);

Q: What will that log?

There’s even a property to remove multiple elements from a range of indices called splice.
You can check out the docs for it here.

78
Objects

79
Objects and data

Objects

The final data type we’re going to cover is objects.

Let’s say you are trying to represent a person using code.

Q: What kind of attributes do you think are important to store about a person?
How would you store these attributes using what you know so far?

80
Objects and data

Objects
You might have ended up with something like this:
const firstName = 'Nicolas'
const lastName = 'Marcora'
const age = 33

Mmm, ok. What if we want to have a second person?


const firstName1 = 'Nicolas'
const lastName1 = 'Marcora'
const age1 = 33

const firstName2 = 'Sergio'


const lastName2 = 'Neves'
const age2 = 30

Q: What do you think about this code? How could it be better?

81
Objects and data

Objects

const person = {
firstName: 'Nicolas',
lastName: 'Marcora',
age: 33
}

Say hi to objects! JavaScript objects are a data type that consists of keys and values, wrapped with
curly braces

82
Objects and data

Objects

const person = {
firstName: 'Nicolas',
lastName: 'Marcora',
age: 33
}

keys go on the left, they are always strings,


although JS allows us to omit the quotes to keep things cleaner

Note: Quotes need to be added if you want to have a key with spaces or other special characters

83
Objects and data

Objects

const person = {
firstName: 'Nicolas',
lastName: 'Marcora',
age: 33
}

Each key has an accompanying value on the right hand side, together they form a key/value pair

Any valid JavaScript type can be a value: numbers, strings, booleans, null, undefined, even
arrays and objects themselves!

84
Objects and data

Objects

const person = {
firstName: 'Nicolas',
lastName: 'Marcora',
age: 33
}

Keys and values are separated using colons, and each pair is separated from the next using a comma

We can have as many pairs as we like

85
Objects and data

Object CRUD

Just like with arrays, we can create, read, update and delete key/value pairs

86
Objects and data

Object CRUD

So, let’s say we have an object:


const instructor = {}

Creating in this context means adding a new key/value pair

instructor['firstName'] = 'Nicolas'
=> { firstName: 'Nicolas' }

And, if you don’t have any special characters, this cleaner syntax does the same thing

instructor.lastName = 'Marcora'
=> { firstName: 'Nicolas', lastName: 'Marcora' }

87
Objects and data

Object CRUD

Reading means getting the value of a particular key

Again, we can do this with the squared brackets, or with dot notation

instructor['firstName']
=> 'Nicolas'

instructor.lastName
=> 'Marcora'

Q: What do you think will happen if we try to access a key that doesn’t exist?

88
Objects and data

Object CRUD

Updating means changing a key to a different value, it works exactly like creating a new key, only
if the key already exists, we are overriding it

instructor['firstName'] = 'Sergio'
=> { firstName: 'Sergio', lastName: 'Marcora' }

instructor.lastName = instructor.lastName.toUpperCase()
=> { firstName: 'Sergio', lastName: 'MARCORA' }

89
Objects and data

Object CRUD

Deleting means removing a key/value pair from an object. We can do this using the delete
operator

delete instructor.lastName
=> { firstName: 'Sergio' }

If the key existed and it got successfully deleted, we’ll get back true
If it failed for any reason, we get false

90
Objects and data

Representing data
We can use the data types we’ve learned so far to reseprent pretty much anything you can possibly
imagine. Like a list of todo items:

[
{
id: 1,
title: 'buy milk',
completed: true
},
{
id: 2,
title: 'conquer the world',
completed: false
}
]

91
Objects and data

Representing data
Or even a character in a video game:
const character = {
name: 'Nicolas',
hp: 100,
hungry: true,
weapon: {
name: 'Excalibur',
damage: 20,
durability: 90
},
inventory: [
{ name: 'HP Potion', icon: './hp-potion.jpg', hp: 30 },
{ name: 'Skewer', icon: './skewer.jpg' }
]
}

Q: If you have a character, how can you reach the hp value of the HP Potion?
92
Objects and data

Immutability

Look at this code:

const user = 'Nicolas'

Because we are using const here, we know the variable will always point to the same value, since it
cannot be reassigned. Now… type that in the console and try to make it so that user gives you
anything other than ‘Nicolas’ … without refreshing the page! 😜

Q: Could you do it? What about all the other data types we’ve learned so far?

93
Objects and data

Immutability

All the primitive types we saw are immutable, meaning that if one of these values gets assigned to
a constant variable, no matter what you do, they cannot be changed. As a result, you know that
that variable will stay exactly the same for the duration of the program

Arrays and objects however, are mutable, so we can actually change them in place

Q: What are the consequences of dealing with mutable data types? 🤔

Later in the course, we will learn some techniques to deal with objects and arrays immutably

94
Time for some live
coding
Let’s explore mutation!

95
Time for some practice
1) How would you represent a single email in JavaScript?

Think about all the info an email could have and you to best represent
it using the data types you already know

2) How about a whole inbox?

Challenge
Create the inbox, add a new email, update an existing emails

96
Conditional Flow

97
Control flow

Conditions
Remember how we said booleans on their own didn’t do much but they are a crucial part of
programming? Well, here’s where they really start to shine!

Up until now, whatever we were writing was being executed when our program ran. Conditions allow
us to execute some code only if a condition is met. The main way to implement a condition in
JavaScript is by using an if statement. Take a look at the following example:

if (true) console.log('WOOOHOOOO!')

Q: What do you think will happen if we run this example in the console?

if (false) console.log('WOOOHOOOO!')

Q: And this one?

98
Control flow

Conditions

Now, here’s where programming gets interesting, so let’s ponder on this for a bit:

Everywhere a value goes, an expression that results in that same value can also go and it
will have the same result

Things are starting to get really abstract, and it’s perfectly normal if at this stage this phrase
makes no sense, but this is a key concept in programming, and it is one that will totally change
how you see code and make you a much better developer once you deeply understand it.

So, let’s just take a minute or two to really think about what this means... R
99
Everywhere a value goes,
an expression that results
in that same value can also
go
and will have the same
result

100
Control flow

Conditions
Let’s explore that concept in action:

const age = 18

console.log(18) // what will this log?


console.log(age) // and this?

const ageInTenYears = age + 10

console.log(28) // what will this log?


console.log(age + 10) // and this?
console.log(ageInTenYears) // and this?

Ok, but what does this have to do with if statements?

Q: Do you know any expressions that result in true or false?

101
Control flow

Conditions
As it turns out, within the parentheses of the if statement, you are not just limited to true or false,
but can enter any expression that results in true or false:

if (true) alert("You may come in.")

const age = 20
if (age > 18) alert("You may come in.")

And this is effectively how in code we can do something if a specific condition applies.
In this case, if our code was an English sentence it would be something like:

Allow the user to come in only if they are over 18

Top Tip!
Always try to reason about your code as it if was a sequence of English sentences. Not only
will it help you understand your code better, it will also lead you to writing more readable code.

102
Control flow

Conditions

Remember what else we can do with booleans? We can chain them with ANDs (&&) and ORs (||s)!
This allows us to expand our vocabulary within our parenthesis. For example, we can express:

Allow the user to come in only if they are over 18 AND under 65

Translated to code, that would be:

if (age > 18 && age < 65) alert("You may come in.")

103
Control flow

Conditions

Let’s evaluate this code in our heads and see if we can get to the right answer. Learning to run
code in your head will get you closer to understanding how the language works and will make you a
much more proficient programmer, so you should do this often!

const age = 30

(age > 18) && (age < 65)


(30 > 18) && (30 < 65) // before we know if age is greater or lower, we need to know what it is
(true && true) // before we can evaluate the AND, we need to resolve left and right
true // because left AND right are true, the result should be true

Now we’ve tried it in our heads, let’s actually run the code in the console and check if we’re right

104
Control flow

Refining your experience

Write a little
code

Predict the
outcome

Verify the
outcome

Change the code

105
Control flow

Conditions

Here’s a couple more for you to do:

const age = 15
age > 18 && age < 65

const age = 65
age > 18 && age < 65

const age = 65
age >= 18 && age <= 65

106
Control flow

Conditions
What if we want to do something like:

Allow the user to come in only if they are over 18,


otherwise tell them to come back when they are older.

Now we’ve added a second clause to our condition:


Do A if a condition is true, otherwise do B.

To achieve this, JS gives us the else keyword to use in combination with our if:

const age = 20
if (age > 18) alert("You may come in.")
else alert("Sorry, come back when you are older.")

107
Control flow

Conditions

Let’s keep expanding our vocabulary. Now we’d like to write this program:

If the user is younger than 18, tell them to come back when they are older.
If the user is older than 65, tell them to enjoy their retirement.
Otherwise, let them in.

Since we now have 3 possible actions to do, we need another if in between. For this purpose, JS gives
us else if:

if (age < 18) alert("Come back when you're older!")


else if (age > 65) alert("Enjoy your retirement!")
else alert("You may come in.")

108
Control flow

Conditions

You may have noticed that up until now, we’ve been doing 1 single thing after each condition, but
what if we wanted to do more?

To do this, JS gives us blocks. A block is a chunk of code wrapped with curly braces ({}). The block
can be empty, or it can have as many lines of code as we want.

if (age < 18) {


alert("Come back when you're older!")
confirm("Are you older now?")
alert("Just kidding, you still can't come in.")
}

109
Control flow

Conditions

if, else if and else can all be followed by a block if needed. In fact, it is considered best practice to
always use blocks in your conditions, even if you just want to do one thing

The reason we’re showing you both with and without blocks is because:
1) We want you to understand how the language actually works
2) You are likely to see both in the wild eventually
3) It is a good idea to differentiate between best practice and what’s possible

110
Control flow

Truthy and falsy values

Remember how we talked about JavaScript being very forgiving and trying to make things work?
Remember coercion? So far we’ve seen expressions that evaluate to true or false, but what if we
put something else between those parentheses?

if ("Hello!") alert("Oh, hi!")

What should JS do here? alert or not? "Hello!" is not true nor false, but because JavaScript needs
one here to determine what to do, it will coerce the value into a boolean behind the scenes.

There’s a Boolean() function that you can use to pass a value and see whether it is truthy or falsy

Try some values in the console!

111
Types and expressions

Null & Undefined

Both these types represent a lack of value.

Null represents an explicit lack of value, as in, I, the programmer want to let you know that this value
is not currently here
let userName = null // I hereby declare userName is currently not here

Undefined is more of a casual lack of value, like “I had a peek in here and I didn’t find anything” kind
of emptiness
let userName // I … just didn’t give a value to this variable so it’s empty
let userName = undefined // you could do this... but you have null 🤷

Note: These rules are more about intention than about 100% accuracy, so expect to find the
occasional null where an undefined would have made more sense and vice-versa

112
Types and expressions

Null & Undefined


By far, two of the most common errors you will see in your programming journey are:

These happen when you try to access a property of a value that you thought was not empty, only
to have cold hard reality come crashing down on you and teach an annoying lesson

let userName = null


userName.toUpperCase() // surely I got a string, right!?

let userName
userName.length // ...this time, for sure!

These examples are rather obvious, but in the real world, when you have several lines of code in
between and the flow of your program is filled with forks and roundabouts, you will no doubt
encounter these two friends along the way from time to time

113
Loops

114
Arrays and iteration

For Loops

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


console.log(i)
}

Q: If you had to guess, what do you think this code is doing?

115
Arrays and iteration

For Loops

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


console.log(i)
}

We start with the for keyword

116
Arrays and iteration

For Loops

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


console.log(i)
}

And again we have parenthesis, but this time there’s more going on, so let’s break it down

If you look closely, there’s 3 sections divided by semicolons: (1 ; 2 ; 3)

117
Arrays and iteration

For Loops

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


console.log(i)
}

The first step is called initialisation. The expression we write here will run only once, before the whole loop
begins

Most of the time, you will see this loop with an i variable that starts at 0, and will be incremented as we loop

118
Arrays and iteration

For Loops

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


console.log(i)
}

The middle step is called condition. The expression we write here will be evaluated before every iteration. If
the expression is truthy, the loop will continue running, if it is falsy, the loop ends

Here, we are checking if the i variable we created is lower than 10

119
Arrays and iteration

For Loops

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


console.log(i)
}

The last step is called the finalisation. The expression we write here will run at the end of every iteration

120
Arrays and iteration

For Loops

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


console.log(i)
}

And then we have our good old friend the block. This code will run over and over as long as the condition
remains truthy, and within it, we have access to any variables we declared in the initialization step

121
Arrays and iteration

For Loops

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


console.log(i)
}

Q: So, let’s try explaining what’s going on here in plain English once again

122
Arrays and iteration

For Loops

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


console.log(i)
}

Create a variable i and set it to 0. As long as i is lower than 10, log i, then increase it by 1.

123
Arrays and iteration

For Loops

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


console.log(i)
break
}

You can end a loop early by using the break keyword

Q: What will this code do?

124
Arrays and iteration

For Loops

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


console.log(i)
if (i > 5) break
}

Q: And this one?

125
Functions

126
Functions

Functions

You can’t spell functions without fun!

This is the last data type we’ll be covering for the time being, but get ready, because it will change
everything!

At their core, functions are a way for us to describe an action we want to perform

127
Functions

Functions

function add(a, b) {
return a + b
}

A function is a callable piece of code that can take multiple inputs and return a single output

In other words, you call them and give them some info, they do something, and they give you
something back

128
Functions

Functions

function add(a, b) {
return a + b
}

To define a function, you start by using the function keyword

129
Functions

Functions

function add(a, b) {
return a + b
}

Then you may give it a name. Names are arbitrary and again you should aim to make them descriptive

Data types like strings and arrays don’t DO anything, but functions do, so it is a good idea to name your
functions using commanding verbs and name your data using nouns

Q: If you see two names in the wild, one is multiplication and the other one is multiply, what do you
expect each to be?

Top Tip
you may also choose to not give your function a name in some cases, these are called anonymous functions
130
Functions

Functions

function add(a, b) {
return a + b
}

Next up we have the parameters. These are the external pieces of data that your function will
expect when you call it later on. You can have none or as many as you need for your function to
work

They are wrapped by parentheses and separated by commas

The names again are arbitrary and you should think really carefully when creating them, making
sure the reader will easily understand what’s going on when they see it
131
Functions

Functions

function add(a, b) {
return a + b
}

Lastly, we have our function’s block. This is the code we want out function to run

Within this block, we will have access to all the parameters we’ve defined, and we can also use the
special keyword return to end the function and give back a single value as a result

Q: What do you expect will happen if you don’t specify a return within your function?

132
Functions

Functions

function add(a, b) {
return a + b
}

You can think about it like a black box that asks you for something, does some stuff, and gives you
something back depending on what you gave to it

5 a
add 8
b
3
133
Functions

Functions
While some functions you will define yourself and you will be able to see exactly what they do, other
functions will be provided to you by JavaScript or by a library and you may not really know how
exactly they work inside, but you don’t really care as long as you get the output you expect given
your inputs

For example, we don’t really care how add below was written, as long as it:
- gives me back 8 if I give it 5 and 3
- gives me back 10 if I enter 6 and 4
- etc...

5 a
add 8
b
3
134
Functions

Functions
It’s important to think about a function in terms of its signature. By that we mean:
- What kind of inputs does it need?
- What kind of output does it give?

In this case, for example, add takes in 2 numbers, and returns a number
As a shortcut, you can think about it like this: (number, number) => number

number
5 a number
add 8
number
b
3
135
Functions

Functions
Here’s another function we just made up out of thin air:

string
“hello” word string
shout “hello!!!”
number
exclamations
3

Q: How would you write its signature using the notation we learned earlier?
Can you write an implementation for this function in the console?

136
Functions

Functions
Remember the alert function?

??? alert ???

Q: What is its signature? 🤔


137
Functions

Functions
That’s right, sometimes a function will always return undefined. Since that’s a pretty useless value to
return, we can assume that we call it for another reason, it must be doing something else that’s
useful!

string undefined
“Welcome!” message alert undefined

Whenever a function does anything other than working with the inputs given and give you a useful
output, we say that function is performing a side-effect, and we call that function impure

Pure functions are the ones that do nothing else, they just receive inputs and give you a value back

138
Functions

Declaring, passing and calling functions


This code:
function add(a, b) {
return a + b
}

Is not actually doing anything yet, we’re just declaring how the function will work when we call it
later with ()

console.log(add(5, 3)) // what will this do?

add(5, 3) is an expression that gives back 8. We could have also done it like this:

const result = add(5, 3)


console.log(result)

Remember!! Wherever a value goes, an expression that results in the same value can also go!
139
Quiz time!
Without running any code, what will these expressions
evaluate to?

1. add(10, 10)

2. add(add(15, 15), add(20, 20))

3. add(add(add(1, 2), add(3, 4)), add(add(5, 6), add(7, 8)))

Show your work ;)

140
Answer time!
Without running any code, what will these expressions
evaluate to?

1. 20

2. 70

3. 36

Show your work ;)

141
Functions

Declaring, passing and calling functions

Something really cool that makes functions extremely powerful in JavaScript is that we can treat
just like any other value in the language

As a rule of thumb: Wherever you can put the number 42, you can also put a function

Q: What do we mean by that? Thing about places we’ve seen so far where the number 42 would fit

142
Functions

Declaring, passing and calling functions

Let’s explore this code in the console:

function add(a, b) {
return a + b
}

const aVariable = add

const anArray = [add, add, add]

const anObject = {
name: "Nicolas",
property: add
}

143
Functions

Declaring, passing and calling functions


So, if we just refer to a function by its name, without calling it using the (), we are just passing that
box around, ready to be called whenever we are ready

You can even pass a function as an argument to another function! 🤯


function add (a, b) {
return a + b
}

function callAnotherFunction (func) {


return func(50, 30)
}

callAnotherFunction(add)

Q: What’s happening here? What will it return?


144
Functions

Declaring, passing and calling functions

The technical word for this feature is first-class functions

Although the concept might seem a little weird right now, you will see just how useful it can be and
how it’s pretty much everywhere you look in the JavaScript world!

Let’s take a look at the first couple of functions that accept another function as an argument

145
Functions

setTimeout

setTimeout is another global function provided by JavaScript. We can use it to defer the execution
of a function. Here’s how we use it:

function sayHi () {
console.log('Hi!')
}

setTimeout(sayHi, 10000)

Q: What do you think this code will do?

146
Functions

setTimeout
Let’s visually explore how this function works

(function, number) => number


function
sayHi handler number
setTimeout 12734
number
timeInMs
10000

Let’s try to describe it step by step


- It takes 2 arguments: a function and a time in milliseconds
- It returns a... number??? 🤔
- After the time we specified has elapsed, it calls the function we gave it

Q: What’s up with that number it returns? Any guesses?

147
Functions

setTimeout

That number is the id of the timeout that was created, and we can use it if we want to cancel the
timeout before it happens if we need to. To cancel it, we use another function called clearTimeout:

let timeoutId = setTimeout(sayHi, 10000)


clearTimeout(id)

Since setTimeout returns that id, we can assign it to a variable for later use!

148
Functions

setInterval

setTimeout has a sibling function called setInterval

It works pretty much exactly the same way, but with one big difference: instead of just once, the
function you provide will be called every X ms

setInterval(sayHi, 3000)

Try that one in the console, then try making it stop!

149
Functions

Inline functions

setTimeout(function sayHi () {
console.log('Hi!')
}, 10000)

This code does exactly the same thing as the previous example

Creating a function right there in the argument is called inlining the function

Q: Do we still have to give our function a name here?

150
Functions

Inline functions

setTimeout(function() {
console.log('Hi!')
}, 10000)

That’s right, this is a good use case for an anonymous function, since we don’t plan to call that
function by name anywhere else

It’s super important to note that we’re not the ones calling the function, we are defining it,
then passing it down to setTimeout, and it’s setTimeout itself that calls it later on when it
wants to!

151
Functions

Scope

One last important thing to know about functions is scope

const friend = 'Darkness'

function greetFriend () {
console.log(`Hello ${friend}, my old friend!`)
}

Q: What will this function log when called?

152
Functions

Scope

Q: How about now?

const friend = 'Darkness'

function greetFriend(friend) {
console.log(`Hello ${friend}, my old friend!`)
}

greetFriend()

153
Functions

Scope

Q: How about now?

const friend = 'Darkness'

function greetFriend(friend) {
console.log(`Hello ${friend}, my old friend!`)
}

greetFriend(“Steven")

154
Functions

Scope

Q: One more for good luck!

let friend = 'Darkness'

function greetFriend (friend) {


const otherFriends = ['Kitty', 'Moto', "is it me you’re looking for?"]

for (const friend of otherFriends) {


console.log(`Hello ${friend}, my old friend!`)
}
}

155
Functions

Scope

So what’s happening here? When we type the name of a variable in our program, a lookup begins
to find the closest variable with that name that has been declared

Q: What if no variable with that name has been declared?

156
Functions

Scope

function greetFriend () {
const friend = 'Darkness'
}

console.log(`Hello ${friend}, my old friend!`)

Q: What will happen here? Why?

157
Functions

Scope
As you have seen, another important part of understanding scope is knowing what is accessible to
us

When we define a variable within a function, it is only accessible to us within the function. This
also happens when you define a variable in other blocks, like a for loop:

const friends = ['Kitty', 'Moto', 'is it me you’re looking for?']


for (const friend of friends) {
console.log(`Hello ${friend}, my old friend!`)
}
console.log(friend)

Boom! That friend variable does not exist outside of the for loop. These are very common errors, and
when you see one, remember to ask yourself:
- Do I have access to this variable?
- What is the first variable with this name that I will find?
158
Wrapping up

From strings and numbers, to objects, arrays and


functions, these building blocks that make up pretty much
all of the JavaScript you will see from now on

There’s more to learn about these types, and we’ll be


exploring those things as we go along, but if you keep
practicing and improving your understanding on what we’ve
seen so far, you’ll be well on your way to becoming a
JavaScript guru!

We now have enough knowledge to deeply understand how


we can use JS to work with our pages. Things are about to get
really exciting!

159
Time for some practice
Two functions to write:

1) getRandomNumber: Generate a random number between a min and max


value

Call that function ten times with a min value of 1 and a max value of
100. Log the number returned

2) isOddOrEven: Check if a number given is odd or even

Generate a random number between 1 and 100 then Call isOddOrEven


to find out whether (or not) the generated number was even. Log the
result
160
Let’s build snake!

161
Snake

Starting point:

https://github.com/boolean-uk/demo-snake

You might also like