__LINE__ equivalent in Javascript

There is a way, although more expensive: throw an exception, catch it immediately, and dig out the first entry from its stack trace. See example here on how to parse the trace. The same trick can also be used in plain Java (if the code is compiled with debugging information turned on).

Edit: Apparently not all browsers support this. The good news is (thanks for the comment, Christoph!) that some browsers export source file name and line number directly through the fileName and lineNumber properties of the error object.


The short answer is no.

The long answer is that depending on your browser you might be able to throw & catch an exception and pull out a stack trace.

I suspect you're using this for debugging (I hope so, anyway!) so your best bet would be to use Firebug. This will give you a console object; you can call console.trace() at any point to see what your programme is doing without breaking execution.


A __LINE__ in C is expanded by a preprocessor which literally replaces it with the line number of the current input. So, when you see

printf("Line Number: %d\r\n", __LINE__);

the compiler sees:

printf("Line Number: %d\r\n", 324);

In effect the number (324 in this case) is HARDCODED into the program. It is only this two-pass mechanism that makes this possible.

I do not know how PHP achieves this (is it preprocessed also?).

Tags:

Javascript