javascript statement completion value

We all know how painful it is to write long and tedious cloud formation json templates. Cloudform is a nice little library to write cloud formation template in typescript and will compile it into json. Its types are all from amazon’s own library so it is easy to keep up to date without the maintainer having to write new code to support the new aws features.

As I was reading the source code of cloudform compiler where it eventually emit the cloud formation template via a eval() function, i was kind of confused how it works. As i dig deeper, find an interesting concept in js that I never heard of: statement completion value.

To test that, i did some test on the node cli:

const s0 = 'const f1 = ()=>1;';
const s1 = 'const f1 = ()=>1; f1();';
const s2 = 'const f1 = ()=>1; f2 = ()=>2; f1(); f2()';
const s3 = 'const f1 = ()=>1; f1(); "2"';

// output undefined
console.log(eval(s0));
// output 1
console.log(eval(s1));
// output 2
console.log(eval(s2));
// output 2
console.log(eval(s3));

So this means, it always take the last valid return value.

Another note is IIFE can also return value as long as you have return statement. And async is not well supported as the eval is executed synchronously, so logic executed in other ticks will not get a chance to return unless we do some monkey patching with async/await.

interesting reference on question by Paul Irish on Twitter on 01/2017 and answered by Brendan Eich: HERE

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s