npm cheatsheet

Package management

npm iAlias for npm install
npm installInstall everything in package.json
npm install lodashInstall a package
npm install --save-dev lodashInstall as devDependency
npm install --save-exact lodashInstall with exact

--save is the default as of npm@5. Previously, using npm install without --save doesn’t update package.json.

Install names

npm i saxNPM package
npm i sax@latestSpecify tag latest
npm i sax@3.0.0Specify version 3.0.0
npm i sax@">=1 <2.0"Specify version range
npm i @org/saxScoped NPM package
npm i user/repoGitHub
npm i user/repo#masterGitHub
npm i github:user/repoGitHub
npm i gitlab:user/repoGitLab
npm i /path/to/repoAbsolute path
npm i ./archive.tgzTarball
npm i https://site.com/archive.tgzTarball via HTTP

Updating

npm updateUpdate production packages
npm update --devUpdate dev packages
npm update -gUpdate global packages
npm update lodashUpdate a package

Misc features

# Add someone as an owner
npm owner add USERNAME PACKAGENAME
# list packages
npm ls
# Adds warning to those that install a package of old versions
npm deprecate PACKAGE@"< 0.2.0" "critical bug fixed in v0.2.0"
# update all packages, or selected packages
npm update [-g] PACKAGE
# Check for outdated packages
npm outdated

fetch() cheatsheet

Fetch

fetch('/data.json')
  .then(response => response.json())
  .then(data => {
    console.log(data)
  })
  .catch(err => ...)
 

Response

fetch('/data.json')
.then(res => {
  res.text()       // response body (=> Promise)
  res.json()       // parse via JSON (=> Promise)
  res.status       //=> 200
  res.statusText   //=> 'OK'
  res.redirected   //=> false
  res.ok           //=> true
  res.url          //=> 'http://site.com/data.json'
  res.type         //=> 'basic'
                   //   ('cors' 'default' 'error'
                   //    'opaque' 'opaqueredirect')

  res.headers.get('Content-Type')
})

Request options

fetch('/data.json', {
  method: 'post',
  body: new FormData(form), // post body
  body: JSON.stringify(...),

  headers: {
    'Accept': 'application/json'
  },

  credentials: 'same-origin', // send cookies
  credentials: 'include',     // send cookies, even in CORS

})

Catching errors

fetch('/data.json')
  .then(checkStatus)
function checkStatus (res) {
  if (res.status >= 200 && res.status < 300) {
    return res
  } else {
    let err = new Error(res.statusText)
    err.response = res
    throw err
  }
}

Non-2xx responses are still successful requests. Use another function to turn them to errors.

Using with node.js

const fetch = require('isomorphic-fetch')

See: isomorphic-fetch (npmjs.com)

References

JavaScript Date cheatsheet

Constructor

// Now
new Date()
// ms since epoch
new Date(1419785527580)
// Date format
new Date("May 17, 1995 03:24:00")
// ISO date format
new Date("2013-03-01T01:10:00")
new Date(2014, 2, 1, 13, 0, 59, 0)

Constructor

new Date(2014,2,1,13,0,59,0)
DateYearMonthDayHourMinSecMilli

Months are zero-indexed (eg, January is 0).

Conversion

d.toString()"Mon Dec 29 2014 00:58:28 GMT+0800 (PHT)"
d.toTimeString()"00:58:46 GMT+0800 (PHT)"
d.toUTCString()"Sun, 28 Dec 2014 16:58:59 GMT"
d.toDateString()"Thu Jan 10 2013"
d.toISOString()"2013-01-09T16:00:00.000Z"
d.toLocaleString()"12/29/2014, 12:57:31 AM"
d.toLocaleTimeString()"12:57:31 AM"
d.getTime()1419785527580

Accessing

Getters

.getDate()1..31
.getDay()0..6 (sun..sat)
.getFullYear()2014
.getMonth()0..11
.getHours() 
.getMinutes() 
.getSeconds() 
.getMilliseconds() 
.getTime()ms since epoch
.getTimezoneOffset() 

UTC versions are also available (eg, .getUTCDate().getUTCDay(), etc).

Setters

.setDate (val) 
.setDay (val) 
.setFullYear (val) 
.setMonth (val) 
.setHours (val) 
.setMinutes (val) 
.setSeconds (val) 
.setMilliseconds (val) 
.setTime (val) 
.setTimezoneOffset (val) 

ES2015+ cheatsheet

A quick overview of new JavaScript features in ES2015, ES2016, ES2017, ES2018 and beyond.

Block scoping

Let

function fn () {
  let x = 0
  if (true) {
    let x = 1 // only inside this `if`
  }
}
 
 

Const

const a = 1

let is the new var. Constants work just like let, but can’t be reassigned. See: Let and const

Backtick strings

Interpolation

const message = `Hello ${name}`

Multiline strings

const str = `
hello
world
`

Templates and multiline strings. See: Template strings

Binary and octal literals

let bin = 0b1010010
let oct = 0o755

See: Binary and octal literals

New methods

New string methods

"hello".repeat(3)
"hello".includes("ll")
"hello".startsWith("he")
"hello".padStart(8) // "   hello"
"hello".padEnd(8) // "hello   " 
"hello".padEnd(8, '!') // hello!!!
"\u1E9B\u0323".normalize("NFC")

See: New methods

Classes

class Circle extends Shape {

Constructor

  constructor (radius) {
    this.radius = radius
  }
 

Methods

  getArea () {
    return Math.PI * 2 * this.radius
  }
 

Calling superclass methods

  expand (n) {
    return super.expand(n) * Math.PI
  }
 

Static methods

  static createFromDiameter(diameter) {
    return new Circle(diameter / 2)
  }
}
 

Syntactic sugar for prototypes. See: Classes

Exponent operator

const byte = 2 ** 8
// Same as: Math.pow(2, 8)
 

Promises

Making promises

new Promise((resolve, reject) => {
  if (ok) { resolve(result) }
  else { reject(error) }
})
 

For asynchronous programming. See: Promises

Using promises

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
 
 

