Hello, fellow devs!❤
Ever encountered the "RangeError: Maximum Call Stack Size Exceeded" in your JavaScript code?
Picture this: your code is chugging along, minding its own business, when suddenly, BAM!😡 You're hit with the dreaded error.
The "RangeError: Maximum Call Stack Size Exceeded" is a very common error in JavaScript. But fear not! We will understand everything about it, so it never fails to catch your breath.
Maximum call stack size exceeded
Let's take an example
function recFunc() {
recFunc();
}
recFunc();
My recursive function in this case is called recFunc, and it is indefinite since it lacks any parameters. It continues to repeat itself in an attempt to discover an endpoint as a result, placing it in an infinite loop scenario.
Due to the function's lack of a target and call stack overflow, the RangeError is raised as an error.
This is how it appears to your terminal:😖
Due to the function's lack of a target and call stack overflow, the RangeError is raised as an error.
This is how it appears to your terminal:😖
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)
It relates to a runtime issue that can occur in Python and JavaScript, among other computer languages. A call stack is used by an executable program to record function calls. A "Maximum Call Stack Size Exceeded" error may be raised by the system if this stack gets too deep as a result of an excessive number of function calls or endless recursion.
This error indicates that the call stack capacity of the program has been reached, which frequently calls for a study and optimization of the code to avoid stack overflow.
This error indicates that the call stack capacity of the program has been reached, which frequently calls for a study and optimization of the code to avoid stack overflow.
What is a Recursive Function?
Since they enable a function to call itself, recursive functions are essential to programming. This method works especially well for resolving issues that have recurring patterns or can be divided into more manageable, related subproblems.
The main concept is to solve a smaller version of the issue with each recursive call, working your way up to the solution of the original problem. When used properly, recursive functions enhance the beauty and conciseness of code.
The main concept is to solve a smaller version of the issue with each recursive call, working your way up to the solution of the original problem. When used properly, recursive functions enhance the beauty and conciseness of code.
How do I fix the maximum call stack size exceeded?
The solution to this problem is easy. Our only task is to set yourself free from the never-ending loop; how can you achieve this? I'll give you an explanation:
It is obvious from the example above that the RangeError happened as a result of the function's lack of clarity on when it stops calling itself. It is reached an unlimited number of times.
But what happens if we assign it a definite value for your loop?
So let's look at an example to learn how to achieve that.
It is obvious from the example above that the RangeError happened as a result of the function's lack of clarity on when it stops calling itself. It is reached an unlimited number of times.
But what happens if we assign it a definite value for your loop?
So let's look at an example to learn how to achieve that.
function recFunc(i) {
if (i >= 6) {
return;
}
recFunc(i+1);
}
recFunc(1);
Again, this is a simple example, but you get the point. Right? It is obvious the function calls itself for a purpose. It is for the letter "i," and it must call itself a certain amount of times.
That is, unless "i" equals or exceeds 6. Hence, till this argument is fulfilled, the function keeps looping. Thus, it continues to operate as "i" until it reaches 6. The function loops till it reaches 6 and then stops and returns the output.
What about for Complex Scenario?
But sometimes we deal with huge databases and complex concepts, I also have done that in one of my Industry level projects. I have pasted my code with a recursive function in nodeJs, hope you get a better idea😀
const folderWiseItem = async (params) => {
async function getFolderHierarchyRecursive(parentId, userId, folderType) {
const query = {
parentId: parentId,
userId: userId,
deletedAt: null,
type: "folder",
};
if (folderType) {
query.folderType = folderType;
}
const folders = await Model.find(query).sort({ ordering: 1 });
const folderDetails = await Promise.all(
folders.map(async (folder) => {
const subFolderDetails = await getFolderHierarchyRecursive(
folder._id,
userId,
folderType
);
const itemDetails = await Model.find({
parentId: folder._id,
userId: userId,
deletedAt: null,
type: "item",
}).sort({ ordering: 1 });
const totalItemValue = itemDetails.reduce(
(total, item) =>
total +
(item.field.find((f) => f.code === "TotalValue")
? Number(
item.field.find((f) => f.code === "TotalValue").fieldValue
)
: 0),
0
);
return {
...folder.toObject(),
subFolderDetails: subFolderDetails.filter(
(subFolder) => subFolder.type === "folder"
),
itemDetails: itemDetails,
folderCount: subFolderDetails.length,
itemCount: itemDetails.length,
totalItemValue: totalItemValue,
};
})
);
return folderDetails;
}
try {
const userId = params.userId
? new ObjectId(params.userId)
: params.authUser._id;
const { folderType } = params;
const folderDataWithSubFolders = await getFolderHierarchyRecursive(
null,
userId,
folderType
);
return {
status: HttpStatus.OK,
message: ApiMessage.SUCCESS,
data: folderDataWithSubFolders,
};
} catch (error) {
console.error(error);
return errorHandler(error, params);
}
};
Happy coding✌