• Assignment to property of function parameter no-param-reassign

avatar

Last updated: Mar 7, 2024 Reading time · 3 min

banner

# Table of Contents

  • Disabling the no-param-reassign ESLint rule for a single line
  • Disabling the no-param-reassign ESLint rule for an entire file
  • Disabling the no-param-reassign ESLint rule globally

# Assignment to property of function parameter no-param-reassign

The ESLint error "Assignment to property of function parameter 'X' eslint no-param-reassign" occurs when you try to assign a property to a function parameter.

To solve the error, disable the ESLint rule or create a new object based on the parameter to which you can assign properties.

assignment to property of function parameter eslint no param reassign

Here is an example of how the error occurs.

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.

One way to resolve the issue is to create a new object to which you can assign properties.

We used the spread syntax (...) to unpack the properties of the function parameter into a new object to which we can assign properties.

If you need to unpack an array, use the following syntax instead.

The same approach can be used if you simply need to assign the function parameter to a variable so you can mutate it.

We declared the bar variable using the let keyword and set it to the value of the foo parameter.

We are then able to reassign the bar variable without any issues.

# Disabling the no-param-reassign ESLint rule for a single line

You can use a comment if you want to disable the no-param-reassign ESLint rule for a single line.

Make sure to add the comment directly above the assignment that causes the error.

# Disabling the no-param-reassign ESLint rule for an entire file

You can also use a comment to disable the no-param-reassign ESLint rule for an entire file.

Make sure to add the comment at the top of the file or at least above the function in which you reassign parameters.

The same approach can be used to disable the rule only for a single function.

The first comment disables the no-param-reassign rule and the second comment enables it.

If you try to reassign a parameter after the second comment, you will get an ESLint error.

# Disabling the no-param-reassign ESLint rule globally

If you need to disable the no-param-reassign rule globally, you have to edit your .eslintrc.js file.

disable no param reassign rule globally

If you only want to be able to assign properties to an object parameter, set props to false instead of disabling the rule completely.

The following code is valid after making the change.

If you use a .eslintrc or .eslintrc.json file, make sure to double-quote the properties and values.

If you want to only allow assignment to object parameters, use the following line instead.

Make sure all properties are double-quoted and there are no trailing commas if your config is written in JSON.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • eslint is not recognized as an internal or external command
  • Plugin "react" was conflicted between package.json » eslint-config-react-app
  • React: Unexpected use of 'X' no-restricted-globals in ESLint
  • TypeScript ESLint: Unsafe assignment of an any value [Fix]
  • ESLint error Unary operator '++' used no-plusplus [Solved]
  • ESLint Prefer default export import/prefer-default-export
  • Arrow function should not return assignment. eslint no-return-assign
  • TypeError: Cannot redefine property: X in JavaScript [Fixed]
  • ESLint: disable multiple rules or a rule for multiple lines
  • Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style
  • Missing return type on function TypeScript ESLint error

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

HatchJS Logo

HatchJS.com

Cracking the Shell of Mystery

How to Assign to the Property of a Function Parameter in JavaScript

Avatar

Assignment to Property of Function Parameter

One of the most powerful features of JavaScript is the ability to assign values to the properties of function parameters. This can be used to create complex and dynamic code that can be easily modified.

In this article, we will take a closer look at assignment to property of function parameter. We will discuss what it is, how it works, and how it can be used to improve your code.

We will also provide some examples of how assignment to property of function parameter can be used in practice. By the end of this article, you will have a solid understanding of this important JavaScript concept.

Property Value Example
name “John Doe” function greet(name) {
console.log(`Hello, ${name}`);
}

greet(“John Doe”);

