Week 2: Introduction to Javascript
Week 2 - Intro to JavaScript
Continuing to think about websites like a house (these are going to keep getting worse 😆):
HTML is the foundation and framing
CSS is the paint and design
Javascript is the light switches - it controls the fixtures in the house
[to be continued…]
Uses of JavaScript

Javascript is everywhere! It’s by far the most common in browsers, which it was designed for in 1995.
Node.JS was released in 2009, and is very common for building API servers and tools, including tools to work on the frontend.
Javascript Basics
Printing text to screen
To print text to the console, in either NodeJS or the browser, we use the function console.log(). One or more arguments can be provided, and they will be printed space-separated.
console.log('hello, world')
let letters = ['a', 'b', 'c']
console.log('letters', letters)Conditional Statements & Comments
Comments and if/else statements look like this:
if(thingA && thingB) {
// do stuff if A and B are truthy
} else if(!thingC) {
// do stuff if C is falsey - the `!` negates the check
} else {
/*
Do stuff with a multi-line comment
*/
}Declaring Variables
Variables can be defined 3 ways: var, let, and const.
Due to JS scoping, as a rule of thumb, never use var, always use let.
Once a variable has been declared, it cannot be re-declared within the same scope, BUT it can be re-assigned if it was not declared with const.
let a = 1;
a = 2
// ✅
let a = 2;
// ❌ Uncaught SyntaxError: Identifier 'a' has already been declared
const b = 'Hello';
b = 'World'
// ❌ Uncaught TypeError: Assignment to constant variable.
Variable Types
Primitives
Common Javascript primitives are String, Number, Boolean, null, and undefined.
The value undefined is the value of a variable that hasn’t yet been assigned a variable. Asside from this special case, it’s effectively the same as null.
let x;
console.log('x', x)
let y = null;
console.log('y', y);
console.log('are they equivalent?', x == y)Complex Objects
There are two complex data structures, Objects and Arrays.
Objects are key-value stores - think of a “Dictionary” or “Map”:
let obj = { 'key': 'value' }Arrays are lists of values:
let letters = ['a', 'b', 'c']Type Caveats
A reoccurring theme will be JS having some odd behaviors. When dealing with the basic types of javascript, a few to be aware of.
Numbers
All numbers are floats. This might seem like a good thing; any number can have great precision! This often leads to odd rounding issues however.
Large Integer Precision Loss
9999999999999999; // Expected: 9999999999999999, Actual: 10000000000000000
Floating Point Arithmetic
0.1 + 0.2; // Expected: 0.3, Actual: 0.30000000000000004
Dividing by Zero
1 / 0; // Expected: Error or undefined, Actual: Infinity
Not a Number
Not an odd behavior per-se, but instead of throwing an error for invalid numeric operations, the special value NaN is returned.
"abc" / 3; // NaN
An odd behavior, however, is that NaN != NaN
NaN === NaN; // false
Arrays are an object
Arrays act more like an object than a distinct data structure. For example, getting the type of an Array returns object:
let letters = ['a', 'b', 'c']
typeof letters
// -> 'object'
To actually check if an Array is in fact an Array, you’ll call Array.isArray(value)
let letters = ['a', 'b', 'c']
Array.isArray(letters)Arrays are not typed
Most languages will restrict the type of value you can put into an array, but JS will let you mix values.
let stuff = [
'hello',
/world/,
{'key': 'value'},
123
]
Semi-colons
JS expects semi-colons (;) at the end of every line. If you don’t add them, it will add them for you under the hood. This can cause some odd effects; it’s typically best to add your own! For example, this would return undefined, not the object, because JS adds a semicolon after the return statement
function asdf() {
// becomes return;
return
{
key: "value"
};
}
asdf()
// -> undefined
Functions
Functions can be defined a few ways, which we’ll cover next class. For now, the traditional method of creating a function gives it a name using the function keyword.
function asdf() {
return 'asdf'
}Loops
A traditional for loop might look like this:
let letters = ['a', 'b', 'c']
for(let i = 0; i < letters.length; i++) {
console.log('index', i, typeof i)
console.log('value', letters[i])
}JS gives us the in keyword to quickly iterate through an object by index using the in keyword:
let letters = ['a', 'b', 'c']
for(let index in letters) {
console.log('index', index, typeof index)
'value', letters[index]
}It also provides us a utility to iterate through the values of an object using the of keyword:
let letters = ['a', 'b', 'c']
for(let value of letters) {
console.log('value', value)
}While loops exist, but it’s probably best to pretend they don’t.
let product = 1;
while(product < 10) {
product *= 2;
console.log('product', product)
}Note: This week may be the last time we use these traditional loop structures. Next week, we’ll start using “higher order functions” in our code to perform the same tasks.
Built-in Utilities
JS provides a number of built-in utility functions. Some common examples include:
- Math - Perform complex math operations like
- you’ll want this for your lab!
- Date - Date Operations
- Regular Expressions - Can be defined with
/regex/syntax
Everything is an object
Everything (that is not a primitive) in Javascript is technically an object. Oh, and also null is an object 🫠.
typeof null
// -> 'object'
What do I mean by everything is an object? Any variable has properties and functions that can be read or set.
let letters = ['a', 'b', 'c'];
letters.length
// -> 0
letters.map
// [Function: map]

