# JavaScript

## Contents

- [JavaScript language features](#the-javascript-language)
  - [Basic types](#types): `Number`, `String`, `Boolean`, `Array`, `Object`, and `undefined`
  - [Printing values](#console.log): `console.log`
  - [Variables](#variables): `let`, `const`, and destructuring
  - [Control flow](#control-flow)
    - [`if`](#if-statements)
    - [`while`](#while-loops); `break` and `continue`
    - [`for (initializer; condition; increment)`](#c-style-for-loops)
    - [`for (const value of iterable)`](#for-of-loops)
  - [Functions](#functions)
    - [Anonymous functions](#anonymous-functions): `=>`
    - [Named functions](#function): `function`
    - [Function arguments/parameters](#parameters)
  - [Classes](#classes): `class`
    - [Constructors](#constructor): `constructor`
    - [Methods](#methods): instance and `static` methods
    - [Inheritance](#inheritance): `extends`
  - [`Set`](#set)
  - [`Map`](#map)
  - [Error handling](#error-handling): `Error`, `throw`, and `try`-`catch`
  - [More function parameters](#advanced-function-parameters): `= default` arguments, `...` arguments, and destructuring arguments
- [JavaScript in the browser](#browser-side-javascript)
  - [Example](#browser-side-example)
  - [Documentation](#browser-side-documentation)
- [Node.js](#nodejs): server-side JavaScript
  - [Running programs in Node.js](#running-the-interpreter)
  - [Modules](#modules): Node.js builtin modules, `require`, and `module.exports`
  - [Example](#nodejs-example)
  - [Documentation](#nodejs-documentation)
---

## The JavaScript language

### Types

JavaScript is a dynamically-typed language, much like Python.
This means that writing JavaScript can require a lot of time spent debugging programs to figure out why values don't have the types you were expecting.
JavaScript also has an annoying tendency to try to guess what you meant to write rather than immediately reporting an error.
(For example, what do you think `[] * 3` evaluates to?)

With that being said, these are the primary types in JavaScript:
- `Number`: this is a numeric type like `float` in Python or `double` in Java.
  It mostly behaves as you'd expect, e.g. `1 + 2` is `3` and `1 / 3` is `0.3333333333333333`.
  It supports the same operations as Python does: `+`, `-`, `*`, `/`, `%` (remainder), and `**` (exponentiation).
- `String`: this is a textual type like `str` in Python or `String` in Java.
  - String literals can use single or double quotes, or backticks to embed other values in the string:
    ```js
    'abc' // 'abc'
    "abc" // 'abc'

    const count = 2
    `I have ${count} apples` // 'I have 2 apples'
    ```
  - Strings can be concatenated with the `+` operator.
    You can also extract characters using the `[]` operator, e.g. `'abc'[1]` is `'b'`.
  - Strings have lots of useful methods: `toLowerCase()`, `slice()`, `repeat()`, etc. As in Python or Java, strings are immutable, so methods like `replace()` return a *new* string with the replacements.
- `Boolean`: `true` and `false`. Useful operators: `!` for negation, `&&` for "and", and `||` for "or".
  Numbers and strings can also be treated as booleans (`0` and `''` are "falsy" and all other values are "truthy").
  For example, `if (values.length)` checks whether the array `values` is not empty.
- `undefined`: this is a special value that is used to indicate "no value".
  It is the default value of uninitialized variables, return values from functions, etc.
  It is falsy.
- Arrays: this is a growable list type like `list` in Python or `List` in Java.
  - Array literals look like `[1, 2, 3]`, just as in Python.
  - Use the `[]` operator to get/set elements of an array:
    ```js
    const arr = [1, 2, 3]
    arr[0] = arr[2]
    arr // [3, 2, 3]
    ```
  - Arrays can be grown by setting an index past the end, or by calling `push()`:
    ```js
    const arr = []
    arr.length // 0

    arr[0] = 1
    arr // [1]

    arr.push(2)
    arr // [1, 2]
    arr.length // 2
    ```
  - Arrays have lots of useful [methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Instance_methods), e.g. `map()`, `includes()`, and `some()`
- Objects: in JavaScript, all "objects" (in the Python/Java sense) are really just maps of strings to values.
  However, they are not often used as maps since [`Map`](#map)s are much more convenient.
  - Object literals look like `{key1: value1, key2: value2}`.
  - Values can be get/set using the `[]` operator, or `.` notation:
    ```js
    const point = {x: 1.5, y: 2.3}

    point['x'] += 1
    point // {x: 2.5, y: 2.3}

    point.z = point.x * point.y
    point // {x: 2.5, y: 2.3, z: 5.75}

    point.noSuchKey // undefined
    ```
  - There is a useful shorthand for putting variables into an object:
    ```js
    const head = 'A'
    const tail = {head: 'B'}
    const listAB = {head, tail}
    listAB // {head: 'A', tail: {head: 'B'}}
    ```

The functions `Number`, `String`, and `Boolean` can be used to convert between the primitive types.
For example, `Number('123')` is `123`.

### `console.log()`

`console.log()` is JavaScript's equivalent of `print()` in Python or `System.out.println()` in Java.
It can be very helpful when debugging.
It is a builtin function that you can use in browser-side JS or Node.js.
In Node.js, `console.log()` prints to the terminal.
In browsers, `console.log()` prints values to the developer console.
For example, in Chrome:
![Chrome developer tools](dev-tools.png)

### Variables

JavaScript has two types of variables: `let` and `const`.
Variables declared as `let` can be given a new value, but `const` variables can only have their value set once:
```js
let collatz = 27
while (collatz > 1) {
  console.log(collatz)
  if (collatz % 2 === 0) collatz /= 2
  else collatz = 3 * collatz + 1
}

// vs.
const collatz = 27
collatz = 3 * collatz + 1
// Uncaught TypeError: Assignment to constant variable.
```
(Note that `const` doesn't mean "immutable"; the array and object examples above show that we can *modify* an array or object referenced by a `const` variable.)
I find that around 90% of my variables can be `const`, so I recommend declaring variables `const` whenever possible to avoid unexpectedly changing them.

Both types of variables are only visible in the scope where they are defined:
```js
const x = 'outer'
if (true) {
  const y = 'inner'
  x // 'outer'
  y // 'inner'
}

x // 'outer'
y // Uncaught ReferenceError: y is not defined
```

`let` variables have the value `undefined` by default.
```js
let max
max // undefined

const values = [4, 3, 1, 5, 2]
for (const value of values) {
  if (max === undefined || value > max) max = value
}
max // 5
```

There are two other ways you can assign to a variable: "array destructuring" and "object destructuring".
You can think of these as the opposites of array literals and object literals.
```js
const arr = 'abcdef'.split('')
arr // ['a', 'b', 'c', 'd', 'e', 'f']

const [a, b, ...rest] = arr
a // 'a'
b // 'b'
rest // ['c', 'd', 'e', 'f']

const obj = {mean: 3.1, standardDeviation: 0.57, median: 4}
const {mean, standardDeviation} = obj
mean // 3.1
standardDeviation // 0.57
```

### Control flow

JavaScript has the standard comparison operators `<`, `<=`, `>`, and `>=`.
The major distinction from Python and Java is that we use the `===` ("triple-equals") and `!==` operators to check for equality and inequality!
The `==` and `!=` operators in JS have unpredictable behavior when comparing different types of values, so don't use them!
It's also important to note that `===` on objects (or arrays) returns whether they are *exactly the same object*, as in Java, but unlike in Python:
```js
const a = []
const b = a // a and b refer to the same array; changing one changes the other
const c = [] // c is a different array that also happens to be empty

a === b // true
a === c // false
```

#### `if` statements

`if` statements work exactly like in Python or Java: they run some code only when a condition is `true`, and possibly some other code if the condition is `false`.
The syntax matches Java (or any other language inspired by C):
```js
let a
let b
if (Math.random() < 0.5) {
  a = ['a', 'p', 'e']
  b = ['a', 'n', 'd']
}
else {
  a = ['d', 'o', 'g']
  b = ['d', 'o', 'n']
}

// Find which of a or b comes earlier in dictionary order
let min
if (a[0] < b[0]) min = a
else if (a[0] > b[0]) min = b
else if (a[1] < b[1]) min = a
else if (a[1] > b[1]) min = b
else if (a[2] < b[2]) min = a
else if (a[2] > b[2]) min = b
else min = a // they are equal

min // ['a', 'n', 'd'] or ['d', 'o', 'g']
```

#### `while` loops

`while` statements are also identical to Python and Java: they run some code repeatedly while a certain condition is met.
For example, computing `10 ** 13` by repeated squaring:
```js
let base = 10
let exponent = 13
let power = 1
while (exponent > 0) {
  const addPower = exponent % 2
  if (addPower === 1) power *= base
  base *= base
  exponent = (exponent - addPower) / 2
}
power // 10000000000000
```

As in Python or Java, `break` can be used to quit a loop early and `continue` can be used to skip to the next iteration of the loop.
These also work with both types of `for` loops.
For example, to find a multiple of 3 in an array:
```js
const values = []
while (values.length < 10) {
  values.push(Math.floor(Math.random() * 10))
}

let foundIndex
let testIndex = 0
while (testIndex < values.length) {
  if (values[testIndex] % 3 === 0) {
    foundIndex = testIndex
    break // stop as soon as a multiple of 3 is found
  }

  testIndex++
}
```

#### C-style `for` loops

`for` loops consist of 3 parts: an initialization statement, a `while` condition, and an update statement.
As in C or Java, these loops are often used to loop over all integers in a range.
For example, to randomly shuffle an array:
```js
const arr = []
for (let i = 0; i < 10; i++) arr.push(i)
arr // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

// For each index i, choose one of the i + 1 unused elements to go there
for (let i = arr.length - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1))
  const temp = arr[i]
  arr[i] = arr[j]
  arr[j] = temp
}
arr // [6, 4, 3, 2, 9, 8, 5, 1, 0, 7] (results will vary)
```

#### `for`-`of` loops

The `for`-`of` loop is similar to Python's `for`-`in` loop or Java's `for`-`:` loop: it iterates over each item of a collection.
Be careful not to confuse this with JS's `for`-`in` loop, which behaves very differently!
Typically, `for`-`of` loops are used to iterate over arrays, but they work with any "iterable" values, such as [`Map`](#map) and [`Set`](#set).
For example, to compute an average:
```js
// Sample a million values uniformly between 0 and 1 and square them
const values = []
while (values.length < 1e6) {
  values.push(Math.random() ** 2)
}

let sum = 0
for (const value of values) sum += value
const average = sum / values.length
average // 0.3332654911154851 (results will vary)
```

Or, to compute all combinations of elements from arrays:
```js
const adjectives = ['angry', 'boring', 'contemplative']
const nouns = ['dad', 'elephant', 'farmer']
const verbs = ['gamble', 'hibernate', 'imagine']
const sentences = []
for (const adjective of adjectives) {
  for (const noun of nouns) {
    for (const verb of verbs) {
      sentences.push(`${adjective} ${noun} ${verb}s`)
    }
  }
}
sentences
/* [
  'angry dad gambles',
  'angry dad hibernates',
  'angry dad imagines',
  'angry elephant gambles',
  'angry elephant hibernates',
  'angry elephant imagines',
  'angry farmer gambles',
  'angry farmer hibernates',
  'angry farmer imagines',
  'boring dad gambles',
  'boring dad hibernates',
  'boring dad imagines',
  'boring elephant gambles',
  'boring elephant hibernates',
  'boring elephant imagines',
  'boring farmer gambles',
  'boring farmer hibernates',
  'boring farmer imagines',
  'contemplative dad gambles',
  'contemplative dad hibernates',
  'contemplative dad imagines',
  'contemplative elephant gambles',
  'contemplative elephant hibernates',
  'contemplative elephant imagines',
  'contemplative farmer gambles',
  'contemplative farmer hibernates',
  'contemplative farmer imagines'
] */
```

### Functions

#### Anonymous functions

JavaScript has strong support for "anonymous" or "lambda" functions, i.e. functions that can be treated as values.
To get a sense of this, it may be helpful to see some examples:
```js
// "square is the function that takes x and returns x * x"
const square = x => x * x
// "call square, passing in 5 as x"
square(5) // 25

// Since square is a value, we can pass it into another function
[10, 9, 8].map(square) // [100, 81, 64]

// We can also put multiple lines of code inside functions.
// This is equivalent to the "square" defined above.
const square2 = x => {
  const squared = x * x
  return squared
}

const list = []
// A function that takes two arguments:
// a value and the number of times to add it to the list
const addCopiesOfValue = (value, times) => {
  for (let i = 0; i < times; i++) list.push(value)
}
addCopiesOfValue('a', 2)
addCopiesOfValue('b', 0)
addCopiesOfValue('c', 3)
list // ['a', 'a', 'c', 'c', 'c']

// You don't have to store functions in variables at all;
// they can be passed directly to other functions
const sum = [1, 2, 3, 4, 5].reduce((a, b) => a + b)
sum // 15
```

#### `function`

There is a convenient shorthand for assigning names to functions:
```js
// Equivalent to `let transpose = matrix => { /* ... */ }`
function transpose(matrix) {
  const result = []
  for (let i = 0; i < matrix[0].length; i++) {
    result[i] = []
    for (let j = 0; j < matrix.length; j++) {
      result[i][j] = matrix[j][i]
    }
  }
  return result
}

transpose([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
])
/* [
  [1, 4, 7],
  [2, 5, 8],
  [3, 6, 9]
] */
```

#### Parameters

JavaScript functions can be called with more or fewer arguments than they are declared with.
Missing arguments are passed as `undefined` and extra arguments are ignored.
This can be very handy or a source of tricky bugs.
For example:
```js
const arr = ['a', 'b', 'c', 'd', 'e']
// .map() expects a function which takes an array value and its index.
// If we don't care about the index, we can just use the value:
arr.map(letter => letter.toUpperCase())
// ['A', 'B', 'C', 'D', 'E']

arr.map((letter, index) => letter.repeat(index + 1))
// ['a', 'bb', 'ccc', 'dddd', 'eeeee']

// Returns the result of running f the specified number of times
function simulate(f, times) {
  // Default to 100 times if not specified
  if (times === undefined) times = 100

  const results = []
  while (times > 0) {
    results.push(f())
    times--
  }
  return results
}
simulate(Math.random)
// [0.9646134999107248, 0.6281785239945497, 0.34087991779123406, ...]
simulate(() => {
  // Computes the number of dice rolls needed to get all 6 outcomes
  const diceRollsSeen = []
  for (let i = 0; i < 6; i++) diceRollsSeen[i] = false
  let rolls = 0
  while (!diceRollsSeen.every(rolled => rolled)) {
    diceRollsSeen[Math.floor(Math.random() * 6)] = true
    rolls++
  }
  return rolls
}, 10)
// [12, 25, 40, 18, 9, 14, 14, 14, 10, 22]
```

### Classes

JavaScript supports object-oriented programming much like Python or Java.
Object classes can be defined using the keyword `class`.

#### Constructor

Every class has a constructor, which is a function that can be called with the `new` keyword to create an instance of the class.
The constructor is declared inside the `class` with the notation `constructor(...arguments) { /* ... */ }`.
It can take arguments just like any other function, but it can't return anything.
If you don't provide a constructor, one that does nothing will be created automatically.

Inside the constructor, `this` refers to the new object being constructed.
You can set fields on an object by assigning a value to `this.fieldName`.
Like Python, fields don't need to be declared outside the constructor and other methods can also add fields to the object.

#### Methods

Methods are declared inside the `class` using `methodName(...args) { /* ... */ }`.
Methods work identically to normal functions, except `this` automatically refers to the object the method was called on.

You can also add `static` in front of a method to make it a method you can call on the *class* instead of on an object.

JS doesn't (currently) have a concept of private methods or fields; all fields can be accessed and all methods can be called outside the `class`.
It is common to give methods a name starting with a `_` if they are meant to be private.

#### Inheritance

Like Python or Java, JS supports object inheritance, where one type of object can be a special case of another type of object.
These "subclasses" have all the fields and methods of their "superclasses", plus additional functionality.

To define a subclass, you can write `class SubClass extends SuperClass { /* ... */ }`.
The `constructor` of a subclass needs to call the superclass's constructor, which can be done using `super(...args)`.

You can also extend builtin classes like `Array`:
```js
// A Vector3D is a 3-element Array,
// representing the x-, y-, and z-coordinates of a 3D vector
class Vector3D extends Array {
  constructor(x, y, z) {
    super() // call `new Array()` to make an empty array
    this.push(x, y, z)
  }

  add(vector) {
    return new Vector3D(
      this[0] + vector[0],
      this[1] + vector[1],
      this[2] + vector[2]
    )
  }
  multiply(scalar) {
    return new Vector3D(
      scalar * this[0],
      scalar * this[1],
      scalar * this[2]
    )
  }
  magnitude() {
    // Use Array methods to compute the magnitude
    return Math.sqrt(
      this.map(x => x ** 2) // square each component
        .reduce((a, b) => a + b) // and add them
    )
  }

  static zero() {
    return new Vector3D(0, 0, 0)
  }
}

// Vector3D [5, 7, 9]
new Vector3D(1, 2, 3).add(new Vector3D(4, 5, 6))
// Vector3D [-3, 0, 3]
new Vector3D(-1, 0, 1).multiply(3)
// 7
new Vector3D(2, 3, 6).magnitude()
// Vector3D [0, 0, 0]
Vector3D.zero()
```

#### Complete example

A `Lazy` class that computes a value only when it is needed for the first time:
```js
class Lazy {
  constructor(f) {
    this.f = f
  }

  getValue() {
    if (this.value === undefined) this.value = this.f()
    return this.value
  }
}

const lazyRandom = new Lazy(Math.random)
lazyRandom.getValue() // 0.5037322551664427
lazyRandom.getValue() // 0.5037322551664427
```

### `Set`

JavaScript `Set`s are a builtin datatype analogous to `set` in Python and `LinkedHashSet` in Java.
They are collections that can be quickly queried to see if they contain a given value.

Here are the methods you can call on `Set`s:
```js
// Make an empty set
const words = new Set()

// Add some words to the set
words.add('zebra')
words.add('east')
words.add('running')

// Check whether a word is in the set
words.has('east') // true
words.has('west') // false

// Remove a word from the set
words.delete('zebra')
words.has('running') // true
words.has('zebra') // false

// Get the size of the set
words // Set {'east', 'running'}
words.size // 2

// Iterate over the set.
// Values are returned in the order they were added to the set.
let phrase = ''
for (const word of words) phrase += word + ' '
phrase.trim() // 'east running'

// You can also build a set that is a copy of an array or another set:
const alsoWords = new Set(['apple', 'blackboard', 'chainsaw'])
```

Sets can contain any values, both primitives and objects.
However, objects are always compared using `===`.
For example:
```js
const vectors = new Set()
vectors.add([1, 2, 3])
vectors // Set {[1, 2, 3]}
vectors.has([1, 2, 3]) // false

// If you want to check whether an *equivalent* value is in the set,
// store the values as strings instead:
const vectors2 = new Set()
vectors2.add([1, 2, 3].join(' '))
vectors2 // Set {'1 2 3'}
vectors2.has([1, 2, 3].join(' ')) // true
vectors2.has([1, 2, 4].join(' ')) // false
```

### `Map`

`Map`s in JavaScript are similar to `Set`s: they map keys to values and allow keys to be quickly looked up in the map.
They are similar to `dict`s in Python or `LinkedHashMap`s in Java.

They can be used as follows:
```js
// Make a new map, mapping numbers to their prime factors
const primeFactors = new Map()
for (let testPrime = 2; testPrime <= 100; testPrime++) {
  // Check whether `testPrime` is already in the `primeFactors` map.
  // If so, it must not be prime.
  if (primeFactors.has(testPrime)) continue

  // Add all multiples of the prime into `primeFactors`
  for (let multiple = testPrime; multiple <= 100; multiple += testPrime) {
    // Get `multiple`'s existing list of factors.
    // If `multiple` is not in the map, `get()` returns `undefined`.
    let factors = primeFactors.get(multiple)
    if (factors === undefined) {
      // If `multiple` wasn't in the map, create an empty list of factors for it
      factors = []
      primeFactors.set(multiple, factors)
    }
    // Add the prime factor to the list
    factors.push(testPrime)
  }
}

// Iterate over the keys and corresponding values in the map.
// They are returned in the order they were added to the map.
for (const [number, factors] of primeFactors) {
  // "42 has factors 2, 3, 7", etc.
  console.log(`${number} has factors ${factors.join(', ')}`)
}

// Other methods:
primeFactors.size // 99
primeFactors.delete(2) // deletes the key 2 from the map
```

#### Example

You can use a `Map` to store the return values of a recursive function on different inputs in order to avoid calling it again.
This technique is called "memoization".
```js
// The nth Catalan number counts the ways to match up n pairs of parentheses.
// (See https://en.wikipedia.org/wiki/Catalan_number for more use cases.)
const catalanNumbers = new Map()
function catalanNumber(n) {
  // The 0th Catalan number is 1
  if (n === 0) return 1

  // If we've already computed the nth Catalan number, just return it
  const savedResult = catalanNumbers.get(n)
  if (savedResult !== undefined) return savedResult

  // Otherwise, compute it and save it
  let result = 0
  for (let i = 0; i < n; i++) {
    result += catalanNumber(i) * catalanNumber(n - 1 - i)
  }
  catalanNumbers.set(n, result)
  return result
}

// 4861946401452
catalanNumber(25)
```

### Error handling

JavaScript allows you to throw errors just like in Python or Java.
For example, a Node.js program might throw an error if it is called with the wrong number of arguments:
```js
if (process.argv.length !== 4) {
  throw new Error('Invalid syntax. Usage: node copy.js source destination')
}

const source = process.argv[2]
const destination = process.argv[3]

// Copy the file `source` to `destination`
// ...
```
Running `node copy.js source` without a second argument prints the following message and exits the program:
```
$ node copy.js source
/Users/csander/repos/cs-11-async/copy.js:2
  throw new Error('Invalid syntax. Usage: node copy.js source destination')
  ^

Error: Invalid syntax. Usage: node copy.js source destination
    at Object.<anonymous> (/Users/csander/repos/cs-11-async/copy.js:2:9)
    at Module._compile (internal/modules/cjs/loader.js:1144:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1164:10)
    at Module.load (internal/modules/cjs/loader.js:993:32)
    at Function.Module._load (internal/modules/cjs/loader.js:892:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
```

By default, throwing an error exits the function it was thrown in, which exits the function that called it, and so on, eventually terminating the program.
However, it is often useful to handle an error by running some other code.
This can be done by wrapping the code that throws the error inside a `try`-`catch` block.
For example, `changePassword()` can intercept an error thrown inside the `authenticateUser()` user function and return an appropriate response.
```js
// Never store raw passwords in a real application!
const users = [
  {username: 'csander', password: 'i<3async'},
  {username: 'admin', password: '123456'}
]

// Check that the given user has the given password.
// If not, throw an error.
function authenticateUser(username, password) {
  const user = users.find(user => user.username === username)
  if (user === undefined) throw new Error('No such user')
  if (password !== user.password) throw new Error('Incorrect password')
}

function changePassword(username, password, newPassword) {
  try {
    authenticateUser(username, password)
  }
  catch (error) {
    // If username/password was invalid,
    // report the authentication error message to the client
    return {success: false, message: error.message}
  }

  // Otherwise, change the user's password as requested
  const user = users.find(user => user.username === username)
  user.password = newPassword
  return {success: true}
}
```

### Advanced function parameters

There are several additional types of function parameters:
```js
// Default arguments.
// For example, simulate() in the functions example could be rewritten:
function simulate(f, times = 100) { // default to 100 times if not specified
  const results = []
  while (times > 0) {
    results.push(f())
    times--
  }
  return results
}
simulate(Math.random)
// [0.8004992632182273, 0.4693706190197571, 0.6858328708181958, ...]
simulate(Math.random, 2)
// [0.9457667615017811, 0.9236581755819082]

// Destructuring arguments.
// This can be used to pass parameters with names:
const countOccurrences = ({string, search}) =>
  string.split(search).length - 1
countOccurrences({search: 'ock', string: 'Ruddock rhymes with buttock'})
// 2

// Rest arguments.
// This allows a function to be called with a variable number of arguments.

// Math.max() and Math.min() already work like this:
Math.max(1, 2) // 2
Math.min(6, 5, 10, 7, 9, 8) // 5
// To get the maximum of an array, use the ... ("spread") notation:
const values = [100, 10, 1000, 10000, 1]
Math.max(...values) // 10000

// Also use the ... notation to collect the arguments into an array of arguments
function zip(...arrays) {
  const result = []
  while (true) {
    const zipped = []
    for (const array of arrays) {
      if (result.length === array.length) {
        return result
      }
      zipped.push(array[result.length])
    }
    result.push(zipped)
  }
}
// This sets `arrays` to [[1, 2, 3], ['a', 'b', 'c']]
zip([1, 2, 3], ['a', 'b', 'c'])
// [[1, 'a'], [2, 'b'], [3, 'c']]
```

## Browser-side JavaScript

[JavaScript](https://en.wikipedia.org/wiki/JavaScript) was originally designed as a language that would run in browsers to add dynamic functionality to webpages.
JS code can, for example, access and modify the current web page, handle clicks and other events, and make requests to other websites.
Writing programs in JS is appealing because everyone has a JS interpreter (namely, a web browser) installed on their computer.
Although different browsers and versions of the same browser support slightly different sets of JS features, the core language functionality is identical across browsers.

### Browser-side example

Web browsers render HTML documents.
HTML is *not* a programming language; it is a "Markup Language" that can be used to render text, tables, links, forms, etc.
We won't dive too deeply into how HTML works, but it consists of several types of "elements" that can be nested inside each other.
For example, `<button> button content </button>` makes a `button` element with `button content` displayed inside it.
You can include JavaScript code in an HTML document by putting it inside a `<script>` tag.

[`calculator.html`](calculator.html) is an example of an HTML document that defines some elements and some JS code that interacts with them.
If you download it and open it in any modern web browser, you should see a calculator that you can interact with.

### Browser-side documentation

Mozilla's MDN has great documentation and examples of the entire [language](https://developer.mozilla.org/en-US/docs/Web/JavaScript).
Its pages on JavaScript's builtin objects (e.g. [`Array.push()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)) also have extensive examples of how to use them.

## Node.js

More recently, programmers have started writing JavaScript that runs *outside* a browser.
This is called "server-side" JS, as opposed to "client-side" or "browser-side" JS.
To run server-side JS code, you will need to install the [Node.js](https://nodejs.org/) runtime.

Both client-side and server-side JavaScript are designed around asynchronous APIs, so some projects in this course will run in the browser and some will run in Node.js.
The server-side JS language is **identical** to client-side JS; the only difference is in the set of standard-library functions each provides.

### Running the interpreter

Running Node.js scripts looks a lot more like running Python scripts than running JS in the browser.
To execute the JS file `script.js`, you would run `node script.js` in a terminal.
Node.js also has a REPL that you can open by running `node`, which is very useful for testing out bits of code.

### Modules

Node.js has a powerful module system that allows you to define `function`s, `class`es, etc. in one file and use them in another.
Unlike in Python modules, variables and functions defined in one file are not visible outside it by default; you need to *explicitly* export them from the file.
Each module exports whatever value it assigns to `module.exports`.
For example, we can make a module `linked-list.js` that exports a `LinkedList` class and a function `arrayToList`:
```js
class LinkedList {
  constructor(node) {
    this.head = node
  }

  addFront(data) {
    return new LinkedList({data, rest: this.head})
  }
  toArray() {
    const values = []
    for (let current = this.head; current; current = current.rest) {
      values.push(current.data)
    }
    return values
  }
}

function arrayToList(array) {
  let list = new LinkedList()
  for (let i = array.length - 1; i >= 0; i--) {
    list = list.addFront(array[i])
  }
  return list
}

// We export an *object* with `LinkedList` and `arrayToList` as its fields
module.exports = {
  LinkedList,
  arrayToList
}
```

In Node.js, you call the function `require()` to import a module.
The location of the module to import is passed to `require()`.
For example, if `linked-list.js` is in the same directory, you would call `require('./linked-list')`.
If `linked-list.js` were inside the directory `utils`, you would call `require('./utils/linked-list')`.
```js
// It is common to "unpack" the values exported from another module
const {arrayToList, LinkedList} = require('./linked-list')

const empty = new LinkedList()
empty.toArray() // []

const list234 = arrayToList([2, 3, 4])
const list1234 = list234.addFront(1)
list1234.toArray() // [1, 2, 3, 4]
list234.toArray() // [2, 3, 4]
```

Most of the functions included in Node.js need to be imported from the corresponding library, e.g. `fs` for file system operations, `http` for making HTTP servers and requests, and `zlib` for compressing and decompressing files.
See the example below for using one of these modules.

### Node.js example

[`copy.js`](copy.js) is a simple Node.js program that copies one file to another (like the command-line program `cp`).
If you download it, you can run it as `node copy.js source_file destination_file`.
It reports an error if the wrong number of arguments are passed or an error is thrown when reading the source file or writing the destination file.
```js
// Import the file system module
const fs = require('fs')

if (process.argv.length !== 4) {
  throw new Error('Invalid syntax. Usage: node copy.js source destination')
}

// Extract the command line arguments
const source = process.argv[2]
const destination = process.argv[3]

// Copy `source` to `destination`.
// The notes on streams discuss a more efficient way to do this.

// Read the contents of `source`
fs.readFile(source, (err, data) => {
  if (err) throw err

  // Write the contents to `destination`
  fs.writeFile(destination, data, err => {
    if (err) throw err
  })
})
```

### Node.js documentation

Node.js also has very detailed documentation of its standard library at [nodejs.org](https://nodejs.org/api/).
It's broken down by module (e.g. [`fs`](https://nodejs.org/api/fs.html) or [`http`](https://nodejs.org/api/http.html)) with entries for all the functions exported by each module (e.g. [`fs.readFile()`](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback)).