Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a function that will work in all major browsers, although it won't work in ECMAScript 5 strict mode because <code>arguments.callee</code> and <code>caller</code> have been removed in strict mode.</p> <pre><code>function getCallStackSize() { var count = 0, fn = arguments.callee; while ( (fn = fn.caller) ) { count++; } return count; } </code></pre> <p>Example:</p> <pre><code>function f() { g(); } function g() { h(); } function h() { alert(getCallStackSize()); } f(); // Alerts 3 </code></pre> <p><strong>UPDATE 1 November 2011</strong></p> <p>In ES5 strict mode, there is simply <a href="https://developer.mozilla.org/en/JavaScript/Strict_mode#.22Securing.22_JavaScript" rel="noreferrer">no way to navigate the call stack</a>. The only option left is to parse the string returned by <code>new Error().stack</code>, which is non-standard, not universally supported and obviously problematic, and even this <a href="http://whereswalden.com/2010/09/08/new-es5-strict-mode-support-now-with-poison-pills/" rel="noreferrer">may not be possible for ever</a>.</p> <p><strong>UPDATE 13 August 2013</strong></p> <p>This method is also limited by the fact that a function that is called more than once in a single call stack (e.g. via recursion) will throw <code>getCallStackSize()</code> into an infinite loop (as pointed out by @Randomblue in the comments). An improved version of <code>getCallStackSize()</code> is below: it keeps track of functions it has seen before to avoid going into an infinite loop. However, the returned value is the number of different function objects in the callstack before encountering a repeat rather than the true size of the complete call stack. This is the best you can do, unfortunately.</p> <pre><code>var arrayContains = Array.prototype.indexOf ? function(arr, val) { return arr.indexOf(val) &gt; -1; } : function(arr, val) { for (var i = 0, len = arr.length; i &lt; len; ++i) { if (arr[i] === val) { return true; } } return false; }; function getCallStackSize() { var count = 0, fn = arguments.callee, functionsSeen = [fn]; while ( (fn = fn.caller) &amp;&amp; !arrayContains(functionsSeen, fn) ) { functionsSeen.push(fn); count++; } return count; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload