The JavaScript Beginner's Handbook
The JavaScript Beginner's Handbook
Preface
Introduction to JavaScript
History
Just JavaScript
Syntax
Semicolons
Values
Variables
Types
Expressions
Operators
Precedence
Comparisons
Conditionals
Strings
Arrays
Loops
Functions
Arrow Functions
Objects
Object properties
Object methods
Classes
Inheritance
1
Asynchonous Programming and Callbacks
Promises
Async and Await
Variables scope
Conclusion
2
Preface
The JavaScript Beginner's Handbook follows the
80/20 rule: learn in 20% of the time the 80% of a topic.
Enjoy!
3
Introduction to
JavaScript
JavaScript is one of the most popular programming
languages in the world.
websites
web applications
server-side applications using Node.js
4
languages like C would need, and provides many
constructs which allow you to deal with highly
powerful variables and objects.
dynamic: opposed to static programming
languages, a dynamic language executes at
runtime many of the things that a static language
does at compile time. This has pros and cons,
and it gives us powerful features like dynamic
typing, late binding, reflection, functional
programming, object runtime alteration, closures
and much more. Don't worry if those things are
unknown to you - you'll know all of those at the
end of the course.
dynamically typed: a variable does not enforce a
type. You can reassign any type to a variable, for
example, assigning an integer to a variable that
holds a string.
loosely typed: as opposed to strong typing,
loosely (or weakly) typed languages do not
enforce the type of an object, allowing more
flexibility but denying us type safety and type
checking (something that TypeScript - which
builds on top of JavaScript - provides)
interpreted: it's commonly known as an
interpreted language, which means that it does
not need a compilation stage before a program
can run, as opposed to C, Java or Go for
example. In practice, browsers do compile
JavaScript before executing it, for performance
reasons, but this is transparent to you: there is no
additional step involved.
multi-paradigm: the language does not enforce
any particular programming paradigm, unlike Java
5
for example, which forces the use of object-
oriented programming, or C that forces imperative
programming. You can write JavaScript using an
object-oriented paradigm, using prototypes and
the new (as of ES6) classes syntax. You can write
JavaScript in a functional programming style, with
its first-class functions, or even in an imperative
style (C-like).
6
History
Created in 1995, JavaScript has gone a very long way
since its humble beginnings.
7
JavaScript is now also the language powering
databases and many more applications, and it's even
possible to develop embedded applications, mobile
apps, TV sets apps and much more. What started as a
tiny language inside the browser is now the most
popular language in the world.
8
Just JavaScript
Sometimes it's hard to separate JavaScript from the
features of the environment it is used in.
9
Syntax
In this little introduction I want to tell you about 5
concepts:
white space
case sensitivity
literals
identifiers
White space
JavaScript does not consider white space meaningful.
Spaces and line breaks can be added in any fashion
you might like, even though this is in theory.
Case sensitive
JavaScript is case sensitive. A variable named
something is different from Something .
Literals
10
We define as literal a value that is written in the
source code, for example, a number, a string, a
boolean or also more advanced constructs, like Object
Literals or Array Literals:
5
'Test'
true
['a', 'b']
{color: 'red', shape: 'Rectangle'}
Identifiers
An identifier is a sequence of characters that can be
used to identify a variable, a function, an object. It can
start with a letter, the dollar sign $ or an underscore
_ , and it can contain digits. Using Unicode, a letter
can be any allowed char, for example, an emoji 😄.
Test
test
TEST
_test
Test1
$test
Comments
11
Comments are one of the most important part of any
program. In any programming language.
Like this:
// a comment
true //another comment
/* some kind
of
comment
*/
12
Semicolons
Every line in a JavaScript program is optionally
terminated using semicolons.
13
Values
A hello string is a value. A number like 12 is a
value.
14
Variables
A variable is a value assigned to an identifier, so you
can reference and use it later in the program.
const a = 0
let a = 0
const a = 0
a = 1
constant variable. .
15
On the other hand, you can do it using let :
let a = 0
a = 1
const a = 0
let a
a = 0
const a = 1, b = 2
let c = 1, d = 2
16
let a = 1
let a = 2
17
Types
Variables in JavaScript do not have any type attached.
Primitive types
Primitive types are
numbers
strings
booleans
symbols
Object types
Any value that's not of a primitive type (a string, a
number, a boolean, null or undefined) is an object.
18
Expressions
An expression is a single unit of JavaScript code that
the JavaScript engine can evaluate, and return a
value.
2
0.02
'something'
true
false
this //the current scope
undefined
i //where i is a variable or a constant
1 / 2
i++
i -= 2
i * 2
19
Logical expressions make use of logical operators and
resolve to a boolean value:
a && b
a || b
!a
20
Operators
Operators allow you to get two simple expressions
and combine them to form a more complex
expression.
let b = 2
const three = 1 + 2
const four = three + 1
21
const three = 1 + 2
three + 1 // 4
'three' + 1 // three1
const two = 4 - 2
1 / 0 //Infinity
-1 / 0 //-Infinity
22
A reminder by zero is always NaN , a special value
that means "Not a Number":
1 % 0 //NaN
-1 % 0 //NaN
1 * 2 //2
-1 * 2 //-2
1 ** 2 //1
2 ** 1 //2
2 ** 2 //4
2 ** 8 //256
8 ** 2 //64
23
Precedence
Every complex statement with multiple operators in
the same line will introduce precedence problems.
let a = 1 * 2 + 5 / 2 % 2
Operator Description
* / % multiplication/dividision
+ - addition/subtraction
= assignment
let a = 1 * 2 + 5 / 2 % 2
let a = 2 + 5 / 2 % 2
let a = 2 + 2.5 % 2
let a = 2 + 0.5
let a = 2.5
24
Comparisons
After assignment and math operators, the third set of
operators I want to introduce is conditional operators.
Example:
let a = 2
a >= 1 //true
25
Conditionals
With the comparison operators in place, we can talk
about conditionals.
if (true) {
//do something
}
if (false) {
//do something (? never ?)
}
26
A block can be put wherever you can have a single
statement. And if you have a single statement to
execute after the conditionals, you can omit the block,
and just write the statement:
if (true) doSomething()
Else
You can provide a second part to the if statement:
else .
if (true) {
//do something
} else {
//do something else
}
if (a === true) {
//do something
} else if (b === true) {
//do something else
} else {
//fallback
}
27
Strings
A string is a sequence of characters.
'A string'
"Another string"
'Flavio'.length //6
const name = 'Flavio'
name.length //6
''.length //0
28
You can use the + operator to interpolate variables:
string
is awesome!`
29
const string = `something ${1 + 2 + 3}`
const string2 = `something
${foo() ? 'x' : 'y'}`
30
Arrays
An array is a collection of elements.
const a = []
const a = Array()
const a = [1, 2, 3]
const a = Array.of(1, 2, 3)
31
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix[0][0] //1
matrix[2][0] //7
a[0] //1
a[1] //2
a[2] //3
Array(12).fill(0)
const a = [1, 2, 3]
a.length //3
Note that you can set the length of the array. If you
assign a bigger number than the arrays current
capacity, nothing happens. If you assign a smaller
number, the array is cut at that position:
32
const a = [1, 2, 3]
a //[ 1, 2, 3 ]
a.length = 2
a //[ 1, 2 ]
a.push(4)
a.unshift(0)
a.unshift(-2, -1)
a.pop()
33
a.shift()
const a = [1, 2]
const b = [3, 4]
const c = a.concat(b) //[1,2,3,4]
a //[1,2]
b //[3,4]
const a = [1, 2]
const b = [3, 4]
const c = [...a, ...b]
c //[1,2,3,4]
34
Returns the first item that returns true. Returns
undefined if the element is not found.
The above line will return the first element in the array
that has id === my_id .
a.includes(value)
a.includes(value, i)
35
Loops
Loops are one of the main control structures of
JavaScript.
while loops
for loops
for..of loops
while
Example:
36
You can interrupt a while loop using the break
while (true) {
if (somethingIsTrue) break
}
while (true) {
if (somethingIsTrue) continue
Example:
for
37
The second very important looping structure in
JavaScript is the for loop.
Example:
loop using break and you can fast forward to the next
iteration of a for loop using continue .
for...of
38
Functions
In any moderately complex JavaScript program,
everything happens inside functions.
What is a function?
function getData() {
// do something
}
getData()
function getData() {
//do something
}
function getData(color) {
//do something
}
39
When we can pass an argument, we invoke the
function passing parameters:
getData('green', 24)
getData('black')
40
although the conditional will also be true if age is
null , 0 or an empty string.
function getData() {
// do something
return 'hi!'
}
function getData() {
// do something
return 'hi!'
}
41
To return multiple values, you can return an object, or
an array, like this:
function getData() {
return ['Flavio', 37]
}
42
Arrow Functions
Arrow functions are a recent introduction to
JavaScript.
function getData() {
//...
}
to
() => {
//...
}
43
When we do so, we can remove the name from the
function:
44
const getData = param => console.log(param)
keyword.
getData() //'test'
The are very similar, so you might ask why they were
introduced? The big difference with regular functions
is when they are used as object methods. This is
something we'll soon look into.
45
Objects
Any value that's not of a primitive type (a string, a
number, a boolean, a symbol, null, or undefined) is an
object.
const car = {
46
We initialize a new object using
let age = 36
let myAge = age
myAge = 37
age //36
const car = {
color: 'blue'
}
const anotherCar = car
anotherCar.color = 'yellow'
car.color //'yellow'
47
Object properties
Objects have properties, which are composed by a
label associated with a value.
const car = {
const car = {
color: 'blue'
}
const car = {
color: 'blue',
'the color': 'blue'
}
48
Invalid variable name characters include spaces,
hyphens, and other special characters.
car.color //'blue'
car.brand //undefined
const car = {
brand: {
name: 'Ford'
},
color: 'blue'
}
49
car.brand.name
or
car['brand']['name']
const car = {
color: 'blue'
}
car.color = 'yellow'
car['color'] = 'red'
car.model = 'Fiesta'
car.model //'Fiesta'
const car = {
color: 'blue',
brand: 'Ford'
}
delete car.brand
50
51
Object methods
I talked about functions in a previous chapter.
const car = {
brand: 'Ford',
model: 'Fiesta',
start: function() {
console.log('Started')
}
}
car.start()
52
const car = {
brand: 'Ford',
model: 'Fiesta',
start: function() {
console.log(`Started
${this.brand} ${this.model}`)
}
}
car.start()
const car = {
brand: 'Ford',
model: 'Fiesta',
start: () => {
console.log(`Started
${this.brand} ${this.model}`) //not going to w
}
}
car.start()
53
const car = {
brand: 'Ford',
model: 'Fiesta',
goTo: function(destination) {
console.log(`Going to ${destination}`)
}
}
car.goTo('Rome')
54
Classes
We talked about objects, which are one of the most
interesting parts of JavaScript.
const person = {
name: 'Flavio'
}
class Person {
name
}
55
flavio.name = 'Flavio'
flavio.name
class Person {
hello() {
return 'Hello, I am Flavio'
}
}
class Person {
hello() {
return 'Hello, I am Flavio'
}
}
const flavio = new Person()
flavio.hello()
56
class Person {
constructor(name) {
this.name = name
}
hello() {
return 'Hello, I am ' + this.name + '.'
}
}
class Person {
static genericHello() {
return 'Hello'
}
}
Person.genericHello() //Hello
57
58
Inheritance
A class can extend another class, and objects
initialized using that class inherit all the methods of
both classes.
class Person {
hello() {
return 'Hello, I am a Person'
}
}
59
class Programmer extends Person {
hello() {
return super.hello() +
'. I am also a programmer.'
}
}
60
Asynchonous
Programming and
Callbacks
Most of the time, JavaScript code is ran
synchronously.
However there are times when you cannot just wait for
a line of code to execute.
You can't just wait 2 seconds for a big file to load, and
halt the program completely.
Example:
61
setTimeout(() => {
// runs after 2 seconds
console.log('inside the function')
}, 2000)
console.log('before')
setTimeout(() => {
// runs after 2 seconds
console.log('inside the function')
}, 2000)
console.log('after')
before
after
inside the function
62
We define a function that accepts a callback
doSomething(result => {
console.log(result)
})
63
Promises
Promises are an alternative way to deal with
asynchronous code.
Like this:
doSomething(result => {
console.log(result)
})
64
functions indented into other functions:
doSomething(result => {
doSomethingElse(anotherResult => {
doSomethingElseAgain(yetAnotherResult => {
console.log(result)
})
})
})
Instead of doing:
doSomething(result => {
console.log(result)
})
doSomething()
.then(result => {
console.log(result)
})
65
doSomething()
.then(result => {
console.log(result)
})
.catch(error => {
console.log(error)
})
})
66
const doSomething = new Promise(
(resolve, reject) => {
})
Here's how:
67
Async and Await
Async functions are a higher level abstraction over
promises.
Any code that want to use this function will use the
async keyword right before the function:
Like this:
68
The Async/await duo allows us to have a cleaner code
and a simple mental model to work with asynchronous
code.
getFirstUserData()
69
const getFirstUserData = async () => {
// get users list
const response = await fetch('/users.json')
// parse JSON
const users = await response.json()
// pick first user
const user = users[0]
// get user data
const userResponse =
await fetch(`/users/${user.name}`)
// parse JSON
const userData = await user.json()
return userData
}
getFirstUserData()
70
Variables scope
When I introduced variables, I talked about using
const , let , and var .
71
Suppose you define a var variable inside an if
conditional in a function
function getData() {
if (true) {
var data = 'some data'
console.log(data)
}
}
function getData() {
if (true) {
var data = 'some data'
}
console.log(data)
}
function getData() {
if (true) {
let data = 'some data'
}
console.log(data)
}
defined .
72
This is because var is function scoped, and there's a
special thing happening here, called hoisting. In short,
the var declaration is moved to the top of the closest
function by JavaScript, before it runs the code. More
or less this is what the function looks like to JS,
internally:
function getData() {
var data
if (true) {
data = 'some data'
}
console.log(data)
}
function getData() {
console.log(data)
if (true) {
var data = 'some data'
}
}
73
have less moving parts, and their scope is limited to
the block, which also makes them very good as loop
variables, because they cease to exist after a loop has
ended:
function doLoop() {
for (var i = 0; i < 10; i++) {
console.log(i)
}
console.log(i)
}
doLoop()
When you exit the loop, i will be a valid variable with
value 10.
74
Conclusion
Thanks a lot for reading this book.
75