It means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit.
This is almost always because of a recursive function with a base case that isn’t being met.
Viewing the stack
Consider this code…
(function a() {
a();
})();
Here is the stack after a handful of calls…

As you can see, the call stack grows until it hits a limit: the browser hardcoded stack size or memory exhaustion.
In order to fix it, ensure that your recursive function has a base case which is able to be met…
(function a(x) {
// The following condition
// is the base case.
if ( ! x) {
return;
}
a(--x);
})(10);
answered May 23, 2011 at 10:05
![]()
16
In my case, I was sending input elements instead of their values:
$.post( '',{ registerName: $('#registerName') } )
Instead of:
$.post( '',{ registerName: $('#registerName').val() } )
This froze my Chrome tab to a point it didn’t even show me the ‘Wait/Kill’ dialog for when the page became unresponsive…
answered Aug 13, 2016 at 23:55
![]()
FK-FK-
1,4221 gold badge10 silver badges17 bronze badges
7
You can sometimes get this if you accidentally import/embed the same JavaScript file twice, worth checking in your resources tab of the inspector.
double-beep
4,84116 gold badges32 silver badges41 bronze badges
answered Apr 23, 2012 at 1:58
lucygeniklucygenik
1,6782 gold badges16 silver badges18 bronze badges
6
There is a recursive loop somewhere in your code (i.e. a function that eventually calls itself again and again until the stack is full).
Other browsers either have bigger stacks (so you get a timeout instead) or they swallow the error for some reason (maybe a badly placed try-catch).
Use the debugger to check the call stack when the error happens.
answered May 23, 2011 at 9:55
Aaron DigullaAaron Digulla
317k106 gold badges588 silver badges812 bronze badges
3
The problem with detecting stackoverflows is sometimes the stack trace will unwind and you won’t be able to see what’s actually going on.
I’ve found some of Chrome’s newer debugging tools useful for this.
Hit the Performance tab, make sure Javascript samples are enabled and you’ll get something like this.
It’s pretty obvious where the overflow is here! If you click on extendObject you’ll be able to actually see the exact line number in the code.

You can also see timings which may or may not be helpful or a red herring.

Another useful trick if you can’t actually find the problem is to put lots of console.log statements where you think the problem is. The previous step above can help you with this.
In Chrome if you repeatedly output identical data it will display it like this showing where the problem is more clearly. In this instance the stack hit 7152 frames before it finally crashed:

