bcherny - 1 year ago 28

Javascript Question

Eg. Say this is our JavaScript code:

`let a = x => {`

let y = x * 2

return z => x + y + z

}

let b = a(1)

let c = b(2)

Can I evaluate this using a substitution model, or do I need an environment model?

I began like so:

`let c = ((x => {`

let y = x * 2

return z => x + y + z

})(1))(2)

But then I would need to evaluate the inner expression (called with

`1`

`2`

Is this an indication that the substitution model is inadequate here? Or is it kosher to eval inside-out as well as outside-in? Or is there some other way to look at it?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

The substitution model works for closures. Basically you replace the bindings with their bound values. You don't need an environment model.

```
const b = a(1) // ==
const b = z => 1 + (1 * 2) + z
const c = b(2) // ==
const c = 1 + (1 * 2) + 2 // ==
const c = 5
```

It's only if you really need to use `let`

(in the event you actually rebind it) where you need an environment model.

When it comes to evalution order it's clear that in two calls like `a(1)(2)`

you cannot do the second call with the argument `2`

first since it is called on the result of `a(1)`

. Thus you need to know the result of `a(1)`

so you need to substitute that first, then do the next call on that result.

```
let c = (x => {
let y = x * 2
return z => x + y + z
})(1)(2)
// substituting 1 for x ==>
let c = (z => 1 + 2 + z)(2)
// substituting 2 for z ==>
let c = 1 + 2 + 2
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**