Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Last active June 27, 2017 22:52
Show Gist options
  • Select an option

  • Save rwaldron/5a3e51fb5e575f7ab4c1e4db9cc6a3ee to your computer and use it in GitHub Desktop.

Select an option

Save rwaldron/5a3e51fb5e575f7ab4c1e4db9cc6a3ee to your computer and use it in GitHub Desktop.

Original code:

var func = String.raw
`abc`.split('')
console.log(func); // ['a', 'b', 'c']

Modified to see what's happening:

var sraw = String.raw;

Object.defineProperty(String, "raw", {
  value: function(...args) {
    console.log(1, args);   
    return sraw(...args);
  }
});

var split = String.prototype.split; 

String.prototype.split = function(char) { 
  console.log(2, this, char); 
  return split.call(this, char); 
};

var func = String.raw
`abc`.split('')
console.log(3, func); // ['a', 'b', 'c']

Result:

1 [ [ 'abc' ] ]
2 [String: 'abc'] ''
3 [ 'a', 'b', 'c' ]
  1. String.raw`abc` is a member expression
  2. EvaluateCall is called with arguments: String.raw, `abc`, IsInTailPosition(String.raw).
  3. `abc` is parsed as a TL, specifically NoSubstitutionTemplate, and the result is an array containing a single TemplateCharacters entry, which is the string "abc".
  4. The call to String.raw receives the template object argument which contains the string "abc" (https://tc39.github.io/ecma262/#sec-tagged-templates), does what it does and returns the result, which in this case is a string "abc".
  5. The resulting string "abc" has its .split('') method called, producing an array of characters: ['a', 'b', 'c'] which is then assigned to const func;

Another way to look at it:

function noop(x) {
  return x;
}

const func = noop(`abc`).split('');

console.log(func); // [ 'a', 'b', 'c' ]
@rauschma

Copy link
Copy Markdown

Right. “ASI hazard” was the wrong description. I meant: a hazard for people who don’t use semicolons and expect ASI to kick in where it doesn’t.

In a way, the only real ASI hazard is ASI inserting a semicolon after return.

@rwaldron

Copy link
Copy Markdown
Author

I have no sympathy for that invalid use case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment