Does having unused parameters in javascript functions slow down execution? Does it take up memory? I often write functions with parameters that are never actually used for example function has an event as a parameter, but the event is never used for anything.
Unused local variables make code hard to read and understand. Any computation used to initialize an unused variable is wasted, which may lead to performance problems.
Nothing will happen- meaning you won't get an error or a warning as passing the parameters in javascript is optional.
There is no need to specify the data type for parameters in JavaScript function definitions. It does not perform type checking based on passed in JavaScript function.
When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.
slow down execution?
The running time depends upon the operation being performed on the input. May it be a search or a sort or any simple operation. The running time of the operation determines the speed of its execution. So when you don't pass any parameter, that means no action is being performed on that parameter and hence the running time is stable.
Does it take up memory?
But as far as memory allocation is concerned, they are generally allocated a Lexical Environment.
When the function runs, on every function call, the new
LexicalEnvironment
is created and populated with arguments, variables and nested function declarations.
So for the below function:
function sayHi(name) {
/* LexicalEnvironment = { name: passedvalue,
phrase: undefined }*/ // created at this point.
var phrase = "Hi, " + name
alert(phrase)
}
So when you invoke it as sayHi()
, the lexical envirmonemt looks like:
LexicalEnvironment = { name: undefined, phrase: undefined};
Hence, each parameters and function variables are allocated memory when the interpreter interprets the function.
When the interpreter is preparing to start function code execution, before the first line is run, an empty LexicalEnvironment is created and populated with arguments, local variables and nested functions.
JavaScript anyways stores parameters sent to every function in the arguments
array, irrespective of you allocating local variables for them.
function test() {
console.log(arguments)
}
test('these','are','passed')
//logs ["these','are',passed']
My point is that the unused parameters are anyways taking up memory, you are only referencing them using another variable name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With