answered Mar 7, 2017 at 13:03
Simon_WeaverSimon_Weaver
136k78 gold badges631 silver badges675 bronze badges
1
In my case, I was converting a large byte array into a string using the following:
String.fromCharCode.apply(null, new Uint16Array(bytes))
bytes contained several million entries, which is too big to fit on the stack.
answered Mar 24, 2017 at 16:48
Nate GlennNate Glenn
6,3357 gold badges47 silver badges93 bronze badges
6
In my case, click event was propagating on child element. So, I had to put the following:
e.stopPropagation()
on click event:
$(document).on("click", ".remove-discount-button", function (e) {
e.stopPropagation();
//some code
});
$(document).on("click", ".current-code", function () {
$('.remove-discount-button').trigger("click");
});
Here is the html code:
<div class="current-code">
<input type="submit" name="removediscountcouponcode" value="
title="Remove" class="remove-discount-button">
</div>
![]()
answered Jan 16, 2017 at 15:36
![]()
ShahdatShahdat
5,2334 gold badges37 silver badges37 bronze badges
This can also cause a Maximum call stack size exceeded error:
var items = [];
[].push.apply(items, new Array(1000000)); //Bad
Same here:
items.push(...new Array(1000000)); //Bad
From the Mozilla Docs:
But beware: in using apply this way, you run the risk of exceeding the
JavaScript engine’s argument length limit. The consequences of
applying a function with too many arguments (think more than tens of
thousands of arguments) vary across engines (JavaScriptCore has
hard-coded argument limit of 65536), because the limit (indeed even
the nature of any excessively-large-stack behavior) is unspecified.
Some engines will throw an exception. More perniciously, others will
arbitrarily limit the number of arguments actually passed to the
applied function. To illustrate this latter case: if such an engine
had a limit of four arguments (actual limits are of course
significantly higher), it would be as if the arguments 5, 6, 2, 3 had
been passed to apply in the examples above, rather than the full
array.
So try:
var items = [];
var newItems = new Array(1000000);
for(var i = 0; i < newItems.length; i++){
items.push(newItems[i]);
}
answered Jun 28, 2019 at 15:45
![]()
bendytreebendytree
12.8k10 gold badges73 silver badges89 bronze badges
1
Check the error details in the Chrome dev toolbar console, this will give you the functions in the call stack, and guide you towards the recursion that’s causing the error.
answered May 28, 2012 at 8:48
chimchim
8,2933 gold badges50 silver badges60 bronze badges
0
In my case, I basically forget to get the value of input.
Wrong
let name=document.getElementById('name');
param={"name":name}
Correct
let name=document.getElementById('name').value;
param={"name":name}
answered Aug 24, 2020 at 7:50
AmanAman
2,1293 gold badges17 silver badges22 bronze badges
2
In my case, it was that I have 2 variables with the same name!
answered Sep 8, 2021 at 1:26
![]()
NandostyleNandostyle
3062 silver badges12 bronze badges
Nearly every answer here states that this can only be caused by an infinite loop. That’s not true, you could otherwise over-run the stack through deeply nested calls (not to say that’s efficient, but it’s certainly in the realm of possible). If you have control of your JavaScript VM, you can adjust the stack size. For example:
node --stack-size=2000
See also: How can I increase the maximum call stack size in Node.js
answered Feb 6, 2019 at 20:48
hayesgmhayesgm
8,4801 gold badge37 silver badges40 bronze badges
We recently added a field to an admin site we are working on — contact_type… easy right? Well, if you call the select «type» and try to send that through a jquery ajax call it fails with this error buried deep in jquery.js Don’t do this:
$.ajax({
dataType: "json",
type: "POST",
url: "/some_function.php",
data: { contact_uid:contact_uid, type:type }
});
The problem is that type:type — I believe it is us naming the argument «type» — having a value variable named type isn’t the problem. We changed this to:
$.ajax({
dataType: "json",
type: "POST",
url: "/some_function.php",
data: { contact_uid:contact_uid, contact_type:type }
});
And rewrote some_function.php accordingly — problem solved.
answered Apr 9, 2019 at 19:35
ScottScott
6891 gold badge8 silver badges16 bronze badges
1
Sending input elements instead of their values will most likely resolve it like FK mentioned
answered Oct 17, 2021 at 10:08
1
In my case, two jQuery modals were showing stacked on top of each other. Preventing that solved my problem.
answered Dec 28, 2016 at 21:23
![]()
Baz GuvenkayaBaz Guvenkaya
1,4803 gold badges17 silver badges26 bronze badges
Check if you have a function that calls itself. For example
export default class DateUtils {
static now = (): Date => {
return DateUtils.now()
}
}
answered Nov 22, 2018 at 13:13
onmyway133onmyway133
44.5k27 gold badges253 silver badges260 bronze badges
For me as a beginner in TypeScript, it was a problem in the getter and the setter of _var1.
class Point2{
constructor(private _var1?: number, private y?: number){}
set var1(num: number){
this._var1 = num // problem was here, it was this.var1 = num
}
get var1(){
return this._var1 // this was return this.var1
}
}
answered Aug 4, 2020 at 14:20
![]()
ReemRashwanReemRashwan
1912 silver badges7 bronze badges
dtTable.dataTable({
sDom: "<'row'<'col-sm-6'l><'col-sm-6'f>r>t<'row'<'col-sm-6'i><'col-sm-6'p>>",
"processing": true,
"serverSide": true,
"order": [[6, "desc"]],
"columnDefs": [
{className: "text-right", "targets": [2, 3, 4, 5]}
],
"ajax": {
"url": "/dt",
"data": function (d) {
d.loanRef = loanRef;
}
},
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var editButton = '';
// The number of columns to display in the datatable
var cols = 8;
// Th row element's ID
var id = aData[(cols - 1)];
}
});
In the data function above, I used the same name d.loanRef = loanRef but had not created a variable loanRef therefore recursively declaring itself.
Solution: Declare a loanRef variable or better still, use a different name from the one used on d.loanRef.
answered Mar 7, 2021 at 5:56
KihatsKihats
3,1084 gold badges28 silver badges46 bronze badges
Both invocations of the identical code below if decreased by 1 work in Chrome 32 on my computer e.g. 17905 vs 17904. If run as is they will produce the error «RangeError: Maximum call stack size exceeded». It appears to be this limit is not hardcoded but dependant on the hardware of your machine. It does appear that if invoked as a function this self-imposed limit is higher than if invoked as a method i.e. this particular code uses less memory when invoked as a function.
Invoked as a method:
var ninja = {
chirp: function(n) {
return n > 1 ? ninja.chirp(n-1) + "-chirp" : "chirp";
}
};
ninja.chirp(17905);
Invoked as a function:
function chirp(n) {
return n > 1 ? chirp( n - 1 ) + "-chirp" : "chirp";
}
chirp(20889);
answered Feb 20, 2014 at 13:12
Elijah LynnElijah Lynn
11.8k10 gold badges57 silver badges86 bronze badges
I also faced similar issue here is the details
when uploading logo using dropdown logo upload box
<div>
<div class="uploader greyLogoBox" id="uploader" flex="64" onclick="$('#filePhoto').click()">
<img id="imageBox" src="{{ $ctrl.companyLogoUrl }}" alt=""/>
<input type="file" name="userprofile_picture" id="filePhoto" ngf-select="$ctrl.createUploadLogoRequest()"/>
<md-icon ng-if="!$ctrl.isLogoPresent" class="upload-icon" md-font-set="material-icons">cloud_upload</md-icon>
<div ng-if="!$ctrl.isLogoPresent" class="text">Drag and drop a file here, or click to upload</div>
</div>
<script type="text/javascript">
var imageLoader = document.getElementById('filePhoto');
imageLoader.addEventListener('change', handleImage, false);
function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) {
$('.uploader img').attr('src',event.target.result);
}
reader.readAsDataURL(e.target.files[0]);
}
</script>
</div>
CSS.css
.uploader {
position:relative;
overflow:hidden;
height:100px;
max-width: 75%;
margin: auto;
text-align: center;
img{
max-width: 464px;
max-height: 100px;
z-index:1;
border:none;
}
.drag-drop-zone {
background: rgba(0, 0, 0, 0.04);
border: 1px solid rgba(0, 0, 0, 0.12);
padding: 32px;
}
}
.uploader img{
max-width: 464px;
max-height: 100px;
z-index:1;
border:none;
}
.greyLogoBox {
width: 100%;
background: #EBEBEB;
border: 1px solid #D7D7D7;
text-align: center;
height: 100px;
padding-top: 22px;
box-sizing: border-box;
}
#filePhoto{
position:absolute;
width:464px;
height:100px;
left:0;
top:0;
z-index:2;
opacity:0;
cursor:pointer;
}
before correction my code was :
function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) {
onclick="$('#filePhoto').click()"
$('.uploader img').attr('src',event.target.result);
}
reader.readAsDataURL(e.target.files[0]);
}
The error in console:

