CPNT 262 Day 17 - JSON 404 errors and local modules

Housekeeping

Trophy of the Day

  • A local module!

1. Spoiler demo

Materials

Activity

  • A walk-through and optimization of the guild spoilers.

Key Takeaways

A good coder is a lazy coder. Arrow functions are made for lazy coders.

Given the following input variables:

const cats = require('./cats') // Array of objects
const searchName = 'fluffy' // From either argv or url

Each of the following do the exact same thing (find a cat based on name).

  1. Not lazy at all (bad):

    const foundCat = cats.find(function(cat){
    if (cat.name === searchName) {
    return true
    } else {
    return false
    }
    })
    • The if/else is redundant in this case.
  2. Lazy (good):

    const foundCat = cats.find(function(cat){
    return cat.name === searchName
    })
    • Returning the comparison expression directly instead.
  3. Suuuuper Lazy (fancy and modern):

    const foundCat = cats.find(cat => cat.name === searchName)
    • return is assumed if the block is a single expression.

2. Review

Terminology

Expression
A piece of code that returns a value.

Materials

Activity

Create a function that accepts any array as an argument and returns a random item in that array. See: Find a random item in an Array


3. Local modules

Terminology

Module
A reusable block of code whose existence does not accidentally impact other code (Javascript didn't have this before).
CommonJS Module
An agreed upon standard for how code modules should be structured. Because modules are a relatively new feature of Javascript, there are competing standards: ES Modules are used in the browser but CommonJS Modules are most common in Node.js (which supports both standards).

Materials

Key Takeaways

  • You must prefix local module paths with ./.
  • module.exports is an empty object by default.
  • You can assign any value to module.exports to expose it to the outer environment.
  • require() returns the value that is assigned to a module's module.exports. All other variables will be private to the module.

Activities

  • Find a literal in your Command Line App assignment and move it into a local module.

  • Take the random item function from this morning's demo and move it into a local module such that:

    const randomItem = require('./random-item')
    const array = ['one', 'two', 'three']

    console.log(randomItem(array)) // Output a random item

Lab Time

  • Ash and Norv!