Boolean Coding Weekend Intro to JS
Boolean Coding Weekend Intro to JS
24th
Session 2: Intro to JS
1
HTML Intro
Welcome
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
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:
9
Intro to JavaScript
Looks familiar?
10
Intro to JavaScript
11
But How?
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
Language
14
Intro to JavaScript
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)
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
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
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
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.
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
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?
Representing information
Binary code
1 Bit Bit = 0 or 1
🔍 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.
24
Intro to JavaScript
Representing images
25
Intro to JavaScript
Representing images
26
Intro to JavaScript
Representing images
27
Intro to JavaScript
Representing images
28
Intro to JavaScript
Representing images
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
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
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
Compiled Interpreted
● ADA ● PHP
● C ● Javascript
● C++ ● Ruby
● Pascal ● Basic
● Fortran ● Python
33
Intro to JavaScript
Programming languages
Compiled languages
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
Number -10, 0, 1, 100, 12.5, etc Represent numeric things and do math
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:
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:
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:
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:
42
Types and expressions
Numbers
Finally, you are not limited to a single operation at a time, and you can also group operations together
with parenthesis:
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!
44
Types and expressions
Expressions
All those numbers and calculations we’ve seen so far are called expressions
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.
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
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.
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:
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
const x = 50000 / 52
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!
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
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
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!
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:
However, in plain JavaScript, we don’t have to, in fact, we can’t even if we wanted to!
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
We can declare a variable without assigning it an initial value, but this will only work with let
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
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--
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--
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!` // ✅
61
Types and expressions
Strings
Double and single quote strings are pretty much the same thing, but beware of:
See what happened there? One way to fix this is to use another kind of quotes to wrap it:
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!"
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"
"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"
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:
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?
71
Arrays and iteration
Arrays
We could certainly try something like this:
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
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:
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
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()
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
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:
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:
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
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
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
}
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
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
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
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
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
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
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!')
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
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:
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:
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
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
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
Write a little
code
Predict the
outcome
Verify the
outcome
105
Control flow
Conditions
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:
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:
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.
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
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?
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
111
Types and expressions
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
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
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
115
Arrays and iteration
For Loops
116
Arrays and iteration
For Loops
And again we have parenthesis, but this time there’s more going on, so let’s break it down
117
Arrays and iteration
For Loops
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
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
119
Arrays and iteration
For Loops
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
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
Q: So, let’s try explaining what’s going on here in plain English once again
122
Arrays and iteration
For Loops
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
124
Arrays and iteration
For Loops
125
Functions
126
Functions
Functions
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
}
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
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?
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
Is not actually doing anything yet, we’re just declaring how the function will work when we call it
later with ()
add(5, 3) is an expression that gives back 8. We could have also done it like this:
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)
140
Answer time!
Without running any code, what will these expressions
evaluate to?
1. 20
2. 70
3. 36
141
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
function add(a, b) {
return a + b
}
const anObject = {
name: "Nicolas",
property: add
}
143
Functions
callAnotherFunction(add)
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)
146
Functions
setTimeout
Let’s visually explore how this function works
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:
Since setTimeout returns that id, we can assign it to a variable for later use!
148
Functions
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)
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
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
function greetFriend () {
console.log(`Hello ${friend}, my old friend!`)
}
152
Functions
Scope
function greetFriend(friend) {
console.log(`Hello ${friend}, my old friend!`)
}
greetFriend()
153
Functions
Scope
function greetFriend(friend) {
console.log(`Hello ${friend}, my old friend!`)
}
greetFriend(“Steven")
154
Functions
Scope
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
156
Functions
Scope
function greetFriend () {
const friend = 'Darkness'
}
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:
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
159
Time for some practice
Two functions to write:
Call that function ten times with a min value of 1 and a max value of
100. Log the number returned
161
Snake
Starting point:
https://github.com/boolean-uk/demo-snake