JavaScript: Closures and the Call Stack

[λx.x(closure)] identity of a closure (sorry lambda calculus fun)

Review of Closures

// :: int -> int -> int
const incrementBy = function(n){
// :: int -> int
return function increment(x){
return n + x
}
}
const main = function() {     const incrementByOne = incrementBy(1)
// => int -> int
const eleven = incrementByOne(10)
// => 11
}
main()

Scoping Models

// global declaration of x set to an initial value 10 
int
x = 10;
// Called by g()
int f() {
return x;
}
// g() has its own variable named as x and calls f()
int g() {
int x = 20;
return f();
}
main() {
printf(g());
// => 10 or 20? ...well we need to know the scoping model
}

Activation Records (Stack Frames)

  • parameters,
  • locally defined variables,
  • pointer the result of the invocation and
  • the point in the program to return to
Example of an activation record (stack frame)

Finding the value of non-local variables

// :: (String, ActivationRecord) -> Object 
const getValue = function(variableName, activationRecord) {
if(activationRecord.variables[variableName]) { return activationRecord.variables[variableName] ; } return getValue(
variableName,
activationRecord.accessLink
) ;
}
  • look locally first, if the value is there return it
  • otherwise recurse looking

--

--

--

A 25 year software industry veteran with a passion for functional programming, architecture, mentoring / team development, xp/agile and doing the right thing.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

javascript30.com — Day 1: Learning and relearning vanillajs

How to Build Serverless Vue Applications with AWS Amplify

JavaScript ES6

7 Things I Wish I Knew When I Started Learning How to Code

How can you become a good programmer?

NodeJS on Android [Root]

https://medium.com/@2771254/list/a2058c8adbc0

Breadth First Search? JS Algos and DS for beginners.

Multiple cats — gray, black, tricolor, tabby, brown and white sit on a smooth bright gradient background. The cats are connected via same color arrow pointers horizontally to their siblings. They are also connected to their kittens via arrow pointers vertically but in a different color.

A new perspective on building the Web 😎 w/ PWA in React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Todd Brown

Todd Brown

A 25 year software industry veteran with a passion for functional programming, architecture, mentoring / team development, xp/agile and doing the right thing.

More from Medium

JS-07— JavaScript for Programmers, Chapter4to6, Summary, Part3

JavaScript Eğitimi - 1 / Değişkenler, Operatörler ve Kontrol Yapıları

ACOS: Build web games using serverless code, persistent JSON state, and any JS browser framework

Using esbuild with rails 7 in a simple way