• 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 illegal character `\ufeff`.

Java Illegal Character \uFEFF: What It Is and How to Fix It Have you ever seen a strange character in your Java code, like `\uFEFF`? This character is called the Unicode byte order mark (BOM), and it can cause problems if it’s not properly handled. In this article, we’ll explain what the BOM is, why…

How to Convert a Long to an Int in Java

**Converting a long to an int in Java** Java’s `long` and `int` data types are both integers, but they have different ranges. A `long` can store values from -2^63 to 2^63-1, while an `int` can only store values from -2^31 to 2^31-1. This means that if you have a `long` value that is outside the…

How to Swap Two Variables in JavaScript

Swapping two variables in JavaScript In JavaScript, swapping two variables is a common task that can be accomplished in a few different ways. The simplest way is to use the `temp` variable. This involves creating a temporary variable, assigning the value of one variable to it, then assigning the value of the second variable to…

How to Use `from google.colab.output import eval_js` to Run JavaScript in Google Colab

Google Colab is a free, interactive Jupyter notebook environment that runs in the cloud. You can use it to run Python code, import libraries, and visualize data. One of the most powerful features of Google Colab is the ability to run JavaScript code. This can be done using the `eval_js()` function. The `eval_js()` function takes…

Java SQL RecoverableException: No more data to read from socket

Java.SQL.SQLRecoverableException: No More Data to Read from Socket Have you ever been working on a Java application that suddenly throws a java.sql.SQLRecoverableException: No More Data to Read from Socket? If so, you’re not alone. This is a common error that can occur when there is a problem with the network connection between your application and…

Exception in Thread main java.util.UnknownFormatConversionException: Conversion

Exception in Thread Main: Java Util UnknownFormatConversionException Conversion Have you ever been working on a Java program and suddenly been hit with the dreaded `java.util.UnknownFormatConversionException`? This exception can be a real pain to debug, as it can be difficult to figure out what exactly went wrong. In this article, we’ll take a look at what…

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 when not in strict mode (see When Not To Use It below). 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.

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.

This rule was introduced in ESLint v0.18.0.

Further Reading

Avatar image for spin.atomicobject.com

  • Rule source
  • Tests source

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

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

  • JavaScript: Don’t Reassign Your Function Arguments

This rule was introduced in ESLint 0.18.0.

  • Rule source
  • Documentation source

© OpenJS Foundation and other contributors Licensed under the MIT License. https://eslint.org/docs/rules/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. 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 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.

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:

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.

  • Rule source
  • Documentation source
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

TypeError: invalid assignment to const "x"

The JavaScript exception "invalid assignment to const" occurs when it was attempted to alter a constant value. JavaScript const declarations can't be re-assigned or redeclared.

What went wrong?

A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In JavaScript, constants are declared using the const keyword.

Invalid redeclaration

Assigning a value to the same constant name in the same block-scope will throw.

Fixing the error

There are multiple options to fix this error. Check what was intended to be achieved with the constant in question.

If you meant to declare another constant, pick another name and re-name. This constant name is already taken in this scope.

const, let or var?

Do not use const if you weren't meaning to declare a constant. Maybe you meant to declare a block-scoped variable with let or global variable with var .

Check if you are in the correct scope. Should this constant appear in this scope or was it meant to appear in a function, for example?

const and immutability

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable:

But you can mutate the properties in a variable:

Was this page helpful?

Type Compatibility

Type compatibility in TypeScript is based on structural subtyping. Structural typing is a way of relating types based solely on their members. This is in contrast with nominal typing. Consider the following code:

In nominally-typed languages like C# or Java, the equivalent code would be an error because the Dog class does not explicitly describe itself as being an implementer of the Pet interface.

TypeScript’s structural type system was designed based on how JavaScript code is typically written. Because JavaScript widely uses anonymous objects like function expressions and object literals, it’s much more natural to represent the kinds of relationships found in JavaScript libraries with a structural type system instead of a nominal one.

A Note on Soundness

TypeScript’s type system allows certain operations that can’t be known at compile-time to be safe. When a type system has this property, it is said to not be “sound”. The places where TypeScript allows unsound behavior were carefully considered, and throughout this document we’ll explain where these happen and the motivating scenarios behind them.

Starting out

The basic rule for TypeScript’s structural type system is that x is compatible with y if y has at least the same members as x . For example consider the following code involving an interface named Pet which has a name property:

