Clarification on function default param values

Brandon Benvie bbenvie at mozilla.com
Mon Sep 30 20:21:50 PDT 2013


On 9/30/2013 3:51 PM, Dmitry Soshnikov wrote:
> Just re-read meeting notes, OK, cool on two scopes (seems like they 
> are not in the spec yet). Want to double-check though: whether it will 
> be possible to transpile now to ES3? From what I've seen in the notes, 
> the head-scope will be able to access `this` value of the activation, 
> etc. Not sure how to transpile now. Could someone give an example of a 
> wrapper scope please, and confirm whether it's transpilable now?

I believe it is transpilable if you use an inner function scope. Someone 
correct me if my translations are semantically incorrect:


ES6:
```js
var x = 1, y = 2;
function foo(x = 3, y = y, z = y) {
   return [x, y, z];
}
```

ES3:
```js
var x = 1, y = 2;
function foo(x, y, z) {
   // defaults
   if (x === undefined) {
     x = 3;
   }
   if (y === undefined) {
     y = y; // essentially a no-op
   }
   if (z === undefined) {
     z = y;
   }

   // body
   return (function(x, y, z){
     return [x, y, z];
   }).call(this, x, y, z);
}
```


ES6:
```js
var x = 1, y=2;
function foo(x=3, y= (x = undefined, 4)) {
   return [x,y];
}
```

ES3:
```js
var x = 1, y=2;
function foo(x, y) {
   // defaults
   if (x === undefined) {
     x = 3;
   }
   if (y === undefined) {
     y = (x = undefined, 4);
   }

   // body
   return (function(x, y) {
     return [x, y];
   }).call(this, x, y);
}
```


ES6:
```js
function foo(bar = function() { return 'param-inner' }) {
   var ret = bar();
   function bar() {
     return 'body-inner';
   }
   return ret;
}
```

ES3:
function foo(bar) {
   // defaults
   if (bar === undefined) {
     bar = function() { return 'param-inner'; };
   }

   // body
   return (function(bar){
     var ret = bar();
     function bar() {
       return 'body-inner';
     }
     return ret;
   }).call(this, bar);
}




A clearer example of my own which I think demonstrates the scoping 
better (or exposes a problem with my understanding):

ES6
```js
function foo(x, y = function() { return x }) {
   x++;
   return x + y();
}

foo(1); // is this 3 or 4?
```

ES3:
```js
function foo(x, y) {
   // defaults
   if (y === undefined) {
     y = function() { return x };
   }

   // body
   return (function(x, y) {
     x++;
     return x + y();
   }).call(this, x, y);
}

foo(1); // 3
```


More information about the es-discuss mailing list