Using promises with finally

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
  .finally(() => { // logic independent of success/error })
 

The handler is called when the promise is fulfilled or rejected.

Promise functions

Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)

Async-await

async function run () {
  const user = await getUser()
  const tweets = await getTweets(user)
  return [user, tweets]
}
 
 

async functions are another way of using functions.

See: async function

Destructuring

Destructuring assignment

Arrays

const [first, last] = ['Nikola', 'Tesla']
 

Objects

let {title, author} = {
  title: 'The Silkworm',
  author: 'R. Galbraith'
}
 

Supports for matching arrays and objects. See: Destructuring

Default values

const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores
// Result:
// math === 22, sci === 33, arts === 50

Default values can be assigned while destructuring arrays or objects.

Function arguments

function greet({ name, greeting }) {
  console.log(`${greeting}, ${name}!`)
}
 
greet({ name: 'Larry', greeting: 'Ahoy' })

Destructuring of objects and arrays can also be done in function arguments.

Default values

function greet({ name = 'Rauno' } = {}) {
  console.log(`Hi ${name}!`);
}
 
greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!

Reassigning keys

function printCoordinates({ left: x, top: y }) {
  console.log(`x: ${x}, y: ${y}`)
}
 
printCoordinates({ left: 25, top: 90 })

This example assigns x to the value of the left key.

Loops

for (let {title, artist} of songs) {
  ···
}
 

The assignment expressions work in loops, too.

Object destructuring

const { id, ...detail } = song;
 

Extract some keys individually and remaining keys in the object using rest (…) operator

Spread

Object spread

with Object spread

const options = {
  ...defaults,
  visible: true
}
 

without Object spread

const options = Object.assign(
  {}, defaults,
  { visible: true })

The Object spread operator lets you build new objects from other objects.

See: Object spread

Array spread

with Array spread

const users = [
  ...admins,
  ...editors,
  'rstacruz'
]
 
 

without Array spread

const users = admins
  .concat(editors)
  .concat([ 'rstacruz' ])

The spread operator lets you build new arrays in the same way.

See: Spread operator

Functions

Function arguments

Default arguments

function greet (name = 'Jerry') {
  return `Hello ${name}`
}
 

Rest arguments

function fn(x, ...y) {
  // y is an Array
  return x * y.length
}
 

Spread

fn(...[1, 2, 3])
// same as fn(1, 2, 3)
 

Default, rest, spread. See: Function arguments

Fat arrows

Fat arrows

setTimeout(() => {
  ···
})
 

With arguments

readFile('text.txt', (err, data) => {
  ...
})
 

Implicit return

numbers.map(n => n * 2)
// No curly braces = implicit return
// Same as: numbers.map(function (n) { return n * 2 })
numbers.map(n => ({
  result: n * 2
}))
// Implicitly returning objects requires parentheses around the object
 
 
 
 

Like functions but with this preserved. See: Fat arrows

Objects

Shorthand syntax

module.exports = { hello, bye }
// Same as: module.exports = { hello: hello, bye: bye }

See: Object literal enhancements

Methods

const App = {
  start () {
    console.log('running')
  }
}
// Same as: App = { start: function () {···} }
 

See: Object literal enhancements

Getters and setters

const App = {
  get closed () {
    return this.status === 'closed'
  },
  set closed (value) {
    this.status = value ? 'closed' : 'open'
  }
}
 
 

See: Object literal enhancements

Computed property names

let event = 'click'
let handlers = {
  [`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }
 

See: Object literal enhancements

Extract values

const fatherJS = { age: 57, name: "Brendan Eich" }

Object.values(fatherJS)
// [57, "Brendan Eich"]
Object.entries(fatherJS)
// [["age", 57], ["name", "Brendan Eich"]]

Modules

Imports

import 'helpers'
// aka: require('···')
import Express from 'express'
// aka: const Express = require('···').default || require('···')
import { indent } from 'helpers'
// aka: const indent = require('···').indent
import * as Helpers from 'helpers'
// aka: const Helpers = require('···')
import { indentSpaces as indent } from 'helpers'
// aka: const indent = require('···').indentSpaces

import is the new require(). See: Module imports

Exports

export default function () { ··· }
// aka: module.exports.default = ···
export function mymethod () { ··· }
// aka: module.exports.mymethod = ···
export const pi = 3.14159
// aka: module.exports.pi = ···

export is the new module.exports. See: Module exports

Generators

Generators

function* idMaker () {
  let id = 0
  while (true) { yield id++ }
}
let gen = idMaker()
gen.next().value  // → 0
gen.next().value  // → 1
gen.next().value  // → 2

It’s complicated. See: Generators

For..of iteration

for (let i of iterable) {
  ···
}

For iterating through generators and arrays. See: For..of iteration

Vim scripting cheatsheet

Start hacking

let name = "John"
echo "Hello, " . name

You can either put this in a script (script.vim) and run it (:source script.vim), or you can type the commands individually in normal mode as :let and :echo.

Learn by example

function! SuperTab()
  let l:part = strpart(getline('.'),col('.')-2,1)
  if (l:part=~'^\W\?$')
      return "\<Tab>"
  else
      return "\<C-n>"
  endif
endfunction

imap <Tab> <C-R>=SuperTab()<CR>

Here’s another example with functions, variables and mapping.

Variables

Defining

let var = "hello"

Variable prefixes

let g:ack_options = '-s -H'    " g: global
let s:ack_program = 'ack'      " s: local (to script)
let l:foo = 'bar'              " l: local (to function)

The s: prefix is also available in function names. See :help local-variables

Other prefixes

let w:foo = 'bar'    " w: window
let b:state = 'on'   " b: buffer
let t:state = 'off'  " t: tab
echo v:var           " v: vim special
let @/ = ''          " @  register (this clears last search pattern)
echo $PATH           " $  env

Vim options

echo 'tabstop is ' . &tabstop
if &insertmode
echo &g:option
echo &l:option

Prefix Vim options with &

Operators

a + b             " numbers only!
'hello ' . name   " concat
let var -= 2
let var += 5
let var .= 'string'   " concat

Strings

Strings

let str = "String"
let str = "String with \n newline"

let literal = 'literal, no \ escaping'
let literal = 'that''s enough'  " double '' => '

echo "result = " . re   " concatenation

Also see :help literal-string and :help expr-quote. See: Strings

String functions

strlen(str)    " length
len(str)       " same
strchars(str)  " character length

split("one two three")       "=> ['one', 'two', 'three']
split("one.two.three", '.')  "=> ['one', 'two', 'three']

join(['a', 'b'], ',')  "=> 'a,b'

tolower('Hello')
toupper('Hello')

Also see :help functions See: String functions

Functions

Functions

" prefix with s: for local script-only functions
function! s:Initialize(cmd, args)
  " a: prefix for arguments
  echo "Command: " . a:cmd

  return true
endfunction

See: Functions

Namespacing

function! myplugin#hello()

Calling functions

call s:Initialize()
call s:Initialize("hello")

Consuming return values

echo "Result: " . s:Initialize()

Abortable

function! myfunction() abort
endfunction

Aborts when an error occurs.

Var arguments

function! infect(...)
  echo a:0    "=> 2
  echo a:1    "=> jake
  echo a:2    "=> bella

  for s in a:000  " a list
    echon ' ' . s
  endfor
endfunction

infect('jake', 'bella')

See :help function-argument. See: Var arguments

Loops

for s in list
  echo s
  continue  " jump to start of loop
  break     " breaks out of a loop
endfor
while x < 5
endwhile

Custom commands

Custom commands

command! Save :set fo=want tw=80 nowrap

Custom commands start with uppercase letters. The ! redefines a command if it already exists.

Commands calling functions

command! Save call <SID>foo()
function! s:foo()
  ...
endfunction

Commands with arguments

command! -nargs=? Save call script#foo(<args>)
-nargs=00 arguments, default
-nargs=11 argument, includes spaces
-nargs=?0 or 1 argument
-nargs=*0+ arguments, space separated
-nargs=+1+ arguments, space reparated

Flow

Conditionals

let char = getchar()
if char == "\<LeftMouse>"
  " ...
elseif char == "\<RightMouse>"
  " ...
else
  " ...
endif

Truthiness

if 1 | echo "true"  | endif
if 0 | echo "false" | endif
if 1       "=> 1 (true)
if 0       "=> 0 (false)
if "1"     "=> 1 (true)
if "456"   "=> 1 (true)
if "xfz"   "=> 0 (false)

No booleans. 0 is false, 1 is true. See: Truthiness

Operators

if 3 > 2
if a && b
if (a && b) || (c && d)
if !c

See :help expression-syntax. See: Operators

Strings

if name ==# 'John'     " case-sensitive
if name ==? 'John'     " case-insensitive
if name == 'John'      " depends on :set ignorecase

" also: is#, is?, >=#, >=?, and so on

Identity operators

a is b
a isnot b

Checks if it’s the same instance object.

Regexp matches

"hello" =~ '/x/'
"hello" !~ '/x/'

Single line

if empty(a:path) | return [] | endif
a ? b : c

Use | to join lines together.

Boolean logic

if g:use_dispatch && s:has_dispatch
  ···
endif

#Lists

Lists

let mylist = [1, two, 3, "four"]

let first = mylist[0]
let last  = mylist[-1]

" Suppresses errors
let second = get(mylist, 1)
let second = get(mylist, 1, "NONE")

Functions

len(mylist)
empty(mylist)

sort(list)
let sortedlist = sort(copy(list))

split('hello there world', ' ')

Concatenation

let longlist = mylist + [5, 6]
let mylist += [7, 8]

Sublists

let shortlist = mylist[2:-1]
let shortlist = mylist[2:]     " same

let shortlist = mylist[2:2]    " one item

Push

let alist = [1, 2, 3]
let alist = add(alist, 4)

Map

call map(files, "bufname(v:val)")  " use v:val for value
call filter(files, 'v:val != ""')

Dictionaries

Dictionaries

let colors = {
  \ "apple": "red",
  \ "banana": "yellow"
}

echo colors["a"]
echo get(colors, "apple")   " suppress error

See :help dict

Using dictionaries

remove(colors, "apple")
" :help E715
if has_key(dict, 'foo')
if empty(dict)
keys(dict)
len(dict)
max(dict)
min(dict)
count(dict, 'x')
string(dict)
map(dict, '<>> " . v:val')

Iteration

for key in keys(mydict)
  echo key . ': ' . mydict(key)
endfor

Prefixes

keys(s:)

Prefixes (s:g:l:, etc) are actually dictionaries.

Extending

" Extending with more
let extend(s:fruits, { ... })

Casting

str2float("2.3")
str2nr("3")
float2nr("3.14")

Numbers

Numbers

let int = 1000
let int = 0xff
let int = 0755   " octal

See :help Number. See: Numbers

Floats

let fl = 100.1
let fl = 5.4e4

See :help Float

Arithmetic

3 / 2     "=> 1, integer division
3 / 2.0   "=> 1.5
3 * 2.0   "=> 6.0

Math functions

sqrt(100)
floor(3.5)
ceil(3.3)
abs(-3.4)

sin() cos() tan()
sinh() cosh() tanh()
asin() acos() atan()

Vim-isms

Execute a command

execute "vsplit"
execute "e " . fnameescape(filename)

Runs an ex command you typically run with :. Also see :help execute. See: Execute a command

Running keystrokes

normal G
normal! G   " skips key mappings

execute "normal! gg/foo\<cr>dd"

Use :normal to execute keystrokes as if you’re typing them in normal mode. Combine with :execute for special keystrokes. See: Running keystrokes

Getting filenames

echo expand("%")      " path/file.txt
echo expand("%:t")    " file.txt
echo expand("%:p:h")  " /home/you/path/file.txt
echo expand("%:r")    " path/file
echo expand("%:e")    " txt

See :help expand

Silencing

silent g/Aap/p

Suppresses output. See :help silent

Echo

echoerr 'oh it failed'
echomsg 'hello there'
echo 'hello'

echohl WarningMsg | echomsg "=> " . a:msg | echohl None

Settings

set number
set nonumber
set number!     " toggle
set numberwidth=5
set guioptions+=e

Prompts

let result = confirm("Sure?")
execute "confirm q"

Built-ins

has("feature")  " :h feature-list
executable("python")
globpath(&rtp, "syntax/c.vim")

exists("$ENV")
exists(":command")
exists("variable")
exists("+option")
exists("g:...")

Mapping

Mapping commands

nmap
vmap
imap
xmap
nnoremap
vnoremap
inoremap
xnoremap
...

Explanation

[nvixso](nore)map
 │       └ don't recurse
 │
 └ normal, visual, insert,
   eX mode, select, operator-pending

Arguments

<buffer>only in current buffer
<silent>no echo
<nowait> 

Syntax

Highlights

hi Comment
  term=bold,underline
  gui=bold
  ctermfg=4
  guifg=#80a0ff

Filetype detection

augroup filetypedetect
  au! BufNewFile,BufRead *.json setf javascript
augroup END

au Filetype markdown setlocal spell

Conceal

set conceallevel=2
syn match newLine "<br>" conceal cchar=}
hi newLine guifg=green

Region conceal

syn region inBold concealends matchgroup=bTag start="<b>" end="</b>"
hi inBold gui=bold
hi bTag guifg=blue

Syntax

syn match :name ":regex" :flags

syn region Comment  start="/\*"  end="\*/"
syn region String   start=+"+    end=+"+	 skip=+\\"+

syn cluster :name contains=:n1,:n2,:n3...

flags:
  keepend
  oneline
  nextgroup=
  contains=
  contained

hi def link markdownH1 htmlH1

Include guards

if exists('g:loaded_myplugin')
  finish
endif

" ...

let g:loaded_myplugin = 1

Capybara cheatsheet

visit articles_path
click 'Link Text'
click_button
click_link

Interacting with forms

attach_file 'Image', '/path/to/image.jpg'
fill_in 'First Name', with: 'John'
check 'A checkbox'
uncheck 'A checkbox'
choose 'A radio button'
select 'Option', from: 'Select box'
unselect

Limiting

within '.classname' do
  click '...'
end
within_fieldset :id do
  ...
end

Querying

Predicates

page.has_css?('.button')
expect(page).to have_css('.button')
page.should have_css('.button')
PositiveNegative
has_content?has_no_content?
has_css? (selector)has_no_css?
has_xpath? (path)has_no_xpath?
has_link? (selector)has_no_link?
has_button? (selector)has_no_button?
has_field? (selector)has_no_field?
has_checked_field? (selector)has_unchecked_field?
has_table? (selector)has_no_table?
has_select? (selector)has_no_select?

In Rspec, these also map to matchers like page.should have_content.

Selectors

expect(page).to have_button('Save')
expect(page).to have_button('#submit')
expect(page).to have_button('//[@id="submit"]')

The selector arguments can be text, CSS selector, or XPath expression.

RSpec assertions

page.has_button?('Save')
expect(page).to have_no_button('Save')

In RSpec, you can use page.should assertions.

About negatives

expect(page).to have_no_button('Save')   # OK
expect(page).not_to have_button('Save')  # Bad

Use should have_no_* versions with RSpec matchers because should_not have_* doesn’t wait for a timeout from the driver.

#RSpec

Matchers

expect(page).to \
  have_selector '.blank-state'
  have_selector 'h1#hola', text: 'Welcome'
  have_button 'Save'
  have_checked_field '#field'
  have_unchecked_field
  have_css '.class'
  have_field '#field'
  have_table '#table'
  have_xpath '//div'
  have_link 'Logout', href: logout_path
  have_select 'Language',
    selected: 'German'
    options: ['Engish', 'German']
    with_options: ['Engish', 'German'] # partial match
  have_text 'Hello',
    type: :visible # or :all
    # alias: have_content

Common options

All matchers have these options:

  text: 'welcome'
  text: /Hello/
  visible: true
  count: 4
  between: 2..5
  minimum: 2
  maximum: 5
  wait: 10

#Other features

Finding

find(selector)
find_button(selector)
find_by_id(id)
find_field(selector)
find_link(selector)
locate

Scoping

within '#delivery' do
  fill_in 'Street', with: 'Hello'
end
within :xpath, '//article'
within_fieldset
within_table
within_frame
scope_to
find('#x').fill_in('Street', with: 'Hello')
# same as within

Scripting

execute_script('$("input").trigger('change')')
evaluate_script('window.ga')

Executes JavaScript.

Debugging

save_and_open_page

Opens the webpage in your browser.

Page

page
  .all('h3')
  .body
  .html
  .source
  .current_host
  .current_path
  .current_url

AJAX

using_wait_time 10 do
  ...
end

Misc

drag
field_labeled

Page object

page.status_code == 200
page.response_headers

See: http://www.rubydoc.info/github/jnicklas/capybara/master/Capybara/Session

Poltergeist

Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app, :inspector => true)
end
Capybara.javascript_driver = :poltergeist

Use poltergeist to integrate PhantomJS.

Blacklist

config.before :each, :js do
  page.driver.browser.url_blacklist = [
    'fonts.googleapis.com',
    'use.typekit.net',
    'f.vimeocdn.com',
    'player.vimeo.com',
    'www.googletagmanager.com'
  ].flat_map { |domain| [ "http://#{domain}", "https://#{domain}" ] }
end

Debugging

Enable inspector: true and then:

page.driver.debug

To pause execution for a while:

page.driver.pause

Selenium

Accepting confirm() and alert()

accept_alert { ... }
dismiss_confirm { ... }
accept_prompt(with: 'hi') { ... }

Alternatively:

page.driver.browser.switch_to.alert.accept

Updating session

page.set_rack_session(foo: 'bar')

See also

Vimdiff cheatsheet

Vim is a very efficient text editor. This reference was made for Vim 8.0.

]cNext difference
[cPrevious difference

Editing

doDiff Obtain!
Pull the changes to the current file.
dpDiff Put!
Push the changes to the other file.
:diffupdateRe-scan the files for differences.
ZQQuit without checking changes

Folds

zo / zOOpen
zc / zCClose
za / zAToggle
zvOpen folds for this line
zMClose all
zROpen all
zmFold more (foldlevel += 1)
zrFold less (foldlevel -= 1)
zxUpdate folds

Also see

Kotlin cheatsheet

Kotlin is a statically typed programming language for modern multiplatform applications.

Mutability

var mutableString: String = "Adam"
val immutableString: String = "Adam"
val inferredString = "Adam"

Strings

val name = "Adam"
val greeting = "Hello, " + name
val greetingTemplate = "Hello, $name"

Numbers

val intNum = 10
val doubleNum = 10.0
val longNum = 10L
val floatNum = 10.0F

Booleans

val trueBoolean = true
val falseBoolean = false
val andCondition = trueBoolean && falseBoolean
val orCondition = trueBoolean || falseBoolean

Static Fields

class Person {
    companion object {
        val NAME_KEY = "name_key"
    }
}

val key = Person.NAME_KEY

Null Safety

Nullable properties

val cannotBeNull: String = null // Invalid
val canBeNull: String? = null // Valid

val cannotBeNull: Int = null // Invalid
val canBeNull: Int? = null // Valid

Checking for null

val name: String? = "Adam"

if (name != null && name.length > 0) {
    print("String length is ${name.length}")
} else {
    print("String is empty.")
}

Safe Operator

val nullableStringLength: Int? = nullableString?.length
val nullableDepartmentHead: String? = person?.department?.head?.name

Elvis Operator

val nonNullStringLength: Int = nullableString?.length ?: 0
val nonNullDepartmentHead: String = person?.department?.head?.name ?: ""
val nonNullDepartmentHead: String = person?.department?.head?.name.orEmpty()

Safe Casts

// Will not throw ClassCastException
val nullableCar: Car? = (input as? Car)

Collections

Creation

val numArray = arrayOf(1, 2, 3)
val numList = listOf(1, 2, 3)
val mutableNumList = mutableListOf(1, 2, 3)

Accessing

val firstItem = numList[0]
val firstItem = numList.first()
val firstItem = numList.firstOrNull()

Maps

val faceCards = mutableMapOf("Jack" to 11, "Queen" to 12, "King" to 13)
val jackValue = faceCards["Jack"] // 11
faceCards["Ace"] = 1

Mutability

val immutableList = listOf(1, 2, 3)
val mutableList = immutableList.toMutableList()

val immutableMap = mapOf("Jack" to 11, "Queen" to 12, "King" to 13)
val mutableMap = immutableMap.toMutableMap()

Iterating

for (item in myList) {
    print(item)
}

myList.forEach {
    print(it)
}

myList.forEachIndexed { index, item -> 
    print("Item at $index is: $item")
}

Filtering & Searching

val evenNumbers = numList.filter { it % 2 == 0 }
val containsEven = numList.any { it % 2 == 0 }
val containsNoEvens = numList.none { it % 2 == 0 }
val containsNoEvens = numList.all { it % 2 == 1 }
val firstEvenNumber: Int = numList.first { it % 2 == 0 }
val firstEvenOrNull: Int? = numList.firstOrNull { it % 2 == 0 }

Note: it is the implicit name for a single parameter.

#Functions

Parameters & Return Types

fun printName() {
    print("Adam")
}

fun printName(person: Person) {
    print(person.name)
}

fun getGreeting(person: Person): String {
    return "Hello, ${person.name}"
}

fun getGreeting(person: Person): String = "Hello, ${person.name}"
fun getGreeting(person: Person) = "Hello, ${person.name}"

Higher Order Functions

fun callbackIfTrue(condition: Boolean, callback: () -> Unit) {
    if (condition) {
        callback()
    }
}

callbackIfTrue(someBoolean) {
    print("Condition was true")
}

Extension Functions

fun Int.timesTwo(): Int {
    return this * 2
}

val four = 2.timesTwo()

Default Parameters

fun getGreeting(person: Person, intro: String = "Hello,") {
    return "$intro ${person.name}"
}

// Returns "Hello, Adam"
val hello = getGreeting(Person("Adam"))

// Returns "Welcome, Adam"
val welcome = getGreeting(Person("Adam"), "Welcome,")

Named Parameters

class Person(val name: String = "", age: Int = 0)

// All valid
val person = Person()
val person = Person("Adam", 100)
val person = Person(name = "Adam", age = 100)
val person = Person(age = 100)
val person = Person(age = 100, name = "Adam")

Static Functions

class Fragment(val args: Bundle) {
    companion object {
        fun newInstance(args: Bundle): Fragment {
            return Fragment(args)
        }
    }
}

val fragment = Fragment.newInstance(args)

Classes

Primary Constructor

class Person(val name: String, val age: Int)
val adam = Person("Adam", 100)

Secondary Constructors

class Person(val name: String) {
    private var age: Int? = null

    constructor(name: String, age: Int) : this(name) {
        this.age = age
    }
}

// Above can be replaced with default params
class Person(val name: String, val age: Int? = null)

Inheritance & Implementation

open class Vehicle
class Car : Vehicle()

interface Runner {
    fun run()
}

class Machine : Runner {
    override fun run() {
        // ...
    }
}

Control Flow

If Statements

if (someBoolean) {
    doThing()
} else {
    doOtherThing()
}

For Loops

for (i in 0..10) { } // 1 - 10
for (i in 0 until 10) // 1 - 9
(0..10).forEach { }
for (i in 0 until 10 step 2) // 0, 2, 4, 6, 8

When Statements

when (direction) {
    NORTH -> {
        print("North")
    }
    SOUTH -> print("South")
    EAST, WEST -> print("East or West")
    "N/A" -> print("Unavailable")
    else -> print("Invalid Direction")
}

While Loops

while (x > 0) {
    x--
}

do {
    x--
} while (x > 0)

#Destructuring Declarations

Objects & Lists

val person = Person("Adam", 100)
val (name, age) = person

val pair = Pair(1, 2)
val (first, second) = pair

val coordinates = arrayOf(1, 2, 3)
val (x, y, z) = coordinates

ComponentN Functions

class Person(val name: String, val age: Int) {
	operator fun component1(): String {
		return name
	}

	operator fun component2(): Int {
		return age
	}
}

References

MySQL cheatsheet

Create / Delete Database

CREATE DATABASE dbNameYouWant
CREATE DATABASE dbNameYouWant CHARACTER SET utf8
DROP DATABASE dbNameYouWant
ALTER DATABASE dbNameYouWant CHARACTER SET utf8

Backup Database to SQL File

mysqldump -u Username -p dbNameYouWant > databasename_backup.sql

Restore from backup SQL File

mysql - u Username -p dbNameYouWant < databasename_backup.sql

Repair Tables After Unclean Shutdown

mysqlcheck --all-databases
mysqlcheck --all-databases --fast

Browsing

SHOW DATABASES
SHOW TABLES
SHOW FIELDS FROM table / DESCRIBE table
SHOW CREATE TABLE table
SHOW PROCESSLIST
KILL process_number

Select

SELECT * FROM table
SELECT * FROM table1, table2, ...
SELECT field1, field2, ... FROM table1, table2, ...
SELECT ... FROM ... WHERE condition
SELECT ... FROM ... WHERE condition GROUPBY field
SELECT ... FROM ... WHERE condition GROUPBY field HAVING condition2
SELECT ... FROM ... WHERE condition ORDER BY field1, field2
SELECT ... FROM ... WHERE condition ORDER BY field1, field2 DESC
SELECT ... FROM ... WHERE condition LIMIT 10
SELECT DISTINCT field1 FROM ...
SELECT DISTINCT field1, field2 FROM ...

Select – Join

SELECT ... FROM t1 JOIN t2 ON t1.id1 = t2.id2 WHERE condition
SELECT ... FROM t1 LEFT JOIN t2 ON t1.id1 = t2.id2 WHERE condition
SELECT ... FROM t1 JOIN (t2 JOIN t3 ON ...) ON ...

Conditions

field1 = value1
field1 <> value1
field1 LIKE 'value _ %'
field1 IS NULL
field1 IS NOT NULL
field1 IS IN (value1, value2)
field1 IS NOT IN (value1, value2)
condition1 AND condition2
condition1 OR condition2

Insert

INSERT INTO table1 (field1, field2, ...) VALUES (value1, value2, ...)

Delete

DELETE FROM table1 / TRUNCATE table1
DELETE FROM table1 WHERE condition
DELETE FROM table1, table2 FROM table1, table2 WHERE table1.id1 =
  table2.id2 AND condition

Update

UPDATE table1 SET field1=new_value1 WHERE condition
UPDATE table1, table2 SET field1=new_value1, field2=new_value2, ... WHERE
  table1.id1 = table2.id2 AND condition

Create / Delete / Modify Table

Create

CREATE TABLE table (field1 type1, field2 type2, ...)
CREATE TABLE table (field1 type1, field2 type2, ..., INDEX (field))
CREATE TABLE table (field1 type1, field2 type2, ..., PRIMARY KEY (field1))
CREATE TABLE table (field1 type1, field2 type2, ..., PRIMARY KEY (field1,
field2))
CREATE TABLE table1 (fk_field1 type1, field2 type2, ...,
  FOREIGN KEY (fk_field1) REFERENCES table2 (t2_fieldA))
    [ON UPDATE|ON DELETE] [CASCADE|SET NULL]
CREATE TABLE table1 (fk_field1 type1, fk_field2 type2, ...,
 FOREIGN KEY (fk_field1, fk_field2) REFERENCES table2 (t2_fieldA, t2_fieldB))
CREATE TABLE table IF NOT EXISTS (...)
CREATE TEMPORARY TABLE table (...)

Drop

DROP TABLE table
DROP TABLE IF EXISTS table
DROP TABLE table1, table2, ...

Alter

ALTER TABLE table MODIFY field1 type1
ALTER TABLE table MODIFY field1 type1 NOT NULL ...
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 NOT NULL ...
ALTER TABLE table ALTER field1 SET DEFAULT ...
ALTER TABLE table ALTER field1 DROP DEFAULT
ALTER TABLE table ADD new_name_field1 type1
ALTER TABLE table ADD new_name_field1 type1 FIRST
ALTER TABLE table ADD new_name_field1 type1 AFTER another_field
ALTER TABLE table DROP field1
ALTER TABLE table ADD INDEX (field);

Change field order

ALTER TABLE table MODIFY field1 type1 FIRST
ALTER TABLE table MODIFY field1 type1 AFTER another_field
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 FIRST
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 AFTER
  another_field

Keys

CREATE TABLE table (..., PRIMARY KEY (field1, field2))
CREATE TABLE table (..., FOREIGN KEY (field1, field2) REFERENCES table2
(t2_field1, t2_field2))

Users and Privileges

GRANT ALL PRIVILEGES ON base.* TO 'user'@'localhost' IDENTIFIED BY 'password';
GRANT SELECT, INSERT, DELETE ON base.* TO 'user'@'localhost' IDENTIFIED BY 'password';
REVOKE ALL PRIVILEGES ON base.* FROM 'user'@'host'; -- one permission only
REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'user'@'host'; -- all permissions
SET PASSWORD = PASSWORD('new_pass')
SET PASSWORD FOR 'user'@'host' = PASSWORD('new_pass')
SET PASSWORD = OLD_PASSWORD('new_pass')
DROP USER 'user'@'host'

Host ‘%’ indicates any host.

Main Data Types

TINYINT (1o: -217+128)
SMALLINT (2o: +-65 000)
MEDIUMINT (3o: +-16 000 000)
INT (4o: +- 2 000 000 000)
BIGINT (8o: +-9.10^18)
Precise interval: -(2^(8*N-1)) -> (2^8*N)-1

⚠ INT(2) = “2 digits displayed” – NOT “number with 2 digits max”

FLOAT(M,D)
DOUBLE(M,D)
FLOAT(D=0->53)

⚠ 8,3 -> 12345,678 – NOT 12345678,123!

TIME (HH:MM)
YEAR (AAAA)
DATE (AAAA-MM-JJ)
DATETIME (AAAA-MM-JJ HH:MM; années 1000->9999)
TIMESTAMP (like DATETIME, but 1970->2038, compatible with Unix)
VARCHAR (single-line; explicit size)
TEXT (multi-lines; max size=65535)
BLOB (binary; max size=65535)

Variants for TEXT&BLOB: TINY (max=255), MEDIUM (max=~16000), and LONG (max=4Go). Ex: VARCHAR(32)TINYTEXTLONGBLOBMEDIUMTEXT

ENUM ('value1', 'value2', ...) -- (default NULL, or '' if NOT NULL)

Reset Root Password

$ /etc/init.d/mysql stop
$ mysqld_safe --skip-grant-tables
$ mysql # on another terminal
mysql> UPDATE mysql.user SET password=PASSWORD('new_pass') WHERE user='root';
## Switch back to the mysqld_safe terminal and kill the process using Control + \
$ /etc/init.d/mysql start

Your commands may vary depending on your OS.

Find cheatsheet

Usage

find <path> <conditions> <actions>

Conditions

-name "*.c"
-user jonathan
-nouser
-type f            # File
-type d            # Directory
-type l            # Symlink
-depth 2           # At least 3 levels deep
-regex PATTERN
-size 8            # Exactly 8 512-bit blocks 
-size -128c        # Smaller than 128 bytes
-size 1440k        # Exactly 1440KiB
-size +10M         # Larger than 10MiB
-size +2G          # Larger than 2GiB
-newer   file.txt
-newerm  file.txt        # modified newer than file.txt
-newerX  file.txt        # [c]hange, [m]odified, [B]create
-newerXt "1 hour ago"    # [t]imestamp

Access time conditions

-atime 0           # Last accessed between now and 24 hours ago
-atime +0          # Accessed more than 24 hours ago
-atime 1           # Accessed between 24 and 48 hours ago
-atime +1          # Accessed more than 48 hours ago
-atime -1          # Accessed less than 24 hours ago (same a 0)
-ctime -6h30m      # File status changed within the last 6 hours and 30 minutes
-mtime +1w         # Last modified more than 1 week ago

These conditions only work in MacOS and BSD-like systems (no GNU/Linux support).

Condition flow

\! -name "*.c"
\( x -or y \)

Actions

-exec rm {} \;
-print
-delete

Examples

find . -name '*.jpg'
find . -name '*.jpg' -exec rm {} \;
find . -newerBt "24 hours ago"
find . -type f -mtime +29 # find files modified more than 30 days ago

regexp cheatsheet

Character classes

.Any character, except newline
\wWord
\dDigit
\sWhitespace
\WNot word
\DNot digit
\SNot whitespace
[abc]Any of a, b, or c
[a-e]Characters between a and e
[1-9]Digit between 1 and 9
[^abc]Any character except ab or c

Anchors

^abcStart with abc
abc$End with abc

Escaped characters

\. \* \\Escape special character used by regex
\tTab
\nNewline
\rCarriage return

Groups

(abc)Capture group

Quantifiers

a*Match 0 or more
a+Match 1 or more
a?Match 0 or 1
a{5}Match exactly 5
a{,3}Match up to 3
a{3,}Match 3 or more
a{1,3}Match between 1 and 3

React.js cheatsheet

React is a JavaScript library for building user interfaces. These guide targets React v15 to v16

#Components

Components

<span class="token keyword">import</span> React <span class="token keyword">from</span> <span class="token string">'react'</span>
<span class="token keyword">import</span> ReactDOM <span class="token keyword">from</span> <span class="token string">'react-dom'</span>
<span class="token keyword">class</span> <span class="token class-name">Hello</span> <span class="token keyword">extends</span> <span class="token class-name">React<span class="token punctuation">.</span>Component</span> <span class="token punctuation">{</span>
  render <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>div</span> <span class="token attr-name">className</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">'</span>message-box<span class="token punctuation">'</span></span><span class="token punctuation">></span></span>
      Hello <span class="token punctuation">{</span><span class="token keyword">this</span><span class="token punctuation">.</span>props<span class="token punctuation">.</span>name<span class="token punctuation">}</span>
    <span class="token tag"><span class="token tag"><span class="token punctuation"></</span>div</span><span class="token punctuation">></span></span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">const</span> el <span class="token operator">=</span> document<span class="token punctuation">.</span>body
ReactDOM<span class="token punctuation">.</span><span class="token function">render</span><span class="token punctuation">(</span><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Hello</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">'</span>John<span class="token punctuation">'</span></span> <span class="token punctuation">/></span></span><span class="token punctuation">,</span> el<span class="token punctuation">)</span>

Use the React.js jsfiddle to start hacking. (or the unofficial jsbin)

Import multiple exports

<span class="token keyword">import</span> React<span class="token punctuation">,</span> <span class="token punctuation">{</span>Component<span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'react'</span>
<span class="token keyword">import</span> ReactDOM <span class="token keyword">from</span> <span class="token string">'react-dom'</span>
<span class="token keyword">class</span> <span class="token class-name">Hello</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span>
  <span class="token operator">...</span>
<span class="token punctuation">}</span>

Properties

<span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Video</span> <span class="token attr-name">fullscreen</span><span class="token attr-value"><span class="token punctuation">=</span>{true}</span> <span class="token attr-name">autoplay</span><span class="token attr-value"><span class="token punctuation">=</span>{false}</span> <span class="token punctuation">/></span></span>
render () {
  this.props.fullscreen
  const { fullscreen, autoplay } = this.props
  ···
}
 
 

Use this.props to access properties passed to the component.

See: Properties

States

<span class="token function">constructor</span><span class="token punctuation">(</span>props<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">super</span><span class="token punctuation">(</span>props<span class="token punctuation">)</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>state <span class="token operator">=</span> <span class="token punctuation">{</span> username<span class="token punctuation">:</span> undefined <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">setState</span><span class="token punctuation">(</span><span class="token punctuation">{</span> username<span class="token punctuation">:</span> <span class="token string">'rstacruz'</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
render () {
  this.state.username
  const { username } = this.state
  ···
}
 
 

Use states (this.state) to manage dynamic data.

With Babel you can use proposal-class-fields and get rid of constructor

<span class="token keyword">class</span> <span class="token class-name">Hello</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span>
  state <span class="token operator">=</span> <span class="token punctuation">{</span> username<span class="token punctuation">:</span> undefined <span class="token punctuation">}</span><span class="token punctuation">;</span>
  <span class="token operator">...</span>
<span class="token punctuation">}</span>

See: States

Nesting

<span class="token keyword">class</span> <span class="token class-name">Info</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span>
  render <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> <span class="token punctuation">{</span> avatar<span class="token punctuation">,</span> username <span class="token punctuation">}</span> <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>props

    <span class="token keyword">return</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>div</span><span class="token punctuation">></span></span>
      <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>UserAvatar</span> <span class="token attr-name">src</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span>avatar<span class="token punctuation">}</span></span> <span class="token punctuation">/></span></span>
      <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>UserProfile</span> <span class="token attr-name">username</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span>username<span class="token punctuation">}</span></span> <span class="token punctuation">/></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation"></</span>div</span><span class="token punctuation">></span></span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

As of React v16.2.0, fragments can be used to return multiple children without adding extra wrapping nodes to the DOM.

<span class="token keyword">import</span> React<span class="token punctuation">,</span> <span class="token punctuation">{</span>
  Component<span class="token punctuation">,</span>
  Fragment
<span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'react'</span>

<span class="token keyword">class</span> <span class="token class-name">Info</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span>
  render <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> <span class="token punctuation">{</span> avatar<span class="token punctuation">,</span> username <span class="token punctuation">}</span> <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>props

    <span class="token keyword">return</span> <span class="token punctuation">(</span>
      <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Fragment</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>UserAvatar</span> <span class="token attr-name">src</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span>avatar<span class="token punctuation">}</span></span> <span class="token punctuation">/></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>UserProfile</span> <span class="token attr-name">username</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span>username<span class="token punctuation">}</span></span> <span class="token punctuation">/></span></span>
      <span class="token tag"><span class="token tag"><span class="token punctuation"></</span>Fragment</span><span class="token punctuation">></span></span>
    <span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

Nest components to separate concerns.

See: Composing Components

Children

<AlertBox>
  <h1>You have pending notifications</h1>
</AlertBox>
 
class AlertBox extends Component {
  render () {
    return <div className='alert-box'>
      {this.props.children}
    </div>
  }
}
 

Children are passed as the children property.

#Defaults

Setting default props

Hello.defaultProps = {
  color: 'blue'
}
 

See: defaultProps

Setting default state

class Hello extends Component {
  constructor (props) {
    super(props)
    this.state = { visible: true }
  }
}
 

Set the default state in the constructor().

And without constructor using Babel with proposal-class-fields.

<span class="token keyword">class</span> <span class="token class-name">Hello</span> <span class="token keyword">extends</span> <span class="token class-name">Component</span> <span class="token punctuation">{</span>
    state <span class="token operator">=</span> <span class="token punctuation">{</span> visible<span class="token punctuation">:</span> <span class="token boolean">true</span> <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

See: Setting the default state

#Other components

Functional components

function MyComponent ({ name }) {
  return <div className='message-box'>
    Hello {name}
  </div>
}
 

Functional components have no state. Also, their props are passed as the first parameter to a function.

See: Function and Class Components

Pure components

import React, {PureComponent} from 'react'

class MessageBox extends PureComponent {
  ···
}
 

Performance-optimized version of React.Component. Doesn’t rerender if props/state hasn’t changed.

See: Pure components

Component API

<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">forceUpdate</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">setState</span><span class="token punctuation">(</span><span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">setState</span><span class="token punctuation">(</span>state <span class="token operator">=></span> <span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">this</span><span class="token punctuation">.</span>state
<span class="token keyword">this</span><span class="token punctuation">.</span>props

These methods and properties are available for Component instances.

See: Component API

#Lifecycle

Mounting

MethodDescription
constructor (props)Before rendering #
componentWillMount()Don’t use this #
render()Render #
componentDidMount()After rendering (DOM available) #
componentWillUnmount()Before DOM removal #
componentDidCatch()Catch errors (16+) #

Set initial the state on constructor(). Add DOM event handlers, timers (etc) on componentDidMount(), then remove them on componentWillUnmount().

Updating

MethodDescription
componentDidUpdate (prevProps, prevState, snapshot)Use setState() here, but remember to compare props
shouldComponentUpdate (newProps, newState)Skips render() if returns false
render()Render
componentDidUpdate (prevProps, prevState)Operate on the DOM here

Called when parents change properties and .setState(). These are not called for initial renders.

See: Component specs

#DOM nodes

References

class MyComponent extends Component {
  render () {
    return <div>
      <input ref={el => this.input = el} />
    </div>
  }

  componentDidMount () {
    this.input.focus()
  }
}
 
 

Allows access to DOM nodes.

See: Refs and the DOM

DOM Events

class MyComponent extends Component {
  render () {
    <input type="text"
        value={this.state.value}
        onChange={event => this.onChange(event)} />
  }

  onChange (event) {
    this.setState({ value: event.target.value })
  }
}
 
 

Pass functions to attributes like onChange.

See: Events

#Other features

Transferring props

<span class="token tag"><span class="token tag"><span class="token punctuation"><</span>VideoPlayer</span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>video.mp4<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
class VideoPlayer extends Component {
  render () {
    return <VideoEmbed {...this.props} />
  }
}
 

Propagates src="..." down to the sub-component.

See Transferring props

Top-level API

React<span class="token punctuation">.</span><span class="token function">createClass</span><span class="token punctuation">(</span><span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
React<span class="token punctuation">.</span><span class="token function">isValidElement</span><span class="token punctuation">(</span>c<span class="token punctuation">)</span>
ReactDOM<span class="token punctuation">.</span><span class="token function">render</span><span class="token punctuation">(</span><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Component</span> <span class="token punctuation">/></span></span><span class="token punctuation">,</span> domnode<span class="token punctuation">,</span> <span class="token punctuation">[</span>callback<span class="token punctuation">]</span><span class="token punctuation">)</span>
ReactDOM<span class="token punctuation">.</span><span class="token function">unmountComponentAtNode</span><span class="token punctuation">(</span>domnode<span class="token punctuation">)</span>
ReactDOMServer<span class="token punctuation">.</span><span class="token function">renderToString</span><span class="token punctuation">(</span><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Component</span> <span class="token punctuation">/></span></span><span class="token punctuation">)</span>
ReactDOMServer<span class="token punctuation">.</span><span class="token function">renderToStaticMarkup</span><span class="token punctuation">(</span><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Component</span> <span class="token punctuation">/></span></span><span class="token punctuation">)</span>

There are more, but these are most common.

See: React top-level API

#JSX patterns

Style shorthand

<span class="token keyword">const</span> style <span class="token operator">=</span> <span class="token punctuation">{</span> height<span class="token punctuation">:</span> <span class="token number">10</span> <span class="token punctuation">}</span>
<span class="token keyword">return</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>div</span> <span class="token attr-name">style</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span>style<span class="token punctuation">}</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation"></</span>div</span><span class="token punctuation">></span></span>
<span class="token keyword">return</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>div</span> <span class="token attr-name">style</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span><span class="token punctuation">{</span> margin<span class="token punctuation">:</span> <span class="token number">0</span><span class="token punctuation">,</span> padding<span class="token punctuation">:</span> <span class="token number">0</span> <span class="token punctuation">}</span><span class="token punctuation">}</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation"></</span>div</span><span class="token punctuation">></span></span>

See: Inline styles

Inner HTML

<span class="token keyword">function</span> <span class="token function">markdownify</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token keyword">return</span> <span class="token string">"<p>...</p>"</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
<span class="token tag"><span class="token tag"><span class="token punctuation"><</span>div</span> <span class="token attr-name">dangerouslySetInnerHTML</span><span class="token script language-javascript"><span class="token punctuation">=</span><span class="token punctuation">{</span><span class="token punctuation">{</span>__html<span class="token punctuation">:</span> <span class="token function">markdownify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">}</span><span class="token punctuation">}</span></span> <span class="token punctuation">/></span></span>

See: Dangerously set innerHTML

Lists

class TodoList extends Component {
  render () {
    const { items } = this.props

    return <ul>
      {items.map(item =>
        <TodoItem item={item} key={item.key} />)}
    </ul>
  }
}
 
 

Always supply a key property.

Conditionals

<span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Fragment</span><span class="token punctuation">></span></span>
  <span class="token punctuation">{</span>showMyComponent
    <span class="token operator">?</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>MyComponent</span> <span class="token punctuation">/></span></span>
    <span class="token punctuation">:</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>OtherComponent</span> <span class="token punctuation">/></span></span><span class="token punctuation">}</span>
<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>Fragment</span><span class="token punctuation">></span></span>

Short-circuit evaluation

<span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Fragment</span><span class="token punctuation">></span></span>
  <span class="token punctuation">{</span>showPopup <span class="token operator">&&</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><</span>Popup</span> <span class="token punctuation">/></span></span><span class="token punctuation">}</span>
  <span class="token operator">...</span>
<span class="token tag"><span class="token tag"><span class="token punctuation"></</span>Fragment</span><span class="token punctuation">></span></span>

#New features

Returning multiple elements

You can return multiple elements as arrays or fragments.

Arrays

render () {
  // Don't forget the keys!
  return [
    <li key="A">First item</li>,
    <li key="B">Second item</li>
  ]
}
 
 
 
 

Fragments

render () {
  // Fragments don't require keys!
  return (
    <Fragment>
      <li>First item</li>
      <li>Second item</li>
    </Fragment>
  )
}
 
 
 
 
 
 

See: Fragments and strings

Returning strings

render() {
  return 'Look ma, no spans!';
}
 

You can return just a string.

See: Fragments and strings

Errors

class MyComponent extends Component {
  ···
  componentDidCatch (error, info) {
    this.setState({ error })
  }
}
 
 
 

Catch errors via componentDidCatch. (React 16+)

See: Error handling in React 16

Portals

render () {
  return React.createPortal(
    this.props.children,
    document.getElementById('menu')
  )
}
 
 
 
 

This renders this.props.children into any location in the DOM.

See: Portals

Hydration

const el = document.getElementById('app')
ReactDOM.hydrate(<App />, el)
 

Use ReactDOM.hydrate instead of using ReactDOM.render if you’re rendering over the output of ReactDOMServer.

See: Hydrate

#Property validation

PropTypes

<span class="token keyword">import</span> PropTypes <span class="token keyword">from</span> <span class="token string">'prop-types'</span>

See: Typechecking with PropTypes

anyAnything

Basic

string 
number 
funcFunction
boolTrue or false

Enum

oneOf(any)Enum types
oneOfType(type array)Union

Array

array 
arrayOf(…) 

Object

object 
objectOf(…)Object with values of a certain type
instanceOf(…)Instance of a class
shape(…) 

Elements

elementReact element
nodeDOM node

Required

(···).isRequiredRequired

Basic types

MyComponent<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  email<span class="token punctuation">:</span>      PropTypes<span class="token punctuation">.</span>string<span class="token punctuation">,</span>
  seats<span class="token punctuation">:</span>      PropTypes<span class="token punctuation">.</span>number<span class="token punctuation">,</span>
  callback<span class="token punctuation">:</span>   PropTypes<span class="token punctuation">.</span>func<span class="token punctuation">,</span>
  isClosed<span class="token punctuation">:</span>   PropTypes<span class="token punctuation">.</span>bool<span class="token punctuation">,</span>
  any<span class="token punctuation">:</span>        PropTypes<span class="token punctuation">.</span>any
<span class="token punctuation">}</span>

Required types

MyCo<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  name<span class="token punctuation">:</span>  PropTypes<span class="token punctuation">.</span>string<span class="token punctuation">.</span>isRequired
<span class="token punctuation">}</span>

Elements

MyCo<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  <span class="token comment" spellcheck="true">// React element</span>
  element<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span>element<span class="token punctuation">,</span>

  <span class="token comment" spellcheck="true">// num, string, element, or an array of those</span>
  node<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span>node
<span class="token punctuation">}</span>

Enumerables (oneOf)

MyCo<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  direction<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span><span class="token function">oneOf</span><span class="token punctuation">(</span><span class="token punctuation">[</span>
    <span class="token string">'left'</span><span class="token punctuation">,</span> <span class="token string">'right'</span>
  <span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

Arrays and objects

MyCo<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  list<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span>array<span class="token punctuation">,</span>
  ages<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span><span class="token function">arrayOf</span><span class="token punctuation">(</span>PropTypes<span class="token punctuation">.</span>number<span class="token punctuation">)</span><span class="token punctuation">,</span>
  user<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span>object<span class="token punctuation">,</span>
  user<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span><span class="token function">objectOf</span><span class="token punctuation">(</span>PropTypes<span class="token punctuation">.</span>number<span class="token punctuation">)</span><span class="token punctuation">,</span>
  message<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span><span class="token function">instanceOf</span><span class="token punctuation">(</span>Message<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
MyCo<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  user<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span><span class="token function">shape</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    name<span class="token punctuation">:</span> PropTypes<span class="token punctuation">.</span>string<span class="token punctuation">,</span>
    age<span class="token punctuation">:</span>  PropTypes<span class="token punctuation">.</span>number
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

Use .array[Of], .object[Of], .instanceOf, .shape.

Custom validation

MyCo<span class="token punctuation">.</span>propTypes <span class="token operator">=</span> <span class="token punctuation">{</span>
  customProp<span class="token punctuation">:</span> <span class="token punctuation">(</span>props<span class="token punctuation">,</span> key<span class="token punctuation">,</span> componentName<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token regex">/matchme/</span><span class="token punctuation">.</span><span class="token function">test</span><span class="token punctuation">(</span>props<span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Error</span><span class="token punctuation">(</span><span class="token string">'Validation failed!'</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

#Also see

ES2015+ cheatsheet

ES2015+ cheatsheet is A quick overview of new JavaScript features in ES2015, ES2016, ES2017, ES2018 and beyond.

Block scoping

Let

function fn () {
  let x = 0
  if (true) {
    let x = 1 // only inside this `if`
  }
}
 
 

Const

<span class="token keyword">const</span> a <span class="token operator">=</span> <span class="token number">1</span>

let is the new var. Constants work just like let, but can’t be reassigned. See: Let and const

Backtick strings

Interpolation

<span class="token keyword">const</span> message <span class="token operator">=</span> <span class="token template-string"><span class="token string">`Hello </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>name<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">`</span></span>

Multiline strings

<span class="token keyword">const</span> str <span class="token operator">=</span> <span class="token template-string"><span class="token string">`
hello
world
`</span></span>

Templates and multiline strings. See: Template strings

Binary and octal literals

<span class="token keyword">let</span> bin <span class="token operator">=</span> <span class="token number">0b1010010</span>
<span class="token keyword">let</span> oct <span class="token operator">=</span> <span class="token number">0o755</span>

See: Binary and octal literals

New methods

New string methods

<span class="token string">"hello"</span><span class="token punctuation">.</span><span class="token function">repeat</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>
<span class="token string">"hello"</span><span class="token punctuation">.</span><span class="token function">includes</span><span class="token punctuation">(</span><span class="token string">"ll"</span><span class="token punctuation">)</span>
<span class="token string">"hello"</span><span class="token punctuation">.</span><span class="token function">startsWith</span><span class="token punctuation">(</span><span class="token string">"he"</span><span class="token punctuation">)</span>
<span class="token string">"hello"</span><span class="token punctuation">.</span><span class="token function">padStart</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// "   hello"</span>
<span class="token string">"hello"</span><span class="token punctuation">.</span><span class="token function">padEnd</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// "hello   " </span>
<span class="token string">"hello"</span><span class="token punctuation">.</span><span class="token function">padEnd</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">,</span> <span class="token string">'!'</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// hello!!!</span>
<span class="token string">"\u1E9B\u0323"</span><span class="token punctuation">.</span><span class="token function">normalize</span><span class="token punctuation">(</span><span class="token string">"NFC"</span><span class="token punctuation">)</span>

See: New methods

Classes

<span class="token keyword">class</span> <span class="token class-name">Circle</span> <span class="token keyword">extends</span> <span class="token class-name">Shape</span> <span class="token punctuation">{</span>

Constructor

  constructor (radius) {
    this.radius = radius
  }
 

Methods

  getArea () {
    return Math.PI * 2 * this.radius
  }
 

Calling superclass methods

  expand (n) {
    return super.expand(n) * Math.PI
  }
 

Static methods

  static createFromDiameter(diameter) {
    return new Circle(diameter / 2)
  }
}
 

Syntactic sugar for prototypes. See: Classes

Exponent operator

const byte = 2 ** 8
// Same as: Math.pow(2, 8)
 

#Promises

Making promises

new Promise((resolve, reject) => {
  if (ok) { resolve(result) }
  else { reject(error) }
})
 

For asynchronous programming. See: Promises

Using promises

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
 
 

Using promises with finally

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
  .finally(() => { // logic independent of success/error })
 

The handler is called when the promise is fulfilled or rejected.

Promise functions

Promise<span class="token punctuation">.</span><span class="token function">all</span><span class="token punctuation">(</span>···<span class="token punctuation">)</span>
Promise<span class="token punctuation">.</span><span class="token function">race</span><span class="token punctuation">(</span>···<span class="token punctuation">)</span>
Promise<span class="token punctuation">.</span><span class="token function">reject</span><span class="token punctuation">(</span>···<span class="token punctuation">)</span>
Promise<span class="token punctuation">.</span><span class="token function">resolve</span><span class="token punctuation">(</span>···<span class="token punctuation">)</span>

Async-await

async function run () {
  const user = await getUser()
  const tweets = await getTweets(user)
  return [user, tweets]
}
 
 

async functions are another way of using functions.

See: async function

#Destructuring

Destructuring assignment

Arrays

const [first, last] = ['Nikola', 'Tesla']
 

Objects

let {title, author} = {
  title: 'The Silkworm',
  author: 'R. Galbraith'
}
 

Supports for matching arrays and objects. See: Destructuring

Default values

<span class="token keyword">const</span> scores <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">22</span><span class="token punctuation">,</span> <span class="token number">33</span><span class="token punctuation">]</span>
<span class="token keyword">const</span> <span class="token punctuation">[</span>math <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">,</span> sci <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">,</span> arts <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">]</span> <span class="token operator">=</span> scores
<span class="token comment" spellcheck="true">// Result:</span>
<span class="token comment" spellcheck="true">// math === 22, sci === 33, arts === 50</span>

Default values can be assigned while destructuring arrays or objects.

Function arguments

function greet({ name, greeting }) {
  console.log(`${greeting}, ${name}!`)
}
 
<span class="token function">greet</span><span class="token punctuation">(</span><span class="token punctuation">{</span> name<span class="token punctuation">:</span> <span class="token string">'Larry'</span><span class="token punctuation">,</span> greeting<span class="token punctuation">:</span> <span class="token string">'Ahoy'</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>

Destructuring of objects and arrays can be also be done in function arguments.

Default values

function greet({ name = 'Rauno' } = {}) {
  console.log(`Hi ${name}!`);
}
 
<span class="token function">greet</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// Hi Rauno!</span>
<span class="token function">greet</span><span class="token punctuation">(</span><span class="token punctuation">{</span> name<span class="token punctuation">:</span> <span class="token string">'Larry'</span> <span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// Hi Larry!</span>

Reassigning keys

function printCoordinates({ left: x, top: y }) {
  console.log(`x: ${x}, y: ${y}`)
}
 
<span class="token function">printCoordinates</span><span class="token punctuation">(</span><span class="token punctuation">{</span> left<span class="token punctuation">:</span> <span class="token number">25</span><span class="token punctuation">,</span> top<span class="token punctuation">:</span> <span class="token number">90</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>

This example assigns x to the value of the left key.

Loops

for (let {title, artist} of songs) {
  ···
}
 

The assignment expressions work in loops, too.

Object destructuring

const { id, ...detail } = song;
 

Extract some keys individually and remaining keys in the object using rest (…) operator

#Spread

Object spread

with Object spread

const options = {
  ...defaults,
  visible: true
}
 

without Object spread

<span class="token keyword">const</span> options <span class="token operator">=</span> Object<span class="token punctuation">.</span><span class="token function">assign</span><span class="token punctuation">(</span>
  <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">,</span> defaults<span class="token punctuation">,</span>
  <span class="token punctuation">{</span> visible<span class="token punctuation">:</span> <span class="token boolean">true</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>

The Object spread operator lets you build new objects from other objects.

See: Object spread

Array spread

with Array spread

const users = [
  ...admins,
  ...editors,
  'rstacruz'
]
 
 

without Array spread

<span class="token keyword">const</span> users <span class="token operator">=</span> admins
  <span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span>editors<span class="token punctuation">)</span>
  <span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span><span class="token punctuation">[</span> <span class="token string">'rstacruz'</span> <span class="token punctuation">]</span><span class="token punctuation">)</span>

The spread operator lets you build new arrays in the same way.

See: Spread operator

#Functions

Function arguments

Default arguments

function greet (name = 'Jerry') {
  return `Hello ${name}`
}
 

Rest arguments

function fn(x, ...y) {
  // y is an Array
  return x * y.length
}
 

Spread

fn(...[1, 2, 3])
// same as fn(1, 2, 3)
 

Default, rest, spread. See: Function arguments

Fat arrows

Fat arrows

setTimeout(() => {
  ···
})
 

With arguments

readFile('text.txt', (err, data) => {
  ...
})
 

Implicit return

numbers.map(n => n * 2)
// No curly braces = implicit return
// Same as: numbers.map(function (n) { return n * 2 })
numbers.map(n => ({
  result: n * 2
})
// Implicitly returning objects requires parentheses around the object
 
 
 
 

Like functions but with this preserved. See: Fat arrows

#Objects

Shorthand syntax

module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span> hello<span class="token punctuation">,</span> bye <span class="token punctuation">}</span>
<span class="token comment" spellcheck="true">// Same as: module.exports = { hello: hello, bye: bye }</span>

See: Object literal enhancements

Methods

const App = {
  start () {
    console.log('running')
  }
}
// Same as: App = { start: function () {···} }
 

See: Object literal enhancements

Getters and setters

const App = {
  get closed () {
    return this.status === 'closed'
  },
  set closed (value) {
    this.status = value ? 'closed' : 'open'
  }
}
 
 

See: Object literal enhancements

Computed property names

let event = 'click'
let handlers = {
  [`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }
 

See: Object literal enhancements

Extract values

<span class="token keyword">const</span> fatherJS <span class="token operator">=</span> <span class="token punctuation">{</span> age<span class="token punctuation">:</span> <span class="token number">57</span><span class="token punctuation">,</span> name<span class="token punctuation">:</span> <span class="token string">"Brendan Eich"</span> <span class="token punctuation">}</span>

Object<span class="token punctuation">.</span><span class="token function">values</span><span class="token punctuation">(</span>fatherJS<span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">// [57, "Brendan Eich"]</span>
Object<span class="token punctuation">.</span><span class="token function">entries</span><span class="token punctuation">(</span>fatherJS<span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">// [["age", 57], ["name", "Brendan Eich"]]</span>

#Modules

Imports

<span class="token keyword">import</span> <span class="token string">'helpers'</span>
<span class="token comment" spellcheck="true">// aka: require('···')</span>
<span class="token keyword">import</span> Express <span class="token keyword">from</span> <span class="token string">'express'</span>
<span class="token comment" spellcheck="true">// aka: const Express = require('···').default || require('···')</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span> indent <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'helpers'</span>
<span class="token comment" spellcheck="true">// aka: const indent = require('···').indent</span>
<span class="token keyword">import</span> <span class="token operator">*</span> <span class="token keyword">as</span> Helpers <span class="token keyword">from</span> <span class="token string">'helpers'</span>
<span class="token comment" spellcheck="true">// aka: const Helpers = require('···')</span>
<span class="token keyword">import</span> <span class="token punctuation">{</span> indentSpaces <span class="token keyword">as</span> indent <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'helpers'</span>
<span class="token comment" spellcheck="true">// aka: const indent = require('···').indentSpaces</span>

import is the new require(). See: Module imports

Exports

<span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> ··· <span class="token punctuation">}</span>
<span class="token comment" spellcheck="true">// aka: module.exports.default = ···</span>
<span class="token keyword">export</span> <span class="token keyword">function</span> mymethod <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> ··· <span class="token punctuation">}</span>
<span class="token comment" spellcheck="true">// aka: module.exports.mymethod = ···</span>
<span class="token keyword">export</span> <span class="token keyword">const</span> pi <span class="token operator">=</span> <span class="token number">3.14159</span>
<span class="token comment" spellcheck="true">// aka: module.exports.pi = ···</span>

export is the new module.exports. See: Module exports

#Generators

Generators

<span class="token keyword">function</span><span class="token operator">*</span> idMaker <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">let</span> id <span class="token operator">=</span> <span class="token number">0</span>
  <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token keyword">yield</span> id<span class="token operator">++</span> <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">let</span> gen <span class="token operator">=</span> <span class="token function">idMaker</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
gen<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>value  <span class="token comment" spellcheck="true">// → 0</span>
gen<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>value  <span class="token comment" spellcheck="true">// → 1</span>
gen<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>value  <span class="token comment" spellcheck="true">// → 2</span>

It’s complicated. See: Generators

For..of iteration

<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token keyword">of</span> iterable<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  ···
<span class="token punctuation">}</span>