Search code examples
javascriptwebpackrolluptree-shaking

What do you call function that use stuff outside of the function and function that is self contained?


Dose this two function have a name or a term? I'm sure they do but don't know what to search for.

// edit: thanks to Bergi: 
// this is a function with `no free variables` (outer variables)

function add (a, b) { return a + b }

and

// edit: thanks to Bergi: 
// this is a function with `free variables` (b) if you didn't know that

var b = 2
function add (a) { return a + b }

Is it called something special if a function goes outside of its own scope? and what do you call the function that don't use anything outside of its own scope?


What I'm would like to explain to someone is if I where to write this utility file that exported two helper function

// util
function divide (a, b) {
  return a / b
}

function half (a) {
  return divide(a, 2)
}

export {
  divide,
  half
}

And then in another file I would only use the divide function

import { divide } from util

Then WebPack/rollup would be able to tree shake and discard the half function in the final bundle

But if where to import the half function from the utility file

import { half } from util

But don't really need the divide function in my main script I would end up having both function in my bundle anyway because half depends on divide

If I have would have changed the function to not use any variables outside of it's own scope like so:

function half (a) {
  return a / 2
}

then it would be "dependency" free.


Solution

  • Is it called something special if a function goes outside of its own scope?

    We call them closures. It has a free variable, which in JS is looked up lexically in the scope.

    However, while technically every function is a closure in JavaScript, this is probably not the term you want to use; most people associate it to dynamically created functions which would be weird for a module-level function.

    What do you call the function that don't use anything outside of its own scope?

    A "function without free variables" would fit.