Functions are objects too, and can be assigned and modified like any other object.
function myFunc() {
return 'asdf'
}
let blah = myFunc;
blah()
// -> 'asdf'
myFunc.randomProperty = 'asdf';
myFunc.randomProperty
// -> 'asdf'
Accessing properties
There are two ways to access a property on an object.
let obj = {
'asdf': 'Hello, World!'
}
// via a dot
obj.asdf
// -> Hello, World!
// via square braces - note that this is a string
obj['asdf']
// -> Hello, World!
// square braces can be used to access a property via a variable
let propName = 'asdf'
obj[propName]
// -> Hello, World!
Accessing undefined properties
When accessing a non-existent property of an object (and therefore any non-primitive), JS will return undefined, but it will not throw an error
let obj = {
'property': 1234
}
obj.property
// -> 1234
obj.asdf
// -> undefined
let letters = ['a', 'b', 'c']
letters.asdf
// -> undefined

Automatic Value Cohersion
We’ve seen some examples of why this is bad in the JS fun fact of the week already. Lets dive into why.
Typically, values are coherced to a string for comparison, but that isn’t always the case.
"5" + 1; // "51" (number is converted to string)
"5" - 1; // 4 (string is converted to number)
[1, 2] + [3, 4]; // "1,23,4" (arrays are converted to strings)
{} + []; // 0 (object and array are coerced to primitive values)
+new Date(); // Number of milliseconds since epoch
Value Comparison

There are two equality operators in JS - TL;DR - always use ===!!!
== is the “Equality Operator”, while === is the “Strict Equality Operator”.
== will automatically coherce values, which we just saw, can be very bad! The strict Equality operator === will compare both value and type, meaning no type coercion is performed.
"2" == 2; // true - string is coerced to number
"2" === 2; // false - string is NOT coerced using the strict operator
Falsey / Truthy values
All values in Javascript are either “truthy” or “falsey”, and it’s very useful for conditional logic.
Truthy values are generally “a thing that exists” while Falsey are generally “empty or null things”. A value can be found to be truthy or falsey by converting it to a boolean with Boolean(value)
For example:
// falsey values
Boolean(false || null || undefined || NaN || 0 || '')
// truthy values
Boolean(true && 1 && -1 && [] && {} && '👨💻')This can be very helpful when dealing with certain types of logic. For example, if an input box requires text:
let formInput = '';
// check if string is empty
if(!formInput) { /* Display error to user */ }
// traditional style for this check would be
if(formInput.length > 0) { /* Display error to user */ }Note: Empty arrays and objects are still considered “truthy”, which is different than a number of other languages, like Python.
Node.JS and NPM
NodeJS is a runtime for javascript, just like the browser.
NPM is a package manager that can install prebuilt packages for us.
NPM packages are generally very tiny and do one specific thing. A silly example: is-odd, with 500k weekly downloads.
Oh, and don’t forget is-even:
module.exports = function isEven(i) {
return !isOdd(i);
};Installing packages
The file package.json contains the list of packages to be installed. Running npm install will install the packages listed in this file.
Running Code
The file package.json can also define custom commands, which can be run with npm run [command]. For example, npm run test would execute unit tests for a project.
We’ll discuss npm and package.json more in later classes.