I solved it by removing onclick="$('#filePhoto').click()" from div tag.
answered Aug 3, 2017 at 8:37
spacedevspacedev
99612 silver badges13 bronze badges
2
I was facing same issue
I have resolved it by removing a field name which was used twice on ajax
e.g
jQuery.ajax({
url : '/search-result',
data : {
searchField : searchField,
searchFieldValue : searchField,
nid : nid,
indexName : indexName,
indexType : indexType
},
.....
answered Nov 8, 2017 at 7:57
![]()
The issue in my case is because I have children route with same path with the parent :
const routes: Routes = [
{
path: '',
component: HomeComponent,
children: [
{ path: '', redirectTo: 'home', pathMatch: 'prefix' },
{ path: 'home', loadChildren: './home.module#HomeModule' },
]
}
];
So I had to remove the line of the children route
const routes: Routes = [
{
path: '',
component: HomeComponent,
children: [
{ path: 'home', loadChildren: './home.module#HomeModule' },
]
}
];
answered Jul 25, 2018 at 17:06
Amine HarbaouiAmine Harbaoui
1,2171 gold badge16 silver badges33 bronze badges
1
The issue might be because of recursive calls without any base condition for it to terminate.
Like in my case, if you see the below code, I had the same name for the API call method and the method which I used to perform operations post that API call.
const getData = async () => {
try {
const response = await getData(props.convID);
console.log("response", response);
} catch (err) {
console.log("****Error****", err);
}
};
So, basically, the solution is to remove this recursive call.
answered May 16, 2022 at 15:03
you can find your recursive function in crome browser,press ctrl+shift+j and then source tab, which gives you code compilation flow and you can find using break point in code.
answered Mar 12, 2014 at 8:01
![]()
1
I know this thread is old, but i think it’s worth mentioning the scenario i found this problem so it can help others.
Suppose you have nested elements like this:
<a href="#" id="profile-avatar-picker">
<span class="fa fa-camera fa-2x"></span>
<input id="avatar-file" name="avatar-file" type="file" style="display: none;" />
</a>
You cannot manipulate the child element events inside the event of its parent because it propagates to itself, making recursive calls until the exception is throwed.
So this code will fail:
$('#profile-avatar-picker').on('click', (e) => {
e.preventDefault();
$('#profilePictureFile').trigger("click");
});
You have two options to avoid this:
- Move the child to the outside of the parent.
- Apply stopPropagation function to the child element.
answered Jan 4, 2018 at 14:22
![]()
I had this error because I had two JS Functions with the same name
answered Jan 5, 2018 at 12:33
![]()
Monir TarabishiMonir Tarabishi
6961 gold badge20 silver badges30 bronze badges
If you are working with google maps, then check if the lat lng are being passed into new google.maps.LatLng are of a proper format. In my case they were being passed as undefined.
answered Jan 30, 2018 at 13:25
User-8017771User-8017771
1,3071 gold badge10 silver badges17 bronze badges
Sometimes happened because of convert data type , for example you have an object that you considered as string.
socket.id in nodejs either in js client as example, is not a string. to use it as string you have to add the word String before:
String(socket.id);
answered Jun 27, 2018 at 21:34
in my case I m getting this error on ajax call and the data I tried to pass that variable haven’t defined, that is showing me this error but not describing that variable not defined. I added defined that variable n got value.
answered Aug 29, 2018 at 4:08
asifaftab87asifaftab87
1,25525 silver badges28 bronze badges
1
Ситуация: заказчик попросил разместить на странице кликабельную картинку, а чтобы на неё обратило внимание больше посетителей, попросил сделать вокруг неё моргающую рамку. Логика моргания в скрипте очень простая:
- В первой функции находим на странице нужный элемент.
- Добавляем рамку с какой-то задержкой (чтобы она какое-то время была на экране).
- Вызываем функцию убирания рамки.
- Внутри второй функции находим тот же элемент на странице.
- Убираем рамку с задержкой.
- Вызываем первую функцию добавления рамки.
Код простой, поэтому делаем всё в одном файле:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pulse</title>
<style type="text/css">
/* рамка, которая будет моргать */
.pulse { box-shadow: 0px 0px 4px 4px #AEA79F; }
</style>
</head>
<body>
<div id="pulseDiv">
<a href="#">
<div id="advisersDiv">
<img src="https://thecode.media/wp-content/uploads/2020/08/photo_2020-08-05-12.04.57.jpeg">
</div>
</a>
</div>
<!-- подключаем jQuery -->
<script src="https://yastatic.net/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<!-- наш скрипт -->
<script type="text/javascript">
// добавляем рамку
function fadeIn() {
// находим нужный элемент и добавляем рамку с задержкой
$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
// затем убираем рамку
fadeOut();
};
// убираем рамку
function fadeOut() {
// находим нужный элемент и убираем рамку с задержкой
$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
// затем добавляем
fadeIn();
};
// запускаем моргание рамки
fadeIn();
</script>
</body>
</html>
Но при открытии страницы в браузере мы видим, что ничего не моргает, а в консоли появилась ошибка:
❌ Uncaught RangeError: Maximum call stack size exceeded
Что это значит: в браузере произошло переполнение стека вызовов и из-за этого он не может больше выполнять этот скрипт.
Переполнения стека простыми словами означает вот что:
- Когда компьютер что-то делает, он это делает последовательно —
1,2,3,4. - Иногда ему нужно отвлечься от одного и сходить сделать что-то другое — а, б, в, г, д. Получается что-то вроде
1,2,3 → а,б,в,г,д → 4. - Вот эти переходы
3 → аид → 4— это компьютеру нужно запомнить, что он выполнял пункт 3, и потом к нему вернуться. - Каждое запоминание, что компьютер бросил и куда ему нужно вернуться, — это называется «вызов».
- Вызовы хранятся в стеке вызовов. Это стопка таких ссылок типа «когда закончишь вот это, вернись туда».
- Стек не резиновый и может переполняться.
Что делать с ошибкой Uncaught RangeError: Maximum call stack size exceeded
Эта ошибка — классическая ошибка переполнения стека во время выполнения рекурсивных функций.
Рекурсия — это когда мы вызываем функцию внутри самой себя, но чуть с другими параметрами. Когда параметр дойдёт до конечного значения, цепочка разматывается обратно и функция собирает вместе все значения. Это удобно, когда у нас есть чёткий алгоритм подсчёта с понятными правилами вычислений.
В нашем случае рекурсия возникает, когда в конце обеих функций мы вызываем другую:
- Функции начинают бесконтрольно вызывать себя бесконечное число раз.
- Стек вызовов начинает запоминать вызов каждой функции, чтобы, когда она закончится, вернуться к тому, что было раньше.
- Стек — это определённая область памяти, у которой есть свой объём.
- Вызовы не заканчиваются, и стек переполняется — в него больше нельзя записать вызов новой функции, чтобы потом вернуться обратно.
- Браузер видит всё это безобразие и останавливает скрипт.
То же самое будет, если мы попробуем запустить простую рекурсию слишком много раз:

Как исправить ошибку Uncaught RangeError: Maximum call stack size exceeded
Самый простой способ исправить эту ошибку — контролировать количество рекурсивных вызовов, например проверять это значение на входе. Если это невозможно, то стоит подумать, как можно переделать алгоритм, чтобы обойтись без рекурсии.
В нашем случае проблема возникает из-за того, что мы вызывали вторые функции бесконтрольно, поэтому они множились без ограничений. Решение — ограничить вызов функции одной секундой — так они будут убираться из стека и переполнения не произойдёт:
<script type="text/javascript">
// добавляем рамку
function fadeIn() {
// находим нужный элемент и добавляем рамку с задержкой
$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
// через секунду убираем рамку
setTimeout(fadeOut,1000)
};
// убираем рамку
function fadeOut() {
// находим нужный элемент и убираем рамку с задержкой
$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
// через секунду добавляем рамку
setTimeout(fadeIn,1000)
};
// запускаем моргание рамки
fadeIn();
</script>

Вёрстка:
Кирилл Климентьев
The JavaScript exception «too much recursion» or «Maximum call stack size exceeded»
occurs when there are too many function calls, or a function is missing a base case.
Message
RangeError: Maximum call stack size exceeded (Chrome) InternalError: too much recursion (Firefox) RangeError: Maximum call stack size exceeded. (Safari)
Error type
InternalError in Firefox; RangeError in Chrome and Safari.
What went wrong?
A function that calls itself is called a recursive function. Once a condition
is met, the function stops calling itself. This is called a base case.
In some ways, recursion is analogous to a loop. Both execute the same code multiple
times, and both require a condition (to avoid an infinite loop, or rather, infinite
recursion in this case). When there are too many function calls, or a function is
missing a base case, JavaScript will throw this error.
Examples
This recursive function runs 10 times, as per the exit condition.
function loop(x) {
if (x >= 10) // "x >= 10" is the exit condition
return;
// do stuff
loop(x + 1); // the recursive call
}
loop(0);
Setting this condition to an extremely high value, won’t work:
function loop(x) {
if (x >= 1000000000000)
return;
// do stuff
loop(x + 1);
}
loop(0);
// InternalError: too much recursion
This recursive function is missing a base case. As there is no exit condition, the
function will call itself infinitely.
function loop(x) {
// The base case is missing
loop(x + 1); // Recursive call
}
loop(0);
// InternalError: too much recursion
Class error: too much recursion
class Person {
constructor() {}
set name(name) {
this.name = name; // Recursive call
}
}
const tony = new Person();
tony.name = "Tonisha"; // InternalError: too much recursion
When a value is assigned to the property name (this.name = name;) JavaScript needs to
set that property. When this happens, the setter function is triggered.
In this example when the setter is triggered, it is told to do the same thing again: to set the same property that it is meant to handle. This causes the function to call itself, again and again, making it infinitely recursive.
This issue also appears if the same variable is used in the getter.
class Person {
get name() {
return this.name; // Recursive call
}
}
To avoid this problem, make sure that the property being assigned to inside the setter
function is different from the one that initially triggered the setter. The same goes
for the getter.
class Person {
constructor() {}
set name(name) {
this._name = name;
}
get name() {
return this._name;
}
}
const tony = new Person();
tony.name = "Tonisha";
console.log(tony);
See also
The JavaScript RangeError: Maximum call stack size exceeded is an error that occurs when there are too many function calls, or if a function is missing a base case.
Error message:
RangeError: Maximum call stack size exceeded
Error Type:
RangeError
What Causes RangeError: Maximum Call Stack Size Exceeded
The RangeError: Maximum call stack size exceeded is thrown when a function call is made that exceeds the call stack size. This can occur due to the following reasons:
- Too many function calls.
- Issues in handling recursion, e.g. missing base case in a recursive function to stop calling itself infinitely.
- Out of range operations.
RangeError: Maximum Call Stack Size Exceeded Example
Here’s an example of a JavaScript RangeError: Maximum call stack size exceeded thrown when using a recursive function that does not have a base case:
function myFunc() {
myFunc();
}
myFunc();
Since the recursive function myFunc() does not have a terminating condition (base case), calling it creates an infinite loop as the function keeps calling itself over and over again until the RangeError: Maximum call stack size exceeded error occurs:
Uncaught RangeError: Maximum call stack size exceeded
at myFunc (test.js:2:2)
at myFunc (test.js:2:2)
at myFunc (test.js:2:2)
at myFunc (test.js:2:2)
at myFunc (test.js:2:2)
at myFunc (test.js:2:2)
at myFunc (test.js:2:2)
at myFunc (test.js:2:2)
at myFunc (test.js:2:2)
at myFunc (test.js:2:2)
How to Avoid RangeError: Maximum Call Stack Size Exceeded
If this error is encountered when calling recursive functions, it should be ensured that the function has a defined base case to terminate the recursive calls.
In case this error occurs due to an excessive number of function calls or variables, these should be reduced as much as possible. Any out of range operations should also be checked and avoided. These issues can be inspected using the browser console and developer tools.
The earlier example can be updated to include a base case:
function myFunc(i) {
if (i >= 5) {
return;
}
myFunc(i+1);
}
myFunc(1);
The above code avoids the error since recursive calls terminate when the base case is met.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Sign Up Today!
The error “Uncaught RangeError: Maximum call stack size exceeded” is common among programmers who work with JavaScript. It happens when the function call exceeds the call stack limit.
Let us look at the error in detail and the solution too.
What do you Mean by Maximum Call Stack Error?
This error is caused mainly due to the following reasons –
Non-Terminating Recursive Functions
Your browser will allocate a certain amount of memory to all data types of the code you are running. But this memory allocation has a limit. When you call a recursive function, again and again, this limit is exceeded and the error is displayed.
So, call recursive functions carefully so that they terminate after a certain condition is met. This will prevent the maximum call stack to overflow and the error will not pop up.
Problematic Ranges
Some JS programs have ranges of inputs that the user can give. Other programs have functions that may go out of range. When this happens, browsers like Google Chrome will give you the Uncaught RangeError message. But Internet Explorer will crash.
To prevent this, always check the validity of input ranges and how the functions are working with the ranges.
Let us look at an example.
Example
<script>
fun_first();
function fun_first(){
console.log('Hi');
fun_first();
}
</script>
Explanation
In the above example, we are recursively calling fun_first() due to which the error is Uncaught RangeError encountered. The recursive function is called, which then calls another function, and goes on until it exceeds the call stack limit.
Solution
We should call a recursive function with an If condition. When the code satisfies the condition, the function execution is stopped.
Code Example
<script>
var i=1;
fun_first(i);
function fun_first(i){
if (i <= 10){
console.log('Hi');
i=i+1;
fun_first(i);
}
}
</script>
In the above example, we have created an if condition to check the value of i. If the value of i reaches 10, the same function will not be called again.
Conclusion
The Uncaught RangeError is caused when the browser’s hardcoded stack size is exceeded and the memory is exhausted. So, always ensure that the recursive function has a base condition that can stop its execution.
The «Uncaught RangeError: Maximum call stack size exceeded» error occurs in JavaScript when you don’t specify an exit condition for your recursive function. Take the following as an example:
const test = () => test()
// ❌ This will throw "Uncaught RangeError: Maximum call stack size exceeded"
test()
Copied to clipboard!
This function will call itself indefinitely, causing the «Maximum call stack size exceeded» error. You may also come across this error in other forms, such as the below, but the cause will be the same.
"Uncaught InternalError: Too much recursion"
To fix the error, we will need to provide an exit condition. You can do this by wrapping the call inside a conditional statement. Take the following code as an example:
const countDown = num => {
if (num > 0) {
console.log(num)
countDown(num - 1)
}
}
Copied to clipboard!
This is also a recursive function that calls itself and will log out numbers until it reaches 0. Notice that we call the function with the «same argument — 1». This means that at a certain call, the condition will not be met, meaning we will stop executing the function. This way, we won’t reach the maximum call stack size, as we have an exit condition.
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.

Infinite loops
The «Maximum call stack size exceeded» error can not only happen with recursive functions, but with infinite loops as well. Most commonly, this can happen while using a while loop.
A common way to ensure that your while loop has an exit condition is to decrement a value at each iteration. Take a look at the following example:
i = 100
while (i--) {
console.log(i)
}
Copied to clipboard!
Once i reaches 0, it will be evaluated as false, meaning we will stop executing the while loop. In this case, this is our exit condition.
Make sure you always define an exit condition to avoid running into infinite loops.
Want to learn more about recursion in JavaScript? Check out the below tutorial.

An Easy Way to Understand Recursion in JavaScript
Recursion demonstrated through practical examples
Learn recursion in and out in JavaScript by learning how to generate file trees.
Maximum call stack size exceededError in JavaScript- Recursive Function in JavaScript
- Fix a Recursive Function in JavaScript
- Find the Error in JavaScript

The JavaScript’s Maximum call stack size exceeded error occurs when a function is called so many times that the invocations exceed the maximum call stack limit.
If the JavaScript’s Maximum call stack size exceeded error occurs, the problem lies with the recursive function within your JavaScript code. More particularly, the problem is with the function, which keeps calling on itself repeatedly.
Maximum call stack size exceeded Error in JavaScript
When this error occurs, there are several steps you can take to fix the piece of code that is eating up all the available call stacks within a browser.
With the help of this JavaScript article, you will go over in great detail why a Maximum call stack size exceeded error shows up and what you can do to fix it.
All JavaScript error objects are descended from or inherited from the Error object. This is referred to as a RangeError.
A RangeError often indicates an error outside a code’s parameter’s argument value.
Now that you know a bit of where this error falls within the scope of JavaScript errors let’s continue to what causes the Maximum call stack size exceeded error.
Still, you need to understand recursion before understanding the Maximum call stack size exceeded error.
Recursive Function in JavaScript
Recursion is a pattern in which a defined function calls itself, with each iteration moving conditions closer to a base case that allows an escape from the function calls. However, if you’re not careful, a function can continuously call itself until the browser’s stack is depleted.
The most common cause of a recursive function’s Maximum call stack size exceeded error is a problem with the base case or the lack thereof. When recursive code doesn’t have its base code or shoots past it, it will keep calling itself until the browser’s Maximum Call Stack is reached.
Fix a Recursive Function in JavaScript
The issue with a recursive function that continues to call on itself is that it is impossible to move on to the following function within a chain, and you’ll eat up the entirety of your stack.
Double-checking your recursive functions is the best approach to avoid this issue. Then, to solve the problem, specify a base case that must be satisfied to exit the recursion.
The screenshot below shows what recursive code looks like when it calls on itself indefinitely.

function example() {
// RangeError: Maximum call stack size exceeded
example();
}
example();
You can call the function, which calls itself until the call stack limit is exceeded. After that, you must specify a condition where the function stops calling itself to solve the error.
let counter = 0;
function example(num) {
if (num < 0) {
return;
}
counter += 1;
example(num - 1);
}
example(4);
console.log(counter);
This time you will check if the function was invoked with a number that is less than 0 on every invocation. If the number is less than 0, you will return from the function, so you do not exceed the call stack’s limit.
If the passed-in value is not less than zero, you will call the function with the passed-in value, which is 1. This will keep you moving toward the case where the if check is satisfied.
A recursive function keeps on calling itself until a condition is met. For example, if there is no condition to complete your function, it will call itself until the maximum call stack size is exceeded.
You’ll receive this error if you have an infinite loop that calls a function.
function sum(x, y) {
return x + y;
}
while (true) {
sum(10, 10);
}
The while loop will keep calling the function, and since you don’t have a condition that would exit the loop, you will eventually exceed the call stack size.
This behaves similarly to a function that calls itself without a base condition. For example, the same would be the case if you used a for loop.
Below is an example of how you can specify a condition that must be met to exit the loop.
function sum(x, y) {
return x + y;
}
let total = 0;
for (let i = 10; i > 0; i--) {
total += sum(5, 5);
}
console.log(total);
The condition in the for loop will not be satisfied if the i variable is equal to or less than 0; thus, you will leave the loop.
Find the Error in JavaScript
Going through your logs is the first step in finding an error, but finding that one line of broken code can be difficult when working with thousands of lines of code.
The error can also occur if you import the same file many times on the same page, such as when you load the jQuery script numerous times on the same page. Open the Network tab in your browser’s developer tools and refresh the page to see which scripts are loaded on your website.