To check whether dog can be assigned to pet , the compiler checks each property of pet to find a corresponding compatible property in dog . In this case, dog must have a member called name that is a string. It does, so the assignment is allowed.

The same rule for assignment is used when checking function call arguments:

Note that dog has an extra owner property, but this does not create an error. Only members of the target type ( Pet in this case) are considered when checking for compatibility. This comparison process proceeds recursively, exploring the type of each member and sub-member.

Be aware, however, that object literals may only specify known properties . For example, because we have explicitly specified that dog is of type Pet , the following code is invalid:

Comparing two functions

While comparing primitive types and object types is relatively straightforward, the question of what kinds of functions should be considered compatible is a bit more involved. Let’s start with a basic example of two functions that differ only in their parameter lists:

To check if x is assignable to y , we first look at the parameter list. Each parameter in x must have a corresponding parameter in y with a compatible type. Note that the names of the parameters are not considered, only their types. In this case, every parameter of x has a corresponding compatible parameter in y , so the assignment is allowed.

The second assignment is an error, because y has a required second parameter that x does not have, so the assignment is disallowed.

You may be wondering why we allow ‘discarding’ parameters like in the example y = x . The reason for this assignment to be allowed is that ignoring extra function parameters is actually quite common in JavaScript. For example, Array#forEach provides three parameters to the callback function: the array element, its index, and the containing array. Nevertheless, it’s very useful to provide a callback that only uses the first parameter:

Now let’s look at how return types are treated, using two functions that differ only by their return type:

The type system enforces that the source function’s return type be a subtype of the target type’s return type.

Function Parameter Bivariance

When comparing the types of function parameters, assignment succeeds if either the source parameter is assignable to the target parameter, or vice versa. This is unsound because a caller might end up being given a function that takes a more specialized type, but invokes the function with a less specialized type. In practice, this sort of error is rare, and allowing this enables many common JavaScript patterns. A brief example:

You can have TypeScript raise errors when this happens via the compiler flag strictFunctionTypes .

Optional Parameters and Rest Parameters

When comparing functions for compatibility, optional and required parameters are interchangeable. Extra optional parameters of the source type are not an error, and optional parameters of the target type without corresponding parameters in the source type are not an error.

When a function has a rest parameter, it is treated as if it were an infinite series of optional parameters.

This is unsound from a type system perspective, but from a runtime point of view the idea of an optional parameter is generally not well-enforced since passing undefined in that position is equivalent for most functions.

The motivating example is the common pattern of a function that takes a callback and invokes it with some predictable (to the programmer) but unknown (to the type system) number of arguments:

Functions with overloads

When a function has overloads, each overload in the target type must be matched by a compatible signature on the source type. This ensures that the source function can be called in all the same cases as the target function.

Enums are compatible with numbers, and numbers are compatible with enums. Enum values from different enum types are considered incompatible. For example,

Classes work similarly to object literal types and interfaces with one exception: they have both a static and an instance type. When comparing two objects of a class type, only members of the instance are compared. Static members and constructors do not affect compatibility.

Private and protected members in classes

Private and protected members in a class affect their compatibility. When an instance of a class is checked for compatibility, if the target type contains a private member, then the source type must also contain a private member that originated from the same class. Likewise, the same applies for an instance with a protected member. This allows a class to be assignment compatible with its super class, but not with classes from a different inheritance hierarchy which otherwise have the same shape.

Because TypeScript is a structural type system, type parameters only affect the resulting type when consumed as part of the type of a member. For example,

In the above, x and y are compatible because their structures do not use the type argument in a differentiating way. Changing this example by adding a member to Empty<T> shows how this works:

In this way, a generic type that has its type arguments specified acts just like a non-generic type.

For generic types that do not have their type arguments specified, compatibility is checked by specifying any in place of all unspecified type arguments. The resulting types are then checked for compatibility, just as in the non-generic case.

For example,

Advanced Topics

Subtype vs assignment.

So far, we’ve used “compatible”, which is not a term defined in the language spec. In TypeScript, there are two kinds of compatibility: subtype and assignment. These differ only in that assignment extends subtype compatibility with rules to allow assignment to and from any , and to and from enum with corresponding numeric values.

Different places in the language use one of the two compatibility mechanisms, depending on the situation. For practical purposes, type compatibility is dictated by assignment compatibility, even in the cases of the implements and extends clauses.

any , unknown , object , void , undefined , null , and never assignability

