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

149
Views
Javascript new Function stack trace line numbers off by 2

Javascript stack trace line numbers for code within new Function are off by 2:

const fn = new Function(` // line 1
  try {                   // line 2
    blah                  // line 3
  } catch(e) {            // line 4
    return e.stack        // line 5
  }                       // line 6
`)

console.log(fn())

Running the above snippet produces:

anonymous@https://stacksnippets.net/js line 12 > Function:5:5

where it should say Function:3:5. Same thing when run in node:

$ cat stack-trace-line-nums.js 
const fn = new Function(` // line 1
  try {                   // line 2
    blah                  // line 3
  } catch(e) {            // line 4
    return e.stack        // line 5
  }                       // line 6
`)

console.log(fn())
$ node stack-trace-line-nums.js 
ReferenceError: blah is not defined
    at eval (eval at <anonymous> (/tmp/stack-trace-line-nums.js:1:12), <anonymous>:5:5)
    ...

The most obvious way to demonstrate is to put all the code on the same line:

const fn = new Function('try { blah } catch(e) { return e.stack }')

console.log(fn())

which produces:

anonymous@https://stacksnippets.net/js line 12 > Function:3:7

instead of Function:1:7.

Any idea what's the cause or if there's a workaround?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Log the function itself and you'll see what's going on:

const fn = new Function(` // line 1
  try {                   // line 2
    blah                  // line 3
  } catch(e) {            // line 4
    return e.stack        // line 5
  }                       // line 6
`)
console.log(fn);
console.log(fn())

It actually becomes:

 function anonymous(
) {
 // line 1
  try {                   // line 2

The first line is the function definition, the second line is the end of the parameter list and the start of the block, and only on line 3 does the actual body of the function passed into the constructor get inserted.

So, just add 2 to the line number every time.

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!