Web Developer Bootcamp
JavaScript
Basics
VALUES & VARIABLES
PLEASE GIVE ME
GOOGLE.COM/SEARCH?Q=CHICKENS
HANG ON
HERE YOU GO!
FRONT END BACK END
Primitive Types
THE BASIC BUILDING BLOCKS
Number
String
Boolean
Null
Undefined
* Technically there are two others: Symbol and BigInt
DIFFERENT DATA TYPES
Running Code
in The Console
THE EASIEST PLACE TO START
Early on, we'll run our code using the
Chrome developer tools console. Then,
we'll learn how to write external scripts.
Numbers
IN JAVASCRIPT
JS has one number type
Positive numbers
Negatives numbers
Whole numbers (integers)
Decimal numbers
Math Operations
// creates a comment
(the line is ignored)
NaN
NOT A NUMBER
NaN is a numeric value that represents
something that is...not a number
Not A Number
// creates a comment
(the line is ignored)
WHAT DOES THIS
EVALUATE TO??
4 + 3 * 4 / 2
WHAT DOES THIS
EVALUATE TO??
4 + 3 * 4 /
(13 % 5) ** 22
WHAT DOES THIS
EVALUATE TO??
Variables
VARIABLES ARE LIKE
LABELS FOR VALUES
N
Up um We can store a value and give it
vo
72 te
s
a name so that we can:
Refer back to it later
Use that value to do...stuff
Or change it later one
BASIC SYNTAX
let someName = value;
BASIC SYNTAX
let year = 1985;
Make me a variable called "year" and give it the value of 1985
RECALL VALUES
RECALL VALUES
This does not change the
value stored in hens
This does!
CONST
const works just like
let, except you CANNOT
change the value
NOT ALLOWED!
YOU'RE IN TROUBLE!!
I'M TELLING MOM!!!
WHY USE CONST?
Once we cover Arrays & Objects, we'll see other
situations where const makes sense over let.
VAR
THE OLD VARIABLE KEYWORD
BEFORE LET & CONST, VAR WAS THE ONLY
WAY OF DECLARING VARIABLES. THESE DAYS,
THERE ISN'T REALLY A REASON TO USE IT.
What is the value of
totalScore?
What is the value of
totalScore?
What is the value of
temperature?
What is the value of
bankBalance?
BOOLEANS
TRUE or FALSE
Booleans
TRUE OR FALSE
Booleans are very simple.
You have two possible options: true
or false. That's it!
Variables Can Change Types
It doesn't really make sense to change from
a number to a boolean here, but we can!
Strings
"STRINGS OF CHARACTERS"
Strings are another primitive type in
JavaScript. They represent text, and
must be wrapped in quotes.
STRINGS
Double quotes work
So do single quotes
This DOES NOT work
It's fine to use either single or double
quotes, just be consistent in your codebase.
STRINGS ARE INDEXED
C H I C K E N
0 1 2 3 4 5 6
Each character has a corresponding index
(a positional number)
String Methods
METHODS ARE BUILT-IN
ACTIONS WE CAN PERFORM
WITH INDIVIDUAL STRINGS
They help us do things like:
- Searching within a string
- Replacing part of a string
- Changing the casing of a string
thing.method()
Casing
Double quotes work
So do single quotes
This DOES NOT work
Trim
thing.method(arg)
Some methods accept arguments that modify their behavior.
Think of them as inputs that we can pass in.
We pass these arguments inside of the parentheses.
indexOf
slice
replace
WHAT IS THE
VALUE OF AGE?
WHAT DOES THIS
EVALUATE TO?
WHAT DOES THIS
EVALUATE TO?
What is the
value of song?
What is the value
of cleanedInput?
What is the value
of index?
What is the value
of index?
WHAT DOES THIS
EVALUATE TO?
STRING ESCAPES
\n - newline
\' - single quote
\" - double quote
\\ - backslash
Template Literals
SUPER USEFUL!
TEMPLATE LITERALS ARE STRINGS THAT ALLOW
EMBEDDED EXPRESSIONS, WHICH WILL BE EVALUATED
AND THEN TURNED INTO A RESULTING STRING
WE USE BACK-TICKS
NOT SINGLE QUOTES
`I am a template literal`
* The back-tick key is usually above the tab key
TEMPLATE LITERALS
NULL & UNDEFINED
Null
"Intentional absence of any value"
Must be assigned
Undefined
Variables that do not have an
assigned value are undefined
NULL
Undefined
MATH
OBJECT
Contains properties and
methods for mathematical
constants and functions
RANDOM
NUMBERS
Math.random() gives us a
random decimal between
0 and 1 (non-inclusive)
RANDOM
INTEGERS
Let's generate random
numbers between 1 and 10
parseInt &
parseFloat
Use to parse strings
into numbers, but
watch out for NaN!
Web Developer Bootcamp
Boolean
Logic
MAKING DECISIONS WITH JAVASCRIPT
COMPARISONS
SOME EXAMPLES
Notice these all return a Boolean!
Though it's uncommon, you can compare
strings. Just be careful, things get
dicey when dealing with case, special
characters, and accents!
==
VS
===
== (double equals)
Checks for equality of value, but
not equality of type.
It coerces both values to the same
type and then compares them.
This can lead to some unexpected
results!
== WEIRDNESSS
TRIPLE EQUALS
CHECKS FOR EQUALITY OF VALUE AND TYPE
console.log()
prints arguments to the console
(we need this if we're going to start working with files!)
Running Code From a File
app.js demo.html
Write your code Include your script
in a .js file in a .html file
Conditionals
MAKING DECISIONS WITH CODE
IF STATEMENT
Only runs code if given condition is true
ELSE IF
If not the first thing, maybe this other thing??
ELSE IF
We can add multiple else ifs!
ELSE
If nothing else was true, do this...
NESTING
We can nest conditionals inside conditionals
TRUTHY AND
FALSY VALUES
All JS values have an inherent truthyness or
falsyness about them
Falsy values:
false
0
"" (empty string)
null
undefined
NaN
Everything else is truthy!
Logical Operators
COMBINING EXPRESSIONS
&& || !
AND
Both sides must be true, for the entire thing to be true
AND
Both sides must be true, for the entire thing to be true
OR
If one side is true, the entire thing is true
OR
If one side is true, the entire thing is true
NOT
!expression returns true if expression is false
Web Developer Bootcamp
JS Arrays
OUR FIRST DATA STRUCTURE
ARRAYS
Ordered collections of values.
List of comments on IG post
Collection of levels in a game
Songs in a playlist
Creating Arrays
PLEASE DROP BY AND SEE ME!
ARRAYS ARE INDEXED
Doc Dopey Bashful Grumpy Sneezy Sleepy Happy
0 1 2 3 4 5 6
Each element has a corresponding index
(counting starts at 0)
Arrays Are Indexed
Modifying Arrays
ARRAY METHODS
Push - add to end
Pop - remove from end
Shift - remove from start
Unshift - add to start
YOU'LL GET USED TO THE NAMES EVENTUALLY!
MORE METHODS
concat - merge arrays
includes - look for a value
indexOf - just like string.indexOf
join - creates a string from an array
reverse - reverses an array
slice - copies a portion on an array
splice - removes/replaces elements
sort - sorts an array
CONST
AND
ARRAYS
WHY DO PEOPLE USE CONST WITH ARRAYS??
THE VALUES CAN CHANGE
AS LONG AS THE REFERENCE REMAINS THE SAME
myEggs
THE VALUES CAN CHANGE
AS LONG AS THE REFERENCE REMAINS THE SAME
myEggs
THE VALUES CAN CHANGE
AS LONG AS THE REFERENCE REMAINS THE SAME
myEggs
THE VALUES CAN CHANGE
AS LONG AS THE REFERENCE REMAINS THE SAME
myEggs
NESTED ARRAYS
We can store arrays inside other arrays!
NESTED
ARRAYS
Web Developer Bootcamp
JS Objects
OUR SECOND DATA STRUCTURE!
OBJECTS
Objects are collections of
properties. age: 20
Properties are a key-value zip: 91003
pair city: 'Tulsa'
Rather than accessing data isAdmin: true
using an index, we use
custom keys.
HOW
WOULD
YOU
STORE
THIS?
Using an Object!
PROPERTY =
KEY
+
VALUE
KEY-VALUE PAIRS
username: 'crazyCatLady'
upvotes: 7
text 'great post!'
DICTIONARY
clarion: fecund:
brilliantly clear fruitful in offspring
pursy:
donnybrook:
having a puckered
uprooad & disorder
appearance
fantod: remonstrate:
emotional outburst argue in protest
ALL TYPES WELCOME!
VALID KEYS
All keys are
converted to
strings *
* Except for Symbols, which we haven't covered yet
ACCESSING DATA
UPDATING
& ADDING
PROPERTIES
ARRAYS + OBJECTS
The Web Developer Bootcamp
Js Loops
REPEAT STUFF. REPEAT STUFF. REPEAT STUFF.
LOOPS
Loops allow us to repeat code
"Print 'hello' 10 times
Sum all numbers in an array
There are multiple types:
for loop
while loop
for...of loop
for...in loop
For
Loops
Buckle Up!
For Loop Syntax
for (
[initialExpression];
[condition];
[incrementExpression]
)
Our First For Loop
start at 1 stop at 10 add 1 each time
Another Example
Start i at 50
Subtract 10 each
iteration
Keep going as
long as i >= 0
Infinite Loops
Looping Over Arrays
To loop over an array, start at index 0 and
continue looping to until last index (length-1)
NESTED LOOPS
While Loops
While loops continue running as
long as the test condition is true.
A Common Pattern
The Break Keyword
FOR...OF
A nice and easy way of
iterating over arrays
(or other iterable objects)
No Internet
Explorer Support
For...Of
for (variable of iterable) {
statement
}
An Example
Nested For...Of
Web Developer Bootcamp
JavaScript
Functions
THE LAST "BIG" TOPIC!
FUNCTIONS
Reusable procedures
Functions allow us to write
reusable, modular code
We define a "chunk" of code that
we can then execute at a later
point.
We use them ALL THE TIME
2 STEP PROCESS
DEFINE RUN
DEFINE
function funcName(){
//do something
}
DEFINE
RUN
funcName(); //run once
funcName(); //run again!
RUN
ARGUMENTS
INPUTS
Right now, our simple functions
accept zero inputs. They behave the
same way every time.
NO INPUTS
grumpus()
grumpus()
NO INPUTS
greet() "Hi!"
greet() "Hi!"
ARGUMENTS
We can also write functions that accept
inputs, called arguments
ARGUMENTS
greet('Tim') "Hi Tim!"
greet('Anya') "Hi Anya!"
ONE MORE
avg(20,25) 22.5
avg(3,2,5,6) 4
We've seen this before
No inputs
Arguments!
GREET TAKE 2
"Hi, Arya!" "Hi, Ned!"
2 ARGUMENTS!
"77 is
larger!"
"33 and 33
are equal"
RETURN
Built-in methods return values
when we call them.
We can store those values:
NO RETURN!
Our functions print values out, but do
NOT return anything
FNIoR S T R E T U R N
w we can capture a return
!
value in a variable!
RETURN
The return statement ends function
execution AND specifies the value to be
returned by that function
FUNCTIONS
IN DETAIL
Important things
you should know
about functions
SCOPE
Variable "visibility"
The location where a variable
is defined dictates where we
have access to that variable
FUNCTION SCOPE
msg is scoped to the
helpMe function
FUNCTION SCOPE
bird is scoped to
birdWatch function
BLOCK SCOPE
PI & circ are
scoped to the
BLOCK
LEXICAL SCOPE
FUNCTION
EXPRESSIONS
FUNCTIONS
ARE...
OBJECTS!
HIGHER
ORDER
FUNCTIONS
HIGHER ORDER
FUNCTIONS
Functions that operate on/with other functions.
They can:
Accept other functions as arguments
Return a function
FUNCTIONS AS
ARGUMENTS
RETURNING
FUNCTIONS
METHODS
We can add functions as
properties on objects.
We call them methods!
SHORTHAND
We do this so often that
there's a new shorthand
way of adding methods.
'THIS' IN METHODS
Use the keyword this to access other properties
on the same object.
The value of this depends on
the invocation context of
the function it is used in.
SAME FUNCTION
DIFFERENT
RESULT???
The value of this depends on
the invocation context of
the function it is used in.
GOALS
Use the new arrow function syntax
Understand and use these methods:
forEach
map
filter
find
reduce
some
every
FOREACH
Accepts a callback
function.
Calls the function
once per element
in the array.
MAP
Creates a new array with the
results of calling a callback on
every element in the array
MAP
ARROW
FUNCTIONS!
ARROW
FUNCTIONS
"syntactically compact alternative"
to a regular function expression
ARROW
FUNCTIONS
IMPLICIT RETURN
All these functions do the same thing:
FIND
returns the value of the first element in the array that
satisfies the provided testing function.
FILTER
Creates a new array with all elements that pass the test
implemented by the provided function.
EVERY
tests whether all elements in the array pass the
provided function. It returns a Boolean value.
SOME
Similar to every, but returns true if ANY of the
array elements pass the test function
REDUCE
Executes a reducer function on
each element of the array,
resulting in a single value.
SUMMING AN ARRAY
FINDING MAX VAL
INITIAL VALUE
TALLYING
DEFAULT
PARAMS
The Old Way
DEFAULT
PARAMS
The New Way
SPREAD
SPREAD
Spread syntax allows an iterable such as an
array to be expanded in places where zero or
more arguments (for function calls) or
elements (for array literals) are expected,
or an object expression to be expanded in
places where zero or more key-value pairs
(for object literals) are expected.
SPREAD
For Function Calls
Expands an iterable
(array, string, etc.)
into a list of arguments
SPREAD
In Array Literals
Create a new array using
an existing array. Spreads
the elements from one
array into a new array.
SPREAD
In Object Literals
Copies properties
from one object into
another object literal.
REST
It looks like spread,
but it's not!
THE ARGUMENTS OBJECT
Available inside every
function.
It's an array-like object
Has a length property
Does not have array
methods like push/pop
Contains all the arguments
passed to the function
Not available inside of
arrow functions!
REST
PARAMS
Collects all remaining
arguments into an
actual array
DESTRUCTURING
A short, clean syntax to 'unpack':
Values from arrays
Properties from objects
Into distinct variables.
A R R A Y
Destructuring
OD eBs t rJu cEt u rC
ing
T