The following table summarizes assignability between some abstract types. Rows indicate what each is assignable to, columns indicate what is assignable to them. A ” ✓ ” indicates a combination that is compatible only when strictNullChecks is off.

any unknown object void undefined null never
any →
unknown →
object →
void →
undefined →
null →
never →

Reiterating The Basics :

  • Everything is assignable to itself.
  • any and unknown are the same in terms of what is assignable to them, different in that unknown is not assignable to anything except any .
  • unknown and never are like inverses of each other. Everything is assignable to unknown , never is assignable to everything. Nothing is assignable to never , unknown is not assignable to anything (except any ).
  • void is not assignable to or from anything, with the following exceptions: any , unknown , never , undefined , and null (if strictNullChecks is off, see table for details).
  • When strictNullChecks is off, null and undefined are similar to never : assignable to most types, most types are not assignable to them. They are assignable to each other.
  • When strictNullChecks is on, null and undefined behave more like void : not assignable to or from anything, except for any , unknown , and void ( undefined is always assignable to void ).

Nightly Builds

How to use a nightly build of TypeScript

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Ryan Cavanaugh  (51)

Last updated: Sep 10, 2024  

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why assignment to property of function parameter is bad style. #1217

@zhaoxiongfei

zhaoxiongfei commented Dec 21, 2016 • edited Loading

req, res, next) => { req.user = Guest; return next(); };

Often used, can not be avoided.
How should I do?

  • 👍 4 reactions

@ljharb

ljharb commented Dec 21, 2016

Since express does require this, you currently can only disable the rule entirely, on a per-file basis, or on a per-line/per-function basis.

eslint has an option proposed to cover this:

Once that's enabled, we'll likely enable it by default to cover , , and .

  • 👍 1 reaction

Sorry, something went wrong.

@ljharb

zhaoxiongfei commented Dec 27, 2016

Thank you sir.

@zhaoxiongfei

ljharb commented Dec 27, 2016

(the question's answered, but reopening to track the eslint rule change)

@felixsanz

felixsanz commented Dec 30, 2016 • edited Loading

You are not reassigning the parameter, you are just creating a property on the object.

Because of this, you can allow it today with .

ljharb commented Dec 30, 2016

Yes, but is something that should be strictly enforced everywhere, where a framework requires it, like express. The rule change would be for , but with exceptions for , etc.

  • 👍 3 reactions
  • 👎 1 reaction

@christianbundy

christianbundy commented Mar 2, 2017

Just a quick update, this has been merged and will be released in the next version of ESLint (which I believe is tomorrow):

@christianbundy

shanev commented Mar 7, 2017

Another example is in Koa routing:

.get('/', (ctx) => { ctx.status = 200; });
  • 👍 5 reactions

ljharb commented Mar 16, 2017

The next release of eslint-config-airbnb-base, and likely eslint-config-airbnb, will include this loosening of no-param-reassign.

  • 🎉 5 reactions

@jbruni

jbruni commented Nov 7, 2017

as " " is ok.

as " " means enforces immutability paradigm. It makes a profound design choice for us.

ljharb commented Nov 7, 2017

Airbnb's config makes many profound design choices for you; that's the point. If you don't agree with them, you can easily override rules and/or fork the guide.

@kholiavko-roman

kholiavko-roman commented Feb 14, 2019 • edited Loading

Guys does anybody knows how to set up eslit for showing error if I modify value from param array ?
Here is example:

checkIsValid = (id, array) => { for (let i = 0; i < array.length; i++) { const item = array[i]; if (item.param) { item.value = null; item.payment = null; } } return array; };

ljharb commented Feb 14, 2019

that’s pushing the limits of static analysis; you may want to try eslint-plugin-immutable, but it’s not very reliable due to the way the language works.

@aboyton

aboyton commented Feb 15, 2019

Or try TypeScript and something like .

kholiavko-roman commented Feb 15, 2019

Thanks for reply. I think I will try eslint-plugin-immutable for the first.

@makevoid

Successfully merging a pull request may close this issue.

@shanev

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

assignment to property of function parameter 'column'

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

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

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

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

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

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

assignment to property of function parameter 'column'

请填写红包祝福语或标题

assignment to property of function parameter 'column'

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

assignment to property of function parameter 'column'

Inspectopedia Help

Assignment could be replaced with operator assignment.

Reports an assignment operation that can be replaced by an operator assignment to make your code shorter and probably clearer.

x = x + 3; x = x / 3;

After the quick fix is applied the result looks like:

x += 3; x /= 3;

Locating this inspection

Can be used to locate inspection in e.g. Qodana configuration files , where you can quickly enable or disable it, or adjust its settings.

Path to the inspection settings via IntelliJ Platform IDE Settings dialog, when you need to adjust inspection settings directly from your IDE.

Settings or Preferences | Editor | Inspections | JavaScript and TypeScript | Assignment issues

Inspection Details

By default bundled with:

, , , , , , , , , , , , ,

Can be installed with plugin:

JavaScript and TypeScript, 242.22907

assignment to property of function parameter 'column'

  • Latest Articles
  • Top Articles
  • Posting/Update Guidelines
  • Article Help Forum

assignment to property of function parameter 'column'

  • View Unanswered Questions
  • View All Questions
  • View C# questions
  • View C++ questions
  • View Javascript questions
  • View Visual Basic questions
  • View .NET questions
  • CodeProject.AI Server
  • All Message Boards...
  • Running a Business
  • Sales / Marketing
  • Collaboration / Beta Testing
  • Work Issues
  • Design and Architecture
  • Artificial Intelligence
  • Internet of Things
  • ATL / WTL / STL
  • Managed C++/CLI
  • Objective-C and Swift
  • System Admin
  • Hosting and Servers
  • Linux Programming
  • .NET (Core and Framework)
  • Visual Basic
  • Web Development
  • Site Bugs / Suggestions
  • Spam and Abuse Watch
  • Competitions
  • The Insider Newsletter
  • The Daily Build Newsletter
  • Newsletter archive
  • CodeProject Stuff
  • Most Valuable Professionals
  • The Lounge  
  • The CodeProject Blog
  • Where I Am: Member Photos
  • The Insider News
  • The Weird & The Wonderful
  • What is 'CodeProject'?
  • General FAQ
  • Ask a Question
  • Bugs and Suggestions

Is it possible to pass a property as a method parameter?

assignment to property of function parameter 'column'

3 solutions

  • Most Recent

Add your solution here

Your Email  
Password  
Your Email  
?
Optional Password  
  • Read the question carefully.
  • Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  • If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Print

Top Experts
Last 24hrsThis month
60
35
25
10
10
441
250
175
133
110

assignment to property of function parameter 'column'

  • Discussions

I want to assign function and parameters to results

arsalansiddiqui

The above images show a table row then a child row which get results from ajax. I'm printing whole table instead of json because i want to assign function to each of the numbers then show specific results (more details).

assignment to property of function parameter 'column'

Param1 will be manager id and Param2 will be status like which counter details to show, like in the image Active has count of 203, so when i click on 203 it pass parameters to function then send another ajax call to show more details in modal.

So how to make work with json with function/parameters ?

colin

You can add that with columns.render

Its not in data table, it is in child row. columns.render work with child row ?

kthorngren

No columns.render does not work with Child Detail rows. If you are following the structure in the example the format() function is used to build the HTML for the child row. Datatables has no visibility into what you put in the HTML. You should be able to place any valid HTML you want. If you are having problems please post a link to your page or a test case so we can take a look. https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Quick Links

  • Recent Discussions
  • 73.9K All Categories
  • 56 Priority support
  • 23.7K Free community support
  • 995 General
  • 14 Announcements
  • 2.5K DataTables
  • 59 DataTables 2
  • 1.3K DataTables 1.10
  • 92 DataTables 1.9
  • 35 DataTables 1.8
  • 9 CloudTables
  • 2.1K Editor
  • 2.8K Extensions
  • 20 AutoFill
  • 307 Buttons
  • 30 DateTime
  • 67 FixedColumns
  • 50 FixedHeader
  • 31 ColReorder
  • 29 KeyTable
  • 102 Responsive
  • 23 RowReorder
  • 41 Scroller
  • 163 SearchBuilder
  • 193 SearchPanes
  • 26 StateRestore
  • 22 TableTools
  • 215 Bug reports
  • 67 Feature requests
  • 99 Plug-ins
  • 68 Web-site

DataTables designed and created by SpryMedia Ltd . © 2007-2023 MIT licensed . Privacy policy . Supporters . SpryMedia Ltd is registered in Scotland, company no. SC456502.

European Microsoft Fabric Community Conference

The ultimate Microsoft Fabric, Power BI, Azure AI, and SQL learning event: Join us in Stockholm, September 24-27, 2024. Save €200 with code MSCUST on top of early bird pricing!

  • Power BI forums
  • News & Announcements
  • Get Help with Power BI
  • Report Server
  • Power Query
  • Mobile Apps
  • DAX Commands and Tips
  • Custom Visuals Development Discussion
  • Health and Life Sciences
  • Power BI Spanish forums
  • Translated Spanish Desktop
  • Training and Consulting
  • Instructor Led Training
  • Dashboard in a Day for Women, by Women
  • Community Connections & How-To Videos
  • COVID-19 Data Stories Gallery
  • Themes Gallery
  • Data Stories Gallery
  • R Script Showcase
  • Webinars and Video Gallery
  • Quick Measures Gallery
  • 2021 MSBizAppsSummit Gallery
  • 2020 MSBizAppsSummit Gallery
  • 2019 MSBizAppsSummit Gallery
  • Custom Visuals Ideas
  • Upcoming Events
  • Community Blog
  • Power BI Community Blog
  • Custom Visuals Community Blog
  • Power BI 中文博客
  • Community Support
  • Community Accounts & Registration
  • Using the Community
  • Community Feedback

Find everything you need to get certified on Fabric—skills challenges, live sessions, exam prep, role guidance, and more. Get started

  • Pass parameter's values to a function from marked ...
  • Subscribe to RSS Feed
  • Mark Topic as New
  • Mark Topic as Read
  • Float this Topic for Current User
  • Printer Friendly Page
  • All forum topics
  • Previous Topic

lg01

  • Mark as New
  • Report Inappropriate Content

Pass parameter's values to a function from marked records

assignment to property of function parameter 'column'

Helpful resources

Europe Fabric Conference

Europe’s largest Microsoft Fabric Community Conference

Join the community in Stockholm for expert Microsoft Fabric learning including a very exciting keynote from Arun Ulag, Corporate Vice President, Azure Data.

AugPowerBI_Carousel

Power BI Monthly Update - August 2024

Check out the August 2024 Power BI update to learn about new features.

August Carousel

Fabric Community Update - August 2024

Find out what's new and trending in the Fabric Community.

How to Get Your Question Answered Quickly

User Count
107
77
71
47
39
User Count
136
108
70
64
57

ganeshacasinos

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

Assignment to property of function parameter 'item'

i have that lint error: Assignment to property of function parameter 'item'

What is the correct way to remove this error?

Giuseppe Fantoni's user avatar

  • does this help? stackoverflow.com/questions/35637770/… –  Alan Yu Commented Nov 16, 2021 at 13:44
  • 2 You are assigning to a property of the parameter. You could use .map and create a new array of new arrays, or disable the rule for this specific functionality. –  jonrsharpe Commented Nov 16, 2021 at 13:46
  • 2 Does getData return JSON? Where do you parse that JSON? Also, what's the structure of each item ? Can you actually set the index like that? You should probably be using map rather than forEach for this operation. –  Andy Commented Nov 16, 2021 at 13:47
  • [ [ "07/10/2020", 0.04, 0.05, 0.04 ], [ "07/10/2020", 0.04, 0.06, 0.04 ] ] @Andy thats the return of getData –  Giuseppe Fantoni Commented Nov 16, 2021 at 14:04
  • I try to use the map but I can't use it well –  Giuseppe Fantoni Commented Nov 16, 2021 at 14:05

Here's an example with map .

const response = [ [ "07/10/2020", 0.04, 0.05, 0.04 ], [ "07/10/2020", 0.04, 0.06, 0.04 ] ]; // Iterate over the response const data = response.map(item => { // For each item destrucuture the data from // the rest of the elements const [date, ...rest] = item; // Return a new array which has the updated // date, and the other elements then spread out return [ moment(new Date(date)).format('DD/MMM/YY'), ...rest ]; }); console.log(data); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Additional documentation

Destructuring assignment

Spread syntax

Andy's user avatar

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 javascript reactjs eslint lint or ask your own question .

  • The Overflow Blog
  • One of the best ways to get value for AI coding tools: generating tests
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Where is DC-3 parked at KOPF?
  • How to reply to a revise and resubmit review, saying is all good?
  • Copyright Fair Use: Is using the phrase "Courtesy of" legally acceptable when no permission has been given?
  • Doesn't nonlocality follow from nonrealism in the EPR thought experiment and Bell tests?
  • Tensor product of intersections in an abelian rigid monoidal category
  • How to deal with coauthors who just do a lot of unnecessary work and exploration to be seen as hard-working and grab authorship?
  • HHL eigenvalue inversion and further inverse QPE
  • Python script to renumber slide ids inside a pptx presentation
  • How do I completly remove "removed" disks from mdadm array
  • Can All Truths Be Scientifically Verified?
  • What was the main implementation programming language of old 16-bit Windows versions (Windows 1 - Windows 3.11)?
  • Is transit visa required for KSA if I am there for only 6 hours
  • Does the science work for why my trolls explode?
  • Why does a capacitor act as an open circuit under a DC circuit?
  • What’s the name of this horror movie where a girl dies and comes back to life evil?
  • What properties of the fundamental group functor are needed to uniquely determine it upto natural isomorphism?
  • Why is resonance such a widespread phenomenon?
  • 1950s comic book about bowling ball looking creatures that inhabit the underground of Earth
  • Why was Panama Railroad in poor condition when US decided to build Panama Canal in 1904?
  • Do black holes convert 100% of their mass into energy via hawking radiation?
  • Little spikes on mains AC
  • Fast leap year check
  • Existence of 2-fold branched covers
  • Rocky Mountains Elevation Cutout

assignment to property of function parameter 'column'

IMAGES

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

    assignment to property of function parameter 'column'

  2. 解决Vue、vuex报“Assignment to property of function parameter ‘state‘” 的方法

    assignment to property of function parameter 'column'

  3. Answers to Math Exercises & Math Problems: Analysis of Functions

    assignment to property of function parameter 'column'

  4. 1.1c Properties of Functions

    assignment to property of function parameter 'column'

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

    assignment to property of function parameter 'column'

  6. Properties of Functions

    assignment to property of function parameter 'column'

VIDEO

  1. ICSE CLASS IX

  2. Use Destructuring Assignment to Pass an Object as a Function's Parameters (ES6) freeCodeCamp

  3. How to use Contour Tool with Full Property Function in CorelDraw X-7,6,5,4,3 |Hindi/Urdu| # 19

  4. parameters and arguments -- C++ Functions for beginners [Part 2]

  5. The Best Feature You're Not Using: The Add User Property Function

  6. A function parameter ceases to exist when the function returns to the caller

COMMENTS

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

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

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

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

  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

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

  6. no-param-reassign

    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; } function foo (bar) {. bar++;

  7. no-param-reassign

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

  8. TypeError: invalid assignment to const "x"

    The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable: js.

  9. TypeScript: Documentation

    Function Parameter Bivariance. When comparing the types of function parameters, assignment succeeds if either the source parameter is assignable to the target parameter, or vice versa. This is unsound because a caller might end up being given a function that takes a more specialized type, but invokes the function with a less specialized type.

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

  11. Why assignment to property of function parameter is bad style

    Why assignment to property of function parameter is bad style. #1217. zhaoxiongfei opened this issue Dec 21, 2016 · 14 comments · Fixed by #1325. Labels. needs eslint rule change/addition semver-patch: loosen/fix/document rules. Comments. Copy link

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

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

  13. Assignment could be replaced with operator assignment

    Assignment could be replaced with operator assignment. Reports an assignment operation that can be replaced by an operator assignment to make your code shorter and probably clearer. Example: x = x + 3; x = x / 3; After the quick fix is applied the result looks like: x += 3; x /= 3; Locating this inspection By ID

  14. Is it possible to pass a property as a method parameter?

    First thing is passing the parameters. You can pass a property as a by-value parameter, because a value is copied from the actual parameter anyway, and a compiler can do it with the property. In contract, out or ref parameter-passing method deal with the reference to the object, which of course cannot be done with the property just because this ...

  15. I want to assign function and parameters to results

    I want to assign function and parameters to results. The above images show a table row then a child row which get results from ajax. I'm printing whole table instead of json because i want to assign function to each of the numbers then show specific results (more details). Param1 will be manager id and Param2 will be status like which counter ...

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

  17. Pass parameter's values to a function from marked records

    Pass parameter's values to a function from marked records 4 hours ago In my project I have a table created from a POST call to a REST service. ... I want to call the function, pass the value of the key column in the record selected to the function and repopulate the table with the new payload coming back from the REST service. Below is the ...

  18. javascript

    You are assigning to a property of the parameter. You could use .map and create a new array of new arrays, or disable the rule for this specific functionality. - jonrsharpe