Languages
[Edit]
EN

JavaScript - get method call stack

4 points
Created by:
Aston-Freeman
787

In this short article we want to show how to get method call stack in JavaScript in Google Chrome web browser.

Quick solution:

// ONLINE-RUNNER:browser;

const pattern = /^\s*at\s*(\w*)\s+\(?(.*)\)?\s*$/g;
            
const getCallStack = () => {
    const stack = [];
    try {
        throw new Error(); // exception throwing to get access to call stack
    } catch(e) {
        const parts = e.stack.split('\n');
        for (let i = 2; i < parts.length; ++i) {
            pattern.lastIndex = 0;
            const match = pattern.exec(parts[i]);
            if (match) {
                stack.push({
                    method: match[1],
                    file: match[2]
                });
            }
        }
    }
    return stack;
};

// Usage example:

const method1 = () => {
    const stack = getCallStack();
    console.log('----------------------------');
	console.log(' method1                    ');
	console.log('----------------------------');
	console.log(JSON.stringify(stack[0], null, 2));
	console.log(JSON.stringify(stack[1], null, 2));
	console.log();
};

const method2 = () => {
    const stack = getCallStack();
    console.log('----------------------------');
	console.log(' method2                    ');
	console.log('----------------------------');
	console.log(JSON.stringify(stack[0], null, 2));
	console.log();
    method1();
};

method2();
Getting method call stack in JavaScript example.
Getting method call stack in JavaScript example.

Alternative titles

  1. JavaScript - get function call stack
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join