1

I'm using console.log(var_name); to debug JS code in chrome and am wondering, is there a way to output to the console the line at which the current function was called?

1
  • I've just solved my bug everyone... thanks to all who replied!!! Commented Nov 30, 2011 at 16:13

2 Answers 2

2

You can get the stack trace with the following:

(new Error).stack;

You could then use a regular expression to filter out the line number: http://jsfiddle.net/8wA74/.

var stack = (new Error).stack.split("\n"),
    line = /:(\d+):/.exec(stack[1]); // 1 is stack depth, format is "url:line:char"

console.log("Current function was called on line " + line[1]);
// this 1 is the number of the group in regexp
Sign up to request clarification or add additional context in comments.

2 Comments

thanks @pimvdb, this is helpful to an extent although it's actually giving me the line where (new Error) is, not the line where the function that encompasses that was called.
@Jimmy_Bob: Then you can try changing stack[1] to stack[2], which is one level deeper in the stack trace.
1

Not that i know of, but wouldnt it be possible to set a breakpoint instead? That surely has a stacktrace visible.

Just try to click the linenumber in the dev. console, it'll show a blue arrow and next time it hits it'll show you the stacktrace.

1 Comment

thanks for this, I'm sure breakpoints will be easier than console logging when I get the hang of them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.