0%

const function

Function Statement

  • hoisted to the top of the full lexical scope
    • can break conflicting scripts
    • it’s difficult to debug
  • named function is shown in the stack trace
    • easier to debug when error occurs in the function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
Function declarations are given two passes,
where the first lifts them to the top (hoisting),
allowing "out of order" usage
*/


doTheThing();

function doTheThing() {
console.log(`This is awesome number ${getAwesome()}`)
}

function getAwesome() {
return (+((Math.random() * 10000).toString().split('.')[0]))
}

Const Declaration

  • edge-case hoisting
  • declare a variable
    • gives it a block scope
    • stops the full hoisting
  • cannot be re-declared
    • throws exception if re-declared
    • easier to debug
  • won’t be caught until called
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
This shows that, because of block-scoping,
const function references must be invoked in-order
or else things will fail silently.
consts are added serially (in the order in which they appear)
and much of the body isn't declared when we first try to invoke or functions
*/


// use `getAwesome()`
const tryDoTheThing = () => {
console.log(`This is me trying to be awesome ${getAwesome()}`)
}


// "getAwesome is not defined", because it is referenced too early,
// before declaring `getAwesome()` function
tryDoTheThing()


const getAwesome = () => (+((Math.random() * 10000).toString().split('.')[0]))


const doTheThing = () => {
console.log(`This is awesome! ${getAwesome()}`)
}

doTheThing()