age 25 function calculateAge(birthdate) {
const today = new Date();
const age = today.getFullYear() – birthdate.getFullYear();
return age;
}

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:

  • Initialize the value of a parameter
  • Pass a reference to an object

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

  • [MDN: Assignment to property of function parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Assignment_to_property_of_function_parameter)
  • [Stack Overflow: When to use assignment to property of function parameter?](https://stackoverflow.com/questions/1435573/when-to-use-assignment-to-property-of-function-parameter)
  • [Codecademy: Assignment to property of function parameter](https://www.codecademy.com/learn/javascript/lessons/assignment-to-property-of-function-parameter)

3. How to use assignment to property of function parameter?

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.

4. Pitfalls of assignment to property of function parameter

There are a few pitfalls to be aware of when using assignment to property of function parameter:

  • The value of the property may be overwritten. If you assign a value to the property of a function parameter, the value of the property may be overwritten by the next time the function is called. For example, the following code assigns the value `”hello”` to the `name` property of the `greet` function parameter. The next time the `greet` function is called, the value of the `name` property will be overwritten by the value of the `name` argument.

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:

  • Use the `const` keyword to declare function parameters as constants.
  • Use the `readonly` keyword to declare function parameters as read-only.
  • Use the `Object.freeze()` method to freeze objects that are passed as function parameters.

Here are some key takeaways from this article:

  • Assigning to the property of a function parameter can change the value of the original variable.
  • This can lead to unexpected behavior and security vulnerabilities.
  • To avoid this problem, use the `const` keyword or pass arguments by reference.

By following these tips, you can write more secure and reliable JavaScript code.

Author Profile

Marcus Greenwood

Latest entries

  • December 26, 2023 Error Fixing User: Anonymous is not authorized to perform: execute-api:invoke on resource: How to fix this error
  • December 26, 2023 How To Guides Valid Intents Must Be Provided for the Client: Why It’s Important and How to Do It
  • December 26, 2023 Error Fixing How to Fix the The Root Filesystem Requires a Manual fsck Error
  • December 26, 2023 Troubleshooting How to Fix the `sed unterminated s` Command

Similar Posts

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…

Java 9 Module System: Why java.base Does Not Open java.lang to Unnamed Modules

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…

NextJS 13 Project Structure: A Guide to Building Modern React Apps

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…

How to Convert a String to an Integer Array in Java

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: Answer from Java side is empty

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…

How to Fix the Execution Failed for Task CompileJava Error

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…

no-param-reassign

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.

Rule Details

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:

When Not To Use It

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.

Further Reading

JavaScript: Don’t Reassign Your Function Arguments

  • Rule source
  • Tests source

© OpenJS Foundation and other contributors Licensed under the MIT License. https://eslint.org/docs/latest/rules/no-param-reassign

JS Tutorial

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).

Function Parameters and 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.

Parameter Rules

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.

Default Parameters

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:

Default Parameter Values

ES6 allows function parameters to have default values.

If y is not passed or undefined, then y = 10.

Function Rest Parameter

The rest parameter (...) allows a function to treat an indefinite number of arguments as an array:

Advertisement

The Arguments Object

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 .

Arguments are Passed by Value

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.

Objects are Passed by Reference

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.

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

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 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.

当函数参数被修改时,该规则也可能会失效。由此造成的副作用可能导致不直观的执行流程,使错误难以跟踪。

Rule Details

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" 的 正确 代码示例:

When Not To Use It

If you want to allow assignment to function parameters, then you can safely disable this rule.

如果你想允许对函数参数重新赋值,你可以禁用此规则。

Further Reading

  • JavaScript: Don’t Reassign Your Function Arguments

This rule was introduced in ESLint 0.18.0.

该规则在 ESLint 0.18.0 中被引入。

  • Rule source
  • Documentation source

noParameterAssign (since v1.0.0)

Diagnostic Category: lint/style/noParameterAssign

  • Same as: no-param-reassign

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.

Related links

  • Disable a rule
  • Configure the rule fix
  • Rule options
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Default parameters

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

Description

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 .

Passing undefined vs. other falsy values

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.

Evaluated at call time

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:

Earlier parameters are available to later default parameters

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:

Destructured parameter with default value assignment

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:

Specifications

Specification

Destructuring assignment

The two most used data structures in JavaScript are Object and Array .

  • Objects allow us to create a single entity that stores data items by key.
  • Arrays allow us to gather data items into an ordered list.

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.

Array destructuring

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.

The rest ‘…’

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.

Default values

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 ).

Object destructuring

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:

The rest pattern “…”

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 (...) :

Nested destructuring

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.

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:

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:

  • name property into the variable name .
  • years property into the variable age .
  • isAdmin property into the variable isAdmin (false, if no such property)

Here’s an example of the values after your assignment:

The maximal salary

There is a salaries object:

Create the function topSalary(salaries) that returns the name of the top-paid person.

  • If salaries is empty, it should return null .
  • If there are multiple top-paid persons, return any of them.

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.

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

