关于函数addNumbers是否为纯函数的疑问
addNumbers function really impure? My confusion with a blog's claim Hey there! I totally get why this has you confused—let's sort this out step by step.
First off, your initial take is right on the money: that addNumbers function is absolutely a pure function. Let's go back to the two core rules of pure functions you mentioned, and verify them here:
- It always returns the exact same output every time it's called (no matter how many times you run
addNumbers(), it will always spit out 101) - It has zero side effects: it doesn't change any variables outside its own scope, doesn't make any network calls, doesn't interact with the DOM, or do anything else that affects the world outside the function itself.
So why did that blog claim it's impure? That's almost certainly an error on their part. Pure functions don't need to take input parameters—they just need to be deterministic (same result every time) and not cause side effects. Since this function's result is fixed by its internal constant values, it checks both boxes perfectly.
Here's the code in question for quick reference:
function addNumbers(){ let num1 = 100; let num2 = 1; return num1 + num2; }
To sum up: don't doubt your initial understanding here—this is a pure function, and the blog's claim is incorrect.
备注:内容来源于stack exchange,提问作者Bappy

