Ramtin Soltani Ramtin Soltani - 5 months ago 33
Javascript Question

Javascript: How to get line number of a statement inside .js file?

I'm wondering if it's possible to get the line number of a statement inside a .js file. For instance:

// line 1
// line 2
detectLineNumber();
// line 4


How can I have
detectLineNumber()
to find where it was invoked and console-log the line number
3
? Is it possible?

UPDATE
I'm afraid
(new Error).lineNumber
won't work for me since it doesn't work in Chrome. Answer should be cross-browser.

Answer
var thisline = new Error().lineNumber

If that doesn't work in whatever environment you're using, you can try:

var stack = new Error().stack

Then hunt through the stack for the line number.

see in How can I determine the current line number in JavaScript?