Stack Exchange Network

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.

Parameterizing vs property assignment

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.

  • object-oriented

user2180613's user avatar

  • 10 Oooo, look. All the fun of global variables in a slightly smaller scope. –  Becuzz Commented Oct 24, 2016 at 14:35
  • "Increase readability" by making the code harder to understand and not having all related information in one place? That doesn't make sense. –  user82096 Commented Oct 24, 2016 at 14:37
  • @dan1111: Historically, it was customary to put all of your variables at the top of the class/module/whatever. Basically, they're all in one place, so there is some logic behind the practice. –  Robert Harvey Commented Oct 24, 2016 at 14:40

3 Answers 3

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.

Robert Harvey's user avatar

  • 1 Yes! Emphasis on this: the variables are properly confined to only the scope in which they are used. Setting properties and using them in your methods isn't bad in and of itself. It's bad when those properties are not valuable to the object itself, or if they're not actually properties of the object. –  svidgen Commented Oct 24, 2016 at 15:11

Your colleague is wrong

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.

OK, maybe he's right, but only sometimes

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:

Method Object

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.

Preserve whole object

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.

John Wu's user avatar

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.

17 of 26's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Software Engineering Stack Exchange. Learn more

Sign up or log in

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 .

Not the answer you're looking for? Browse other questions tagged object-oriented or ask your own question .

  • The Overflow Blog
  • Community Products Roadmap Update, July 2024
  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...

Hot Network Questions

  • Family reunion crossword: The case of the missing letters
  • When do people say "Toiletten" in the plural?
  • How do I drill a 60cm hole in a tree stump, 4.4 cm wide?
  • What spells can I cast while swallowed?
  • Has the Supreme Court given any examples where presumptive immunity would be overcome?
  • What is the reason for using decibels to measure sound?
  • It was the second, but we were told it was the fifth
  • Fontspec and \readline produce trailing blank symbol
  • Can you be charged with breaking and entering if the door was open, and the owner of the property is deceased?
  • Why was this a draw? What move I supposed to play to win?
  • Is "able to find related code by searching keyword 'MyClass '(variable declaration)" a reason to avoid using auto in c++?
  • Do you always experience the gravitational influence of other mass as you see them in your frame?
  • Uniqueness of proofs for inductively defined predicates
  • Confusion on defining uniform distribution on hypersphere and its sampling problem
  • Best way to deny .php in URLs while keeping access to those files through other URLs?
  • Any alternative to lockdown browser?
  • Optimizing Pi Estimation Code
  • Were there any stone vessels (including mortars) made in Paleolithic?
  • Is the proposed solar sailing race course possible?
  • How to see what statement (memory address) my program is currently running: the program counter register, through Linux commands?
  • Does installing Ubuntu Deskto on Xubuntu LTS adopt the longer Ubuntu support period
  • Transferring at JFK: How is passport checked if flights arrive at/depart from adjacent gates?
  • Is there a way to change a cantrip spell type to Necromancy in order to fulfil the requirement of the Death Domain Reaper ability for Clerics?
  • Improve spacing around equality = and other math relation symbols

assignment to property of function parameter 'params'

no-param-reassign

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.

Rule Details

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:

When Not To Use It

If you want to allow assignment to function parameters, then you can safely disable this rule.

Further Reading

  • https://spin.atomicobject.com/2011/04/10/javascript-don-t-reassign-your-function-arguments/

This rule was introduced in ESLint 0.18.0.

  • Rule source
  • Test source
  • Documentation source

优雅解决: assignment to property of function parameter ‘state‘

assignment to property of function parameter 'params'

在airbnb的eslint规则中,有这样一条规则 no-param-reassign

目的是提醒你不要直接修改函数的入参。因为假如入参是一个对象,修改入参可能会导致对象的属性被覆盖。

但有一些情况下,我们必须要这样做,比如在 vuex 中

其实,不仅仅是vuex,再比如express的 req res ,前端事件处理的 e.returnvalue 都需要直接给入参赋值。这时候我们显然不希望直接disable掉这条规则,或者在发生冲突的代码处单独disable。

这时候可以使用 ignorePropertyModificationsFor 这个属性,他可以为这个规则添加一个白名单,即指定的入参名称不予限制。看代码就明白了:

