Core Features

Questions

  • How can I execute short snippets of JavaScript interactively?
  • How can I run small JavaScript programs from the command line?
  • How can I print text in JavaScript?
  • What are JavaScript’s basic data types?
  • How can I find out what type something is?
  • How do I write loops?
  • How do I write conditionals?
  • What counts as true and false?
  • How do I format text?
  • How do I format JavaScript code?
  • How do I store lists of values?
  • How do I store values by name?
  • How do I define functions?
  • How do I divide source code into multiple files?

Introduction

Hello, World

console.log('hello, world')
hello, world
node src/core/hello.js

Basic Data Types

const aNumber = 123.45
console.log('the type of', aNumber, 'is', typeof aNumber)

const anInteger = 123
console.log('the type of', anInteger, 'is', typeof anInteger)

const aString = 'some text'
console.log('the type of', aString, 'is', typeof aString)

const otherValues = [true, undefined, null]
for (let value of otherValues) {
  console.log('the type of', value, 'is', typeof value)
}

console.log('the type of', console.log, 'is', typeof console.log)
the type of 123.45 is number
the type of 123 is number
the type of some text is string
the type of true is boolean
the type of undefined is undefined
the type of null is object
the type of function () { [native code] } is function

Control Flow

const values = [false, true, 0, 1, '', 'text', undefined, null, [], [2, 3]]
for (let v of values) {
  if (v) {
    console.log(`${v} of type ${typeof v} is truthy`)
  } else {
    console.log(`${v} of type ${typeof v} is falsy`)
  }
}
false of type boolean is falsy
true of type boolean is truthy
0 of type number is falsy
1 of type number is truthy
 of type string is falsy
text of type string is truthy
undefined of type undefined is falsy
null of type object is falsy
 of type object is truthy
2,3 of type object is truthy

Formatting

for (let color of ['red', 'green', 'blue']) {
  const message = `color is ${color}`
  console.log(message, `and capitalized is ${color.toUpperCase()}`)
}
color is red and capitalized is RED
color is green and capitalized is GREEN
color is blue and capitalized is BLUE

Objects

const creature = {
  'order': 'Primates',
  'family': 'Callitrichidae',
  'genus': 'Callithrix',
  'species': 'Jacchus'
}

console.log(`creature is ${creature}`)
console.log(`creature.genus is ${creature.genus}`)
for (let key in creature) {
  console.log(`creature[${key}] is ${creature[key]}`)
}
creature is [object Object]
creature.genus is Callithrix
creature[order] is Primates
creature[family] is Callitrichidae
creature[genus] is Callithrix
creature[species] is Jacchus

Functions

function limits (values) {
  if (!values.length) {
    return [undefined, undefined]
  }
  let low = values[0]
  let high = values[0]
  for (let v of values) {
    if (v < low) low = v
    if (v > high) high = v
  }
  return [low, high]
}
const allTests = [
  [],
  [9],
  [3, 30, 300],
  ['apple', 'Grapefruit', 'banana'],
  [3, 'apple', ['sub-array']]
]
for (let test of allTests) {
  console.log(`limits of ${test} are ${limits(test)}`)
}
limits of  are ,
limits of 9 are 9,9
limits of 3,30,300 are 3,300
limits of apple,Grapefruit,banana are Grapefruit,banana
limits of 3,apple,sub-array are 3,3
const limits = (values) => {
  if (!values.length) {
    return [undefined, undefined]
  }
  let low = values[0]
  let high = values[0]
  for (let v of values) {
    if (v < low) low = v
    if (v > high) high = v
  }
  return [low, high]
}

Stuck in the Past

  • Why not stick to function and fix behavior?
  • Would break legacy programs that rely on old behavior
  • Want to make it really easy to define little functions
  • The way a language is used shapes the evolution of its syntax

Modules

const bound = 3

const clip = (values) => {
  let result = []
  for (let v in values) {
    if (v <= bound) {
      result.push(v)
    }
  }
  return result
}

module.exports = {
  clip: clip
}
const utilities = require('./utilities')

const data = [-1, 5, 3, 0, 10]
const result = utilities.clip(data)
console.log(`clip(${data}) -> ${result}`)
clip(-1,5,3,0,10) -> 0,1,2,3

Challenges

Typeof

What kind of thing is typeof? Is it an expression? A function? Something else?

Fill in the Blanks

Answer these questions about the program below: so that it produces the output shown.

  1. What does Array.push do?
  2. How does a while loop work?
  3. What does += do?
  4. What does Array.reverse do, and what does it return?
let current = 0
let table = []
while (current < 5) {
  const entry = `square of ${current} is ${current * current}`
  table.push(entry)
  current += 1
}
table.reverse()
for (let line of table) {
  console.log(line)
}
square of 4 is 16
square of 3 is 9
square of 2 is 4
square of 1 is 1
square of 0 is 0

What Is Truth?

Write a function called isTruthy that returns true for everything that JavaScript considers truthy, and false for everything it considers falsy, except empty arrays: isTruthy should return false for those.

What Does This Do?

Explain what is happening in the assignment statement that creates the constant creature.

const genus = 'Callithrix'
const species = 'Jacchus'
const creature = {genus, species}
console.log(creature)
{ genus: 'Callithrix', species: 'Jacchus' }

What Does This Code Do?

Explain what is happening in the assignment statement in this program. Use this technique to rewrite src/core/import.js so that clip can be called directly as clip(…) rather than utilities.clip(…).

const creature = {
  genus: 'Callithrix',
  species: 'Jacchus'
}
const {genus, species} = creature
console.log(`genus is ${genus}`)
console.log(`species is ${species}`)

Key Points

  • Use console.log to print messages.
  • Use dotted notation X.Y to get part Y of object X.
  • Basic data types are Booleans, numbers, and character strings.
  • Ararys store multiple values in order.
  • The special values null and undefined mean ‘no value’ and ‘does not exist’.
  • Define constants with const and variables with let.
  • typeof returns the type of a value.
  • for (let variable of collection) {…} iterates through the values in an array.
  • if (condition) {…} else {…} conditionally executes some code.
  • false, 0, the empty string, null, and undefined are false; everything else is true.
  • Use back quotes and ${…} to interpolate values into strings.
  • An object is a collection of name/value pairs written in `{…}.
  • object[key] or object.key gets a value from an object.
  • Functions are objects that can be assigned to variables, stored in lists, etc.
  • function (…parameters…) {…body…} is the old way to define a function.
  • name = (…parameters…) => {…body…} is the new way to define a function.
  • Use return inside a function body to return a value at any point.
  • Use modules to divide code between multiple files for re-use.
  • Assign to module.exports to specify what a module exports.
  • require(…path…) imports a module.
  • Paths beginning with ‘.’ are imported locally, but paths without ‘.’ look in the library.