How can I determine the current line number in JavaScript?

JavascriptLine Numbers

Javascript Problem Overview


Does JavaScript have a mechanism for determining the line number of the currently executing statement (and if so, what is it)?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

You can use:

function test(){
    console.trace();
}

test();

Solution 3 - Javascript

A bit more portable between different browsers and browser versions (should work in Firefox, Chrome and IE10+):

function ln() {
  var e = new Error();
  if (!e.stack) try {
    // IE requires the Error to actually be throw or else the Error's 'stack'
    // property is undefined.
    throw e;
  } catch (e) {
    if (!e.stack) {
      return 0; // IE < 10, likely
    }
  }
  var stack = e.stack.toString().split(/\r\n|\n/);
  // We want our caller's frame. It's index into |stack| depends on the
  // browser and browser version, so we need to search for the second frame:
  var frameRE = /:(\d+):(?:\d+)[^\d]*$/;
  do {
    var frame = stack.shift();
  } while (!frameRE.exec(frame) && stack.length);
  return frameRE.exec(stack.shift())[1];
}

Solution 4 - Javascript

You can try to parse a source of a function to seek some marks.
Here is a quick example (yes, it's messed a little).

function foo()	
{		
	alert(line(1));
	var a;
	var b;		
	alert(line(2));
}	
foo();
	
function line(mark)
{
	var token = 'line\\(' + mark + '\\)';		
	var m = line.caller.toString().match(
        new RegExp('(^(?!.*' + token + '))|(' + token + ')', 'gm')) || [];
	var i = 0;
	for (; i < m.length; i++) if (m[i]) break;
	return i + 1;
}

Solution 5 - Javascript

Inject the following snippet to your code:

console.debug("line:", /\(file:[\w\d/.-]+:([\d]+)/.exec(new Error().stack)[1]);

Solution 6 - Javascript

You can try:

window.onerror = handleError;
function handleError(err, url, line){
    alert(err + '\n on page: ' + url + '\n on line: ' + line);
}

Then throw an error where you want to know (not overly desired, but it might help you if you are debugging.

Note: window.onerror isn't defined/handled in WebKit or Opera (the last time I checked)

Solution 7 - Javascript

Purely one can't get the line number out of Error.stack, because in Angular the line number is the line number of the compiled code. But one can get the info in which method the error was created. The class Logger in this code snippet add this piece of information to a new logbook entry.

https://stackblitz.com/edit/angular-logger?file=src/app/Logger/logger.ts

Solution 8 - Javascript

If your code is JavaScript + PHP, then the current PHP line number is available in JavaScript as a literal constant, because it's available in PHP as   <?= __LINE__ ?>

(That's assuming you have PHP short tags enabled, obviously.)

So, for example, in JavaScript you can say:

this_php_line_number = <?= __LINE__ ?>;

However, if you are not careful, the PHP line number might be different from the JavaScript line number, because PHP "eats" source lines before the browser ever sees them. So the problem becomes ensuring that your PHP and JavaScript line numbers are the same. If they're different it makes using the browser's JavaScript debugger a lot less pleasant.

You can ensure the line numbers are the same by including a PHP statement that writes the correct number of newlines needed to synchronize server-side (PHP) and browser-side (JavaScript) line numbers.

Here's what my code looks like:

<!DOCTYPE html>
<html lang="en">
<!-- Copyright 2016, 2017, me and my web site -->
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, user-scalable=yes">

<?php

...lots of PHP stuff here, including all PHP function definitions ...

echo str_repeat("\n",__LINE__-6); # Synchronize PHP and JavaScript line numbers
?>
<!-- *** this is line <?php echo __LINE__ . ' of ' . basename(__FILE__); ?> *** -->

  <title>My web page title</title>

...lots of HTML and JavaScript stuff here...

</body>
</html>
<!-- *** this is line <?php echo __LINE__ . ' of ' . basename(__FILE__); ?> *** -->

The key is this PHP statement:

echo str_repeat("\n",__LINE__-6);

That spits out enough newlines to make the line number seen by JavaScript be the same as the PHP line number. All the PHP function definitions, etc. are at the top, ahead of that line.

After that line, I restrict my use of PHP to code that doesn't change the line numbers.

The "-6" accounts for the fact that my PHP code starts on line 8. If you start your PHP code earlier, you'll reduce that number. Some people put their PHP right at the very top, even ahead of the DOCTYPE.

(The meta viewport line disables Android Chrome "font boosting" per this Stack Overflow Q&A: https://stackoverflow.com/questions/11289166/chrome-on-android-resizes-font. Consider it boilerplate, which every web page needs.)

The following line is just for verifying that I haven't made a mistake. Viewed in the browser's debugger, or by right-click / save-web-page, it becomes an HTML comment which shows the correct source file name and line number:

<!-- *** this is line <?php echo __LINE__ . ' of ' . basename(__FILE__); ?> *** -->

becomes:

<!-- *** this is line 1234 of my_file.php *** -->

Now, wherever I see a line number, whether it's in an error message or in the JavaScript debugger, it's correct. PHP line numbers and JavaScript line numbers are always consistent and identical.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatthew MurdochView Question on Stackoverflow
Solution 1 - JavascriptMark BolusmjakView Answer on Stackoverflow
Solution 2 - JavascriptbaligenaView Answer on Stackoverflow
Solution 3 - JavascriptjwattView Answer on Stackoverflow
Solution 4 - JavascriptMikhail NasyrovView Answer on Stackoverflow
Solution 5 - JavascriptcrishushuView Answer on Stackoverflow
Solution 6 - JavascriptscunliffeView Answer on Stackoverflow
Solution 7 - JavascriptVireeView Answer on Stackoverflow
Solution 8 - JavascriptDave BurtonView Answer on Stackoverflow