如上代码配置即可避免vuex与eslint的冲突。

assignment to property of function parameter 'params'

“相关推荐”对你有帮助么?

assignment to property of function parameter 'params'

请填写红包祝福语或标题

assignment to property of function parameter 'params'

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

assignment to property of function parameter 'params'

Get the Reddit app

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.

Why eslint throws "Assignment to property of function parameter 'element'." for this?

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.

  • 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

Collectives™ on Stack Overflow

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.

TypeScript and redux tool kit , createSlice: Assignment to property of function parameter 'state'

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;

gabriel 's user avatar

Please try to edit your .eslintrc file to make the rule less strict for your case:

Eugene Karataev's user avatar

  • is it possible to fix the error without placing this rule? –  gabriel Commented May 3, 2020 at 9:48
  • I think it's not possible, but please let SO community know if you find a solution. –  Eugene Karataev Commented May 3, 2020 at 14:17
  • Oddly, this solution worked if I was only modifying an existing array element (e.g. state[someIndex] = action.payload ), but did NOT work when adding new elements (e.g. state = [...state, action.payload] ). I tried using ignorePropertyModificationsForRegex and setting props: false , but I eventually just had to set this rule to off completely. :/ –  morphatic Commented May 3, 2020 at 16:58

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

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 .

Not the answer you're looking for? Browse other questions tagged typescript redux or ask your own question .

  • The Overflow Blog
  • Community Products Roadmap Update, July 2024
  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Tour de France General Classification time
  • Could two moons orbit each other around a planet?
  • Two definitions of a monad on an ∞-category
  • Reversing vowels in a string
  • How close would a quasar have to be to be seen with the naked eye?
  • Does Justice Sotomayor's "Seal Team 6" example, in and of itself, explicitly give the President the authority to execute opponents? If not, why not?
  • As an advisor, how can I help students with time management and procrastination?
  • 11 trees in 6 rows with 4 trees in each row
  • Why did the main wire to my apartment burn before the breaker tripped?
  • Sort Number Array
  • Is the proposed solar sailing race course possible?
  • Can the US president legally kill at will?
  • Is "able to find related code by searching keyword 'MyClass '(variable declaration)" a reason to avoid using auto in c++?
  • Setting Stack Pointer on Bare Metal Rust
  • When do people say "Toiletten" in the plural?
  • Why is there not a test for diagonalizability of a matrix
  • Transferring at JFK: How is passport checked if flights arrive at/depart from adjacent gates?
  • Seeing perfectly camouflaged objects
  • When can まで mean "only"?
  • Any alternative to lockdown browser?
  • Strange Interaction with Professor
  • 为什么字形不同的两个字「骨」的编码相同(从而是一个字)?
  • Confusion on defining uniform distribution on hypersphere and its sampling problem
  • Fontspec and \readline produce trailing blank symbol

assignment to property of function parameter 'params'

COMMENTS

  1. Assignment to property of function parameter no-param-reassign

    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.

  2. Assignment to property of function parameter (no-param-reassign)

    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) => {.

  3. How to Assign to the Property of a Function Parameter in JavaScript

    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" };

  4. no-param-reassign

    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

  5. No-param-reassign

    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.

  6. JavaScript: Use Destructuring Assignment over Function Parameters

    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!

  7. Destructuring assignment

    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 ...

  8. JavaScript Function Parameters

    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.

  9. no-param-reassign

    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.

  10. no-param-reassign

    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 ...

  11. noParameterAssign (since v1.0.0)

    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.

  12. Default parameters

    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.

  13. Destructuring assignment

    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:

  14. object oriented

    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 ...

  15. no-param-reassign

    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 ...

  16. 优雅解决: assignment to property of function parameter 'state'

    优雅解决: assignment to property of function parameter 'state'. 在airbnb的 eslint 规则中,有这样一条规则 no-param-reassign. 目的是提醒你不要直接修改函数的入参。. 因为假如入参是一个对象,修改入参可能会导致对象的属性被覆盖。. obj.key = 1; // 可能对象本身就用key的 ...

  17. How to solve this assignment to property of function parameter

    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

  18. Why eslint throws "Assignment to property of function parameter

    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;

  19. TypeScript and redux tool kit , createSlice: Assignment to property of

    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 {