console.log(`Hello, ${name}`);
}
greet(“John Doe”);
const age = calculateAge(new Date(“1997-01-01”));
console.log(age);
In JavaScript, a function parameter is a variable that is declared inside the function’s parentheses. When a function is called, the value of the argument passed to the function is assigned to the function parameter.
For example, the following function takes a string argument and prints it to the console:
js function greet(name) { console.log(`Hello, ${name}`); }
greet(“world”); // prints “Hello, world”
In this example, the `name` parameter is assigned the value of the `”world”` argument.
Assignment to property of function parameter
Assignment to property of function parameter is a JavaScript feature that allows you to assign a value to a property of a function parameter. This can be useful for initializing the value of a parameter or for passing a reference to an object.
For example, the following code assigns the value `”hello”` to the `name` property of the `greet` function parameter:
js function greet(name) { name.value = “hello”; }
greet({ value: “world” }); // prints “hello”
In this example, the `name` parameter is a JavaScript object. The `value` property of the `name` object is assigned the value of the `”hello”` argument.
When to use assignment to property of function parameter?
You should use assignment to property of function parameter when you need to:
Avoid creating a new object
Initializing the value of a parameter
You can use assignment to property of function parameter to initialize the value of a parameter. For example, the following code initializes the `name` property of the `greet` function parameter to the value of the `”world”` argument:
js function greet(name) { name.value = “world”; }
Passing a reference to an object
You can use assignment to property of function parameter to pass a reference to an object. For example, the following code passes a reference to the `person` object to the `greet` function:
js function greet(person) { console.log(`Hello, ${person.name}`); }
const person = { name: “John Doe” };
greet(person); // prints “Hello, John Doe”
You can use assignment to property of function parameter to avoid creating a new object. For example, the following code uses assignment to property of function parameter to avoid creating a new object for the `name` parameter:
greet(“John Doe”); // prints “Hello, John Doe”
In this example, the `name` parameter is a string literal. The `name` property of the `name` parameter is assigned the value of the `”John Doe”` string literal. This avoids creating a new object for the `name` parameter.
Assignment to property of function parameter is a JavaScript feature that can be used to initialize the value of a parameter, pass a reference to an object, and avoid creating a new object. It is a powerful feature that can be used to improve the performance and readability of your code.
Additional resources
To use assignment to property of function parameter, you can simply assign a value to the property of the function parameter. For example, the following code assigns the value `”hello”` to the `name` property of the `greet` function parameter:
In this example, the `greet` function is called with the argument `”world”`. The `name` property of the `greet` function parameter is then assigned the value `”hello”`. When the `greet` function is called, the value of the `name` property is used to print the message `”Hello, world”`.
Assignment to property of function parameter can be used to initialize the value of a parameter, pass a reference to an object, or avoid creating a new object.
You can use assignment to property of function parameter to initialize the value of a parameter. For example, the following code initializes the value of the `name` property of the `greet` function parameter to the value of the `name` variable:
js function greet(name) { name = “world”; console.log(`Hello, ${name}`); }
In this example, the `name` variable is assigned the value `”world”` before the `greet` function is called. The `name` property of the `greet` function parameter is then assigned the value of the `name` variable. When the `greet` function is called, the value of the `name` property is used to print the message `”Hello, world”`.
You can use assignment to property of function parameter to pass a reference to an object. For example, the following code passes a reference to the `user` object to the `greet` function:
js function greet(user) { console.log(`Hello, ${user.name}`); }
const user = { name: “John Doe”, };
greet(user); // prints “Hello, John Doe”
In this example, the `user` object is passed to the `greet` function as a parameter. The `greet` function then uses the `name` property of the `user` object to print the message `”Hello, John Doe”`.
Avoiding creating a new object
You can use assignment to property of function parameter to avoid creating a new object. For example, the following code uses assignment to property of function parameter to avoid creating a new object for the `user` variable:
In this example, the `user` variable is assigned the value of the `user` object. The `greet` function then uses the `name` property of the `user` variable to print the message `”Hello, John Doe”`.
By using assignment to property of function parameter, you can avoid creating a new object for the `user` variable. This can improve the performance of your code and reduce the amount of memory that is used.
There are a few pitfalls to be aware of when using assignment to property of function parameter:
js function greet(name) { name = “hello”; console.log(`Hello, ${name}`); }
greet(“world”); // prints “Hello, hello” greet(“hello”); // prints “Hello, hello”
A: Assignment to property of function parameter occurs when you assign a value to a property of a function parameter. This can be done by using the dot operator (.) to access the property, or by using the bracket operator ([]) to index into the property.
For example, the following code assigns the value “10” to the `x` property of the `foo()` function’s parameter `y`:
const foo = (y) => { y.x = 10; };
foo({ x: 5 }); // { x: 10 }
Q: Why is assignment to property of function parameter dangerous?
A: Assignment to property of function parameter can be dangerous because it can change the value of the property in the calling scope. This can lead to unexpected behavior and errors.
For example, the following code changes the value of the `x` property of the global variable `a`:
foo({ x: 5 }); // a.x is now 10
This behavior can be difficult to debug, as it may not be obvious that the change to the `x` property is being caused by the `foo()` function.
Q: How can I avoid assignment to property of function parameter?
There are a few ways to avoid assignment to property of function parameter. One way is to use the `const` keyword to declare the function parameter as a constant. This will prevent the value of the parameter from being changed.
Another way to avoid assignment to property of function parameter is to use the `readonly` keyword to declare the function parameter as read-only. This will prevent the value of the parameter from being changed, even by assignment to a property of the parameter.
Finally, you can also use the `Object.freeze()` method to freeze the object that is passed as the function parameter. This will prevent any changes to the object, including changes to the values of its properties.
Q: What are the best practices for assignment to property of function parameter?
The best practices for assignment to property of function parameter are as follows:
Here are some key takeaways from this article:
By following these tips, you can write more secure and reliable JavaScript code.
Java: how to set a value to an array.
Java Set to Array: A Comprehensive Guide Arrays are a fundamental data structure in Java, and they’re used to store a collection of data of the same type. Sets, on the other hand, are unordered collections of unique elements. In this comprehensive guide, we’ll explore how to set a Java set to an array, and…
Module java.base does not opens java.lang to unnamed module The Java programming language is a powerful and versatile tool that is used in a wide variety of applications. One of the features that makes Java so powerful is its modularity. Modules allow developers to package code into separate units, which can then be imported into…
Next.js 13 Project Structure: A Guide for Beginners Next.js is a React framework that makes it easy to build fast, modern websites. It’s known for its powerful features, such as its server-side rendering (SSR), routing, and code-splitting capabilities. If you’re new to Next.js, or if you’re just looking to brush up on your knowledge of…
String to Integer Array in Java Converting a string to an integer array in Java is a common task that can be accomplished in a few different ways. The best approach for you will depend on the specific needs of your project. In this article, we will discuss three different methods for converting a string…
Py4J NetworkError: Answer from Java Side is Empty If you’re a Python developer who’s ever used the Py4J library to connect to a Java application, you’ve probably encountered the dreaded Py4J NetworkError: Answer from Java Side is Empty. This error can occur for a variety of reasons, but it’s often caused by a problem with…
Execution Failed for Task CompileJava The dreaded “execution failed for task compileJava” error can be a major headache for Java developers. It can occur for a variety of reasons, and it can be difficult to track down the exact cause. In this article, we’ll take a look at some of the most common causes of…
Disallow reassigning function parameters
Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object. Often, assignment to function parameters is unintended and indicative of a mistake or programmer error.
This rule can be also configured to fail when function parameters are modified. Side effects on parameters can cause counter-intuitive execution flow and make errors difficult to track down.
This rule aims to prevent unintended behavior caused by modification or reassignment of function parameters.
Examples of incorrect code for this rule:
Examples of correct code for this rule:
This rule takes one option, an object, with a boolean property "props" , and arrays "ignorePropertyModificationsFor" and "ignorePropertyModificationsForRegex" . "props" is false by default. If "props" is set to true , this rule warns against the modification of parameter properties unless they’re included in "ignorePropertyModificationsFor" or "ignorePropertyModificationsForRegex" , which is an empty array by default.
Examples of correct code for the default { "props": false } option:
Examples of incorrect code for the { "props": true } option:
Examples of correct code for the { "props": true } option with "ignorePropertyModificationsFor" set:
Examples of correct code for the { "props": true } option with "ignorePropertyModificationsForRegex" set:
If you want to allow assignment to function parameters, then you can safely disable this rule.
This rule was introduced in ESLint v0.18.0.
JavaScript: Don’t Reassign Your Function Arguments
© OpenJS Foundation and other contributors Licensed under the MIT License. https://eslint.org/docs/latest/rules/no-param-reassign
Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript function parameters.
A JavaScript function does not perform any checking on parameter values (arguments).
Earlier in this tutorial, you learned that functions can have parameters :
Function parameters are the names listed in the function definition.
Function arguments are the real values passed to (and received by) the function.
JavaScript function definitions do not specify data types for parameters.
JavaScript functions do not perform type checking on the passed arguments.
JavaScript functions do not check the number of arguments received.
If a function is called with missing arguments (less than declared), the missing values are set to undefined .
Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:
ES6 allows function parameters to have default values.
If y is not passed or undefined, then y = 10.
The rest parameter (...) allows a function to treat an indefinite number of arguments as an array:
Advertisement
JavaScript functions have a built-in object called the arguments object.
The argument object contains an array of the arguments used when the function was called (invoked).
This way you can simply use a function to find (for instance) the highest value in a list of numbers:
Or create a function to sum all input values:
If a function is called with too many arguments (more than declared), these arguments can be reached using the arguments object .
The parameters, in a function call, are the function's arguments.
JavaScript arguments are passed by value : The function only gets to know the values, not the argument's locations.
If a function changes an argument's value, it does not change the parameter's original value.
Changes to arguments are not visible (reflected) outside the function.
In JavaScript, object references are values.
Because of this, objects will behave like they are passed by reference:
If a function changes an object property, it changes the original value.
Changes to object properties are visible (reflected) outside the function.
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]
Top references, top examples, get certified.
禁止对函数参数再赋值 (no-param-reassign).
Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object. Often, assignment to function parameters is unintended and indicative of a mistake or programmer error.
对函数参数中的变量进行赋值可能会误导读者,导致混乱,也会改变 arguments 对象。通常,对函数参数进行赋值并非有意为之,更多的是程序员的书写错误做成的。
This rule can be also configured to fail when function parameters are modified. Side effects on parameters can cause counter-intuitive execution flow and make errors difficult to track down.
当函数参数被修改时,该规则也可能会失效。由此造成的副作用可能导致不直观的执行流程,使错误难以跟踪。
This rule aims to prevent unintended behavior caused by modification or reassignment of function parameters.
该规则旨在避免出现对函数参数的修改或重新赋值造成的非自主行为。
Examples of incorrect code for this rule:
Examples of correct code for this rule:
This rule takes one option, an object, with a boolean property "props" and an array "ignorePropertyModificationsFor" . "props" is false by default. If "props" is set to true , this rule warns against the modification of parameter properties unless they’re included in "ignorePropertyModificationsFor" , which is an empty array by default.
该规则有一个选项,是个对象,其中有一个 "props" 的布尔属性和一个数组属性 "ignorePropertyModificationsFor" 。 "props" 默认为 false 。如果 "props" 设置为 true ,对参数的任何属性的修改,该规则都将发出警告, 除非在 "ignorePropertyModificationsFor" (默认为空数组) 有该参数。
Examples of correct code for the default { "props": false } option:
默认选项 { "props": false } 的 正确 代码示例:
Examples of incorrect code for the { "props": true } option:
选项 { "props": true } 的 错误 代码示例:
Examples of correct code for the { "props": true } option with "ignorePropertyModificationsFor" set:
选项 { "props": true } 并设置了 "ignorePropertyModificationsFor" 的 正确 代码示例:
If you want to allow assignment to function parameters, then you can safely disable this rule.
如果你想允许对函数参数重新赋值,你可以禁用此规则。
This rule was introduced in ESLint 0.18.0.
该规则在 ESLint 0.18.0 中被引入。
Diagnostic Category: lint/style/noParameterAssign
Disallow reassigning function parameters.
Assignment to a function parameters can be misleading and confusing, as modifying parameters will also mutate the arguments object. It is often unintended and indicative of a programmer error.
In contrast to the ESLint rule, this rule cannot be configured to report assignments to a property of a parameter.
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help.
In the following example, if no value is provided for b when multiply is called, b 's value would be undefined when evaluating a * b and multiply would return NaN .
In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined . In the following example, b is set to 1 if multiply is called with only one argument:
With default parameters, checks in the function body are no longer necessary. Now, you can assign 1 as the default value for b in the function head:
Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.
Note: The first default parameter and all parameters after it will not contribute to the function's length .
The default parameter initializers live in their own scope, which is a parent of the scope created for the function body.
This means that earlier parameters can be referred to in the initializers of later parameters. However, functions and variables declared in the function body cannot be referred to from default value parameter initializers; attempting to do so throws a run-time ReferenceError . This also includes var -declared variables in the function body.
For example, the following function will throw a ReferenceError when invoked, because the default parameter value does not have access to the child scope of the function body:
This function will print the value of the parameter a , because the variable var a is hoisted only to the top of the scope created for the function body, not the parent scope created for the parameter list, so its value is not visible to b .
In the second call in this example, even if the first argument is set explicitly to undefined (though not null or other falsy values), the value of the num argument is still the default.
The default argument is evaluated at call time . Unlike with Python (for example), a new object is created each time the function is called.
This even applies to functions and variables:
Parameters defined earlier (to the left) are available to later default parameters:
This functionality can be approximated like this, which demonstrates how many edge cases are handled:
You can use default value assignment with the destructuring assignment syntax.
A common way of doing that is to set an empty object/array as the default value for the destructured parameter; for example: [x = 1, y = 2] = [] . This makes it possible to pass nothing to the function and still have those values prefilled:
Specification |
---|
The two most used data structures in JavaScript are Object and Array .
However, when we pass these to a function, we may not need all of it. The function might only require certain elements or properties.
Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.
Destructuring also works well with complex functions that have a lot of parameters, default values, and so on. Soon we’ll see that.
Here’s an example of how an array is destructured into variables:
Now we can work with variables instead of array members.
It looks great when combined with split or other array-returning methods:
As you can see, the syntax is simple. There are several peculiar details though. Let’s see more examples to understand it better.
It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. However, the array itself is not modified.
It’s just a shorter way to write:
Unwanted elements of the array can also be thrown away via an extra comma:
In the code above, the second element of the array is skipped, the third one is assigned to title , and the rest of the array items are also skipped (as there are no variables for them).
…Actually, we can use it with any iterable, not only arrays:
That works, because internally a destructuring assignment works by iterating over the right value. It’s a kind of syntax sugar for calling for..of over the value to the right of = and assigning the values.
We can use any “assignables” on the left side.
For instance, an object property:
In the previous chapter, we saw the Object.entries(obj) method.
We can use it with destructuring to loop over the keys-and-values of an object:
The similar code for a Map is simpler, as it’s iterable:
There’s a well-known trick for swapping values of two variables using a destructuring assignment:
Here we create a temporary array of two variables and immediately destructure it in swapped order.
We can swap more than two variables this way.
Usually, if the array is longer than the list at the left, the “extra” items are omitted.
For example, here only two items are taken, and the rest is just ignored:
If we’d like also to gather all that follows – we can add one more parameter that gets “the rest” using three dots "..." :
The value of rest is the array of the remaining array elements.
We can use any other variable name in place of rest , just make sure it has three dots before it and goes last in the destructuring assignment.
If the array is shorter than the list of variables on the left, there will be no errors. Absent values are considered undefined:
If we want a “default” value to replace the missing one, we can provide it using = :
Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.
For instance, here we use the prompt function for two defaults:
Please note: the prompt will run only for the missing value ( surname ).
The destructuring assignment also works with objects.
The basic syntax is:
We should have an existing object on the right side, that we want to split into variables. The left side contains an object-like “pattern” for corresponding properties. In the simplest case, that’s a list of variable names in {...} .
For instance:
Properties options.title , options.width and options.height are assigned to the corresponding variables.
The order does not matter. This works too:
The pattern on the left side may be more complex and specify the mapping between properties and variables.
If we want to assign a property to a variable with another name, for instance, make options.width go into the variable named w , then we can set the variable name using a colon:
The colon shows “what : goes where”. In the example above the property width goes to w , property height goes to h , and title is assigned to the same name.
For potentially missing properties we can set default values using "=" , like this:
Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided.
In the code below prompt asks for width , but not for title :
We also can combine both the colon and equality:
If we have a complex object with many properties, we can extract only what we need:
What if the object has more properties than we have variables? Can we take some and then assign the “rest” somewhere?
We can use the rest pattern, just like we did with arrays. It’s not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones.
It looks like this:
In the examples above variables were declared right in the assignment: let {…} = {…} . Of course, we could use existing variables too, without let . But there’s a catch.
This won’t work:
The problem is that JavaScript treats {...} in the main code flow (not inside another expression) as a code block. Such code blocks can be used to group statements, like this:
So here JavaScript assumes that we have a code block, that’s why there’s an error. We want destructuring instead.
To show JavaScript that it’s not a code block, we can wrap the expression in parentheses (...) :
If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.
In the code below options has another object in the property size and an array in the property items . The pattern on the left side of the assignment has the same structure to extract values from them:
All properties of options object except extra which is absent in the left part, are assigned to corresponding variables:
Finally, we have width , height , item1 , item2 and title from the default value.
Note that there are no variables for size and items , as we take their content instead.
There are times when a function has many parameters, most of which are optional. That’s especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, an item list and so on.
Here’s a bad way to write such a function:
In real-life, the problem is how to remember the order of arguments. Usually, IDEs try to help us, especially if the code is well-documented, but still… Another problem is how to call a function when most parameters are ok by default.
That’s ugly. And becomes unreadable when we deal with more parameters.
Destructuring comes to the rescue!
We can pass parameters as an object, and the function immediately destructurizes them into variables:
We can also use more complex destructuring with nested objects and colon mappings:
The full syntax is the same as for a destructuring assignment:
Then, for an object of parameters, there will be a variable varName for the property incomingProperty , with defaultValue by default.
Please note that such destructuring assumes that showMenu() does have an argument. If we want all values by default, then we should specify an empty object:
We can fix this by making {} the default value for the whole object of parameters:
In the code above, the whole arguments object is {} by default, so there’s always something to destructurize.
Destructuring assignment allows for instantly mapping an object or array onto many variables.
The full object syntax:
This means that property prop should go into the variable varName and, if no such property exists, then the default value should be used.
Object properties that have no mapping are copied to the rest object.
The full array syntax:
The first item goes to item1 ; the second goes into item2 , and all the rest makes the array rest .
It’s possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one.
We have an object:
Write the destructuring assignment that reads:
Here’s an example of the values after your assignment:
There is a salaries object:
Create the function topSalary(salaries) that returns the name of the top-paid person.
P.S. Use Object.entries and destructuring to iterate over key/value pairs.
Open a sandbox with tests.
Open the solution with tests in a sandbox.
Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Today I had a dicussion with a colleague.
I tend to believe that a value in a property should be a meaningful part of the state of an object at any given time. This automatically almost always makes the constructor fully responsible for the initial assignment of all the properties in a class. Other methods may subsequently change the state to another valid state, but it is usually not their task to initialize values on class properties.
My colleague believes that class properties may also be useful to increase readability by decreasing the parameter count of internal private functions. Class properties are then used as temporary variables, potentially used by multiple private functions.
My way (php code example - I left out the private method declarations):
Colleague's way
To me, there is a pretty clear distinction as to when one should assign a value to a class property and when values should be parameterized. I do not see them as immediate alternatives to each other. It is confusing to me to see variables that live longer than the execution of the method to which they belong. The necessity for these variables to exist as class properties when they are used in private methods seems to create a temporal coupling.
Do any guidelines exist on this matter? Or is it a matter of style? And does it matter if the object does not live very long and has only few public methods? To clarify: as seen from the outside, the class works correctly.
Nope. Your way is better.
Here's why: the variables are properly confined to only the scope in which they are used. While your colleague's way will work perfectly fine, it will add cognitive dissonance (even if it's only a small amount) to the programmer coming after him, who will read the code and have to figure out why there are what amounts to "global variables" within the class. Are they used anywhere else? What will happen if I change one of them? And so forth.
My colleague believes that class properties may also be useful to increase readability by decreasing the parameter count of internal private functions.
Decreasing the number of parameters does not necessarily make code more readable.
When working with a function or method, it is critical to know what its inputs and outputs are. Your colleague's approach makes it difficult to tell and impossible to tell from the function's prototype.
Also, if your code executes on more than one thread, member-scoped variables can be a problem because object instances are held in the same heap that is used by all threads. This differs from local variables which are held on a thread-specific stack. Heap variables run the risk of contamination from other threads of execution, while stack variables are much safer.
That being said, there may be some cases where very complicated functions with many working variables/logical parts/recursion/repetition where you find you are passing around a ridiculous amount of stuff. In those cases there are a couple patterns that may assist, and these could use member variables as your colleague prefers. Here are two I can think of:
Turn the method into its own object so that all the local variables become fields on that object. You can then decompose the method into other methods on the same object.
E.g. let's say you need to do a Diffie-Helman key exchange. This algorithm has a lot of working variables and maybe it's a pain to pass them all around, so you want them declared at a member level.
The class name will often end with "-er" because it is associated with an action, not an item.
All the member variables are created just for the task and then erased when the task is done.
There is only one public method.
You don't keep it around very long. Create it, get what you want, dispose of it.
Problem: You get several values from an object and then pass them as parameters to a method. Instead, try passing the whole object.
With this pattern, you manage a large set of parameters by removing them from the argument list and replacing them with a single "parameter object." The object has one property for each of the parameters. If the function needs to pass parameters to yet another function, it can pass along the whole object instead of passing the parameters one by one.
This is sort of what your colleague is advocating, but instead of storing the working variables in the same object, they're stored in an object dedicated to handling the state of the parameters.
Some benefits:
Since objects are always passed by reference (in a sense), changes made to the parameter object's members will be available to any subfunctions that receive the parameter object as an argument.
With this pattern it is still somewhat clear what the inputs and outputs are
This pattern provides a way to distinguish between working variables (which are stored in the parameter object being passed) and bone fide state variables (which are stored in the object that contains the function that is being executed).
This pattern is more resilient to multithreading concerns, because each thread can have its own copy of the parameter object.
I can tell you from first hand experience that your coworker's method becomes an unmaintainable mess. Any time you have a non-obvious call order dependency it's going to eventually cause a bug.
Let's say someone later needs to modify doSomething() to use another value:
Is the bug obvious?
With your method it would be much clearer:
I'm not familiar with PHP, but in many programming languages this would generate a warning or error due to using $value4 before declaring it.
Or, even worse - what if someone did this:
Now the code becomes incredibly hard to read and understand. You start getting very different behavior based on the call order of multiple methods.
Reminder: Answers generated by artificial intelligence tools are not allowed on Software Engineering Stack Exchange. Learn more
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
Disallows reassignment of function parameters.
Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object. Often, assignment to function parameters is unintended and indicative of a mistake or programmer error.
This rule can be also configured to fail when function parameters are modified. Side effects on parameters can cause counter-intuitive execution flow and make errors difficult to track down.
This rule aims to prevent unintended behavior caused by modification or reassignment of function parameters.
Examples of incorrect code for this rule:
Examples of correct code for this rule:
This rule takes one option, an object, with a boolean property "props" , and arrays "ignorePropertyModificationsFor" and "ignorePropertyModificationsForRegex" . "props" is false by default. If "props" is set to true , this rule warns against the modification of parameter properties unless they're included in "ignorePropertyModificationsFor" or "ignorePropertyModificationsForRegex" , which is an empty array by default.
Examples of correct code for the default { "props": false } option:
Examples of incorrect code for the { "props": true } option:
Examples of correct code for the { "props": true } option with "ignorePropertyModificationsFor" set:
Examples of correct code for the { "props": true } option with "ignorePropertyModificationsForRegex" set:
If you want to allow assignment to function parameters, then you can safely disable this rule.
This rule was introduced in ESLint 0.18.0.
在airbnb的eslint规则中,有这样一条规则 no-param-reassign
目的是提醒你不要直接修改函数的入参。因为假如入参是一个对象,修改入参可能会导致对象的属性被覆盖。
但有一些情况下,我们必须要这样做,比如在 vuex 中
其实,不仅仅是vuex,再比如express的 req res ,前端事件处理的 e.returnvalue 都需要直接给入参赋值。这时候我们显然不希望直接disable掉这条规则,或者在发生冲突的代码处单独disable。
这时候可以使用 ignorePropertyModificationsFor 这个属性,他可以为这个规则添加一个白名单,即指定的入参名称不予限制。看代码就明白了:
如上代码配置即可避免vuex与eslint的冲突。
请填写红包祝福语或标题
1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。
This subreddit is for anyone who wants to learn JavaScript or help others do so. Questions and posts about frontend development in general are welcome, as are all posts pertaining to JavaScript on the backend.
I started learning javascript a week ago. Started using eslint yesterday and it's very useful. I have been trying this part of the code for sometime now and eslint keeps throwing Assignment to property of function parameter 'element'. Here is the code;
Before this I was doing something like this;
I know eslint isn't showing error for nothing so I would like to know what's reason and how it should be done.
And I have another eventListner with same pattern but that changes the opacity to 0 and pointerEvents to 'none'. So is there a way to do that using ternary operator or should I just stick to if else for that?Thanks and lemme know if there anything else I can improve.
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
Hello I have a problem in my estlint:
Assignment to property of function parameter 'state'. eslintno-param-reassign
on this code:
state.sideisOpen = action.payload;
Please try to edit your .eslintrc file to make the rule less strict for your case:
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
COMMENTS
function createEmployee(emp) { // ⛔️ Assignment to property of function parameter 'emp'. eslint no-param-reassign. emp.name = 'bobby hadz'; emp.salary = 500; return emp; } The ESLint rule forbids assignment to function parameters because modifying a function's parameters also mutates the arguments object and can lead to confusing behavior.
10. This is a common ESLint issue that appears frequently on old codebase. You have modified the result variable which was passed as parameter. This behavior is prohibited by the rule. To resolve it, copy the argument to a temporary variable and work on it instead: export const fn = article => article.categoryValueDtoSet.reduce((res, item) => {.
You can use assignment to property of function parameter to pass a reference to an object. For example, the following code passes a reference to the `person` object to the `greet` function: js function greet (person) { console.log (`Hello, $ {person.name}`); } const person = { name: "John Doe" };
If you want to allow assignment to function parameters, then you can safely disable this rule. Strict mode code doesn't sync indices of the arguments object with each parameter binding. Therefore, this rule is not necessary to protect against arguments object mutation in ESM modules or other strict mode functions. Version
Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, ... This rule takes one option, an object, with a boolean property "props", ... If you want to allow assignment to function parameters, then you can safely disable this rule. Version.
We can go one step further and actually use destructuring assignments right in the function's parameters: And if we don't like the (purposefully vague) parameter names, we can always rename them!
Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object ...
The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value. Changes to arguments are not visible (reflected) outside the function.
Disallow Reassignment of Function Parameters (no-param-reassign) Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object.
Disallow Reassignment of Function Parameters (no-param-reassign) 禁止对函数参数再赋值 (no-param-reassign) Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object. Often, assignment to function parameters is ...
Disallow reassigning function parameters. Assignment to a function parameters can be misleading and confusing ... In contrast to the ESLint rule, this rule cannot be configured to report assignments to a property of a parameter. Examples Section titled Examples. Invalid Section titled Invalid.
In JavaScript, function parameters default to undefined. However, it's often useful to set a different default value. This is where default parameters can help. In the following example, if no value is provided for b when multiply is called, b 's value would be undefined when evaluating a * b and multiply would return NaN. js.
Smart function parameters. There are times when a function has many parameters, most of which are optional. That's especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, an item list and so on. Here's a bad way to write such a function:
With this pattern, you manage a large set of parameters by removing them from the argument list and replacing them with a single "parameter object." The object has one property for each of the parameters. If the function needs to pass parameters to yet another function, it can pass along the whole object instead of passing the parameters one by ...
Side effects on parameters can cause counter-intuitive execution flow and make errors difficult to track down. Rule Details. This rule aims to prevent unintended behavior caused by modification or reassignment of function parameters. Examples of incorrect code for this rule: /*eslint no-param-reassign: "error"*/ function foo (bar) { bar = 13 ...
优雅解决: assignment to property of function parameter 'state'. 在airbnb的 eslint 规则中,有这样一条规则 no-param-reassign. 目的是提醒你不要直接修改函数的入参。. 因为假如入参是一个对象,修改入参可能会导致对象的属性被覆盖。. obj.key = 1; // 可能对象本身就用key的 ...
Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Visit the blog
I started learning javascript a week ago. Started using eslint yesterday and it's very useful. I have been trying this part of the code for sometime now and eslint keeps throwing Assignment to property of function parameter 'element'. Here is the code;
Hello I have a problem in my estlint: Assignment to property of function parameter 'state'. eslintno-param-reassign on this code: state.sideisOpen = action.payload; interface SideBar {