Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
Can anybody explain what is going on here in terms of type coercion, IIFE, and closures?

can anyone explain to me what is JS doing here? Can anybody explain what is going on here in terms of type coercion, IIFE, and closures?

Function.prototype.toString = (
    function() {
      const toStringFnRef = Function.prototype.toString;
      
      return function() {
            return `start:${toStringFnRef.call(this)}end`;
        }
    }
)();

console.log(1 + function x() { alert('hi') });
//output: "1start:function x() { alert('hi') }end"
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The IIFE is being used to create a local scope where the variable toStringFnRef contains the original value of Function.prototype.toString. Then it redefines this with a function that calls the original function and wraps the result in start: and end.

This could also be done using a lexical block (in ES6 most IIFEs can be refactored like this):

{
  const toStringFnRef = Function.prototype.toString;

  Function.prototype.toString = function() {
    return `start:${toStringFnRef.call(this)}end`;
  }
}

When you do 1 + function x() { alert('hi') } it converts both 1 and the function to strings so it can concatenate them. So this calls your redefined Function.prototype.toString(), which surrounds the normal string of the function with those wrappers. This is then concatenated with 1.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!