• 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

How to change button text in javascript with examples.

How to Change Button Text in JavaScript Buttons are a vital part of any user interface, and they can be used to perform a variety of actions, such as submitting a form, adding an item to a cart, or playing a video. By default, buttons have a default text that is displayed when the user…

Accessors in JavaScript: What They Are and How to Use Them

Accessors: A Powerful Tool for Encapsulating Data Accessors are a powerful tool for encapsulating data in JavaScript. They allow you to define getters and setters for your properties, which gives you more control over how your data is accessed and modified. In this article, we’ll take a closer look at accessors and see how you…

> The Method Is for the Type Java: What It Means and How to Fix It

The dreaded “the method is for the type java” error Have you ever been working on a Java project, only to be met with the dreaded error message “the method is for the type java”? If so, you’re not alone. This error is one of the most common in Java, and it can be a…

Unable to Make Field private final long java.time.Instant.seconds Accessible

Unable to Make Field Private Final Long Java.time.Instant.seconds Accessible Java.time.Instant is a class that represents a moment in time, independent of any time zone or calendar. It is expressed as the number of seconds since the Unix epoch (January 1, 1970, 00:00:00 UTC). The seconds field of the Instant class is a private final long…

Java Security UnrecoverableKeyException: Password Verification Failed

Java Security UnrecoverableKeyException: What It Is and How to Fix It If you’re a Java developer, you’ve probably come across the dreaded UnrecoverableKeyException at some point. This exception is thrown when Java’s security infrastructure is unable to recover a key that has been previously stored. This can happen for a variety of reasons, such as:…

Chart.js with ASP.NET Core Razor Pages

Chart.js ASP.NET Core Razor Pages Chart.js is a popular JavaScript charting library that can be used to create interactive charts and graphs. ASP.NET Core Razor Pages is a framework for building web pages that is designed to be lightweight and easy to use. In this article, we will show you how to use Chart.js with…

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

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

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

How to pass a TypeScript function as a parameter

assignment to property of function parameter 'input'

Editor’s note : This article was last updated by Yan Sun on 6 February 2024. It now includes sections about declaring function types in TypeScript, using JavaScript’s passy-by-reference concept for functions, and understanding advanced patterns such as generics and function overloads.

How To Pass A TypeScript Function As A Parameter

In JavaScript, functions are considered first-class citizens, which means they can be handled like any other type of variable, including numbers, strings, and arrays. This feature allows functions to be passed into other functions, returned from functions, and assigned to variables for later use.

This feature is heavily used in asynchronous code, where functions are often passed into asynchronous functions, often referred to as callbacks . But this can be tricky to use with TypeScript.

TypeScript offers us the fantastic benefits of adding static types and transpilation checks, and it can help us better document what types of variables we expect in our functions. But what happens if we need to pass functions?

It is evident that typing these functions is necessary. However, the question arises: how do we type them, and how do we pass a function in TypeScript? In this tutorial, we will explore TypeScript functions and how to pass them as parameters in our apps.

What is a TypeScript function type?

Most TypeScript developers are familiar with typing simple variables, but constructing a type for a function is a little more complicated.

A function type (note: this link redirects to old TypeScript docs, but it has a much clearer example than the newer ones) is made up of the types of arguments the function accepts and the return type of the function.

We can illustrate a very simple example to demonstrate this:

If implemented in JavaScript, the above example would work fine and have no issues.

But when we utilize TypeScript, errors are thrown when we try to transpile our code:

The error message thrown here is descriptive: the stringify and numberify function are not interchangeable. They cannot be assigned interchangeably to the test variable, as they have conflicting types. The arguments they receive are the same (one argument of type any ), but we receive errors because their return types are different.

We could change the return types here to prove our theory is correct:

The above code now works as expected. The only difference is that we changed the stringify function to match the return type of the numberify function. Indeed, the return type was breaking this example.

Declaring function types in TypeScript

In TypeScript, we can declare a function type with the type keyword. The type keyword in TypeScript allows us to specify the shape of data:

Here, we define a type alias named AddOperator using the type keyword. It represents a function type that takes two parameters ( a and b ) of type number and returns a value of type number .

Another way to declare a function type is to use interface syntax. The below Add interface represents the same function type as the above AddOperator function type:

Explicitly defining function structures provides a clear understanding of expected inputs and outputs. This enhances code readability, serves as documentation, and simplifies code maintenance.

Another main advantage of declaring function types is the ability to catch errors at compile time. TypeScript’s static typing ensures that functions adhere to the specified types, preventing runtime errors caused by mismatched parameter types or invalid return types.

In the example below, the TypeScript compiler will throw an error, indicating the mismatch between the expected and actual return types:

Declaring function types allows Integrated Development Environments (IDEs) to offer precise autocompletion.

IntelliSense, a powerful feature offered by modern IDEs, provides us with context-aware suggestions. Function types provide explicit information about parameter types, making it easier to understand the expected inputs. As we start typing function names or parameters, IntelliSense utilizes the declared types to suggest valid options, minimizing errors and saving time.

assignment to property of function parameter 'input'

Over 200k developers use LogRocket to create better digital experiences

assignment to property of function parameter 'input'

Utilizing JavaScript/TypeScript’s pass-by-reference for functions

In JavaScript/TypeScript, understanding the concepts of pass-by-value and pass-by-reference is crucial for working with functions and manipulating data. Primitive types (such as Boolean, null, undefined, String, and Number) are treated as pass-by-value , while objects (including arrays and functions) are handled as pass-by-reference .

When an argument is passed to the function, pass-by-value means a copy of the variable is created, and any modifications made within the function do not affect the original variable. In the example below, we change the value of the variable a inside the function, but the value of the variable a outside isn’t changed as a is passed into the function with pass-by-value :

When an object or array argument is passed to a function, it is treated as pass-by-reference . The argument is copied as a reference, not the object itself. Thus, changes to the argument’s properties inside the function are reflected in the original object. In the example below, we can observe that the change of the array orignalArray inside the function affects the orignalArray outside the function:

Contrary to some misconceptions, even though the reference to the object is copied for pass-by-reference , the reference itself is still passed by value. If the object reference is reassigned inside the function, it won’t affect the original object outside the function.

The below example illustrates reassigning an array reference of originalArray inside the function, and its original object isn’t affected:

Advanced patterns: generics and function overloads

Generics in TypeScript provide a way to write functions that can work with any data type. The following example is sourced from the official TypeScript documentation :

Here, the identity function can accept and return values of any type. This flexibility allows us to write functions that adapt to various data types.

Reusable and adaptable functions using generics

We can create highly reusable and adaptable functions that work with various data types using generics.

Let’s say we want to create a utility function for searching elements in an array based on a specific criterion. Using generics allows the function to work with arrays of various types and accommodate different search criteria:

Here, we create a generic function named findElements that takes an array arr and a filterFn function as parameters. The filterFn parameter is a callback function that determines whether an element satisfies a particular criterion, returning a Boolean.

Below are a couple of examples in which we use the function from above to deal with number types, object types, and different search criteria. We use the function to filter odd numbers from an array and inexpensive products from an array of products, demonstrating its flexibility with different data types:

The use of generics makes the function highly reusable and adaptable, making it applicable to arrays of primitive types or custom objects without sacrificing type safety.

Function overloads

Function overloads allow us to provide multiple type signatures for a single function. This is particularly useful when a function can accept different combinations of argument types.

More great articles from LogRocket:

  • Don't miss a moment with The Replay , a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

To use function overload, we must define multiple overload signatures and an implementation. The overload signature outlines the parameter and return types of a function without including an actual implementation body:

In the above example, we create a function that demonstrates function overloads accepting parameters, either a string or an array of strings. This function, named greeting , has two overloads to handle these scenarios. The implementation checks whether the input parameter is a string or an array of strings and performs the appropriate action for each case.

We can leverage generics to create versatile functions that work with various data types. Additionally, function overload is valuable in enhancing parameter flexibility, allowing functions to accept different types while providing clear expectations for each case.

Using argument numbers in TypeScript

Interestingly, many other languages will create these function types based on the types of argument, return types, and the number of arguments for the function.

Let’s make one final example to expand on our last working example:

Developers familiar with other languages might think the above function examples aren’t interchangeable, as the two function signatures differ.

This example throws no errors, though, and it’s legitimate in TypeScript because TypeScript implements what’s referred to as duck typing .

In duck typing, TypeScript checks if the structure of the assigned function is compatible with the expected type based on the function’s parameters and return type. In this case, both stringify and numberify share the same structure: a function that takes one or more parameters (of any type) and returns a number. Despite the difference in the number of parameters between the two functions, TypeScript allows this assignment due to duck typing.

It’s a small note, but it’s important to remember: the number of arguments isn’t utilized in type definitions for functions in TypeScript.

Typing our functions example in TypeScript

Now, we know precisely how to construct types for our functions. We need to ensure we type the functions that we pass in TypeScript.

Let’s work through a failing example together again:

The above example doesn’t work, but it captures what we need.

We need to pass it to a parent function as a callback, which can be called later. So, what do we need to change here? We need to:

  • Type the el function argument
  • Type the arguments we pass into the el function (if it requires them)

Upon doing this, our example should now look like this:

This specific example doesn’t require arguments, but if it did, here is what it would look like:

This example is relatively simple to explain the concepts of TypeScript functions easily, but if we have more complicated types, we may spend a significant amount of time typing everything.

The community maintains plenty of high-quality open source typings commonly used in TypeScript, called Definitely Typed , which can help us simplify and speed up the typing we need to use.

I hope this article has been helpful so you better understand the TypeScript landscape around passing functions as arguments to other functions.

Callbacks typically rely on this method, so you’ll often see heavy use of callbacks in any mature TypeScript codebase. Happy coding!

LogRocket : Full visibility into your web and mobile apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.

Try it for free .

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • #typescript

Hey there, want to help make our blog better?

Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

assignment to property of function parameter 'input'

Stop guessing about your digital experience with LogRocket

Recent posts:.

assignment to property of function parameter 'input'

Understanding env variables and containers in Astro 4.10

Astro, renowned for its developer-friendly experience and focus on performance, has recently released a new version, 4.10. This version introduces […]

assignment to property of function parameter 'input'

Build an image editor with Fabric.js v6

In web development projects, developers typically create user interface elements with standard DOM elements. Sometimes, web developers need to create […]

assignment to property of function parameter 'input'

Creating toast notifications using Solid Toast

Toast notifications are messages that appear on the screen to provide feedback to users. When users interact with the user […]

assignment to property of function parameter 'input'

Deno adoption guide: Overview, examples, and alternatives

Deno’s features and built-in TypeScript support make it appealing for developers seeking a secure and streamlined development experience.

assignment to property of function parameter 'input'

Leave a Reply Cancel reply

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.

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.

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

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

  • 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 function parameter 'value' no-param-reassign

I am trying to get rid off the no-param-reassign error from the following code.

Tried with adding the followings:

Nothing has worked. Also tried creating a new variable and assign to it. Still didn't work. I can't commit code due to that error.

I need to update this ( properties.color ) array element with function parameter value.

  • typescript-eslint

PineCone's user avatar

  • See if it helps, stackoverflow.com/a/35637900/13262332 –  DJ Hemath Commented Mar 25, 2022 at 4:20
  • Unfortunately I tried most of the suggestion from the post you suggested. But nothing worked. –  PineCone Commented Apr 4, 2022 at 7:55

Know someone who can answer? Share a link to this question via email , Twitter , or Facebook .

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 .

Browse other questions tagged reactjs typescript-eslint reassign or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • Bringing clarity to status tag usage on meta sites
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Who was the French detective mentioned in Hitchcock's "Shadow of a Doubt"?
  • Mistake on car insurance policy about use of car (commuting/social)
  • Was using an older version of a legal card from a nonlegal set ever not legal?
  • Does the Supremacy Clause allow states to retain abortion rights enshrined in each states' constitution?
  • What is the shortest viable hmac for non-critical applications?
  • Using "provide" with value of a variable
  • Practice test paper answers all seem incorrect, but provider insists they are ... what am i missing?
  • Why does ATSAM3X8E have two separate registers for setting and clearing bits?
  • Consistency-proof of ZFC
  • Can't identify logo for a 135N68A MOSFET. Hunting for datasheet. Any ideas?
  • jq - ip addr show in tabular format
  • How can I get the bounding box of a path (drawn with hobby)?
  • Logical relationship between supercompact and rank-into-rank cardinals
  • I want to be a observational astronomer, but have no idea where to start
  • Has anyone returned from space in a different vehicle from the one they went up in? And if so who was the first?
  • Is this map real?
  • Defining a grid in tikz using setlength vs. explicitly setting a length parameter
  • Inspector tells me that the electrician should have removed green screw from the panel
  • Big Transition of Binary Counting in perspective of IEEE754 floating point
  • Starting with 2014 "+" signs and 2015 "−" signs, you delete signs until one remains. What’s left?
  • Why do "modern" languages not provide argv and exit code in main?
  • 4/4 time change to 6/8 time
  • Correct anonymization of submission using Latex
  • How much does a ma'ah cost in £/$ in today's world?

assignment to property of function parameter 'input'

IMAGES

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

    assignment to property of function parameter 'input'

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

    assignment to property of function parameter 'input'

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

    assignment to property of function parameter 'input'

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

    assignment to property of function parameter 'input'

  5. Pass parameters to function in python

    assignment to property of function parameter 'input'

  6. Functions & Parameters in C Programming

    assignment to property of function parameter 'input'

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. How to use Blend Tool with Complete Property Function in CorelDraw X-7,6,5,4,3 |Hindi/Urdu| # 20

  5. C++ Tutorial: Function parameters, arguments, and return types

  6. How to use All Line Connector Tools with Full Property Function in CorelDraw X-7,6,5,4,3 |Hindi| #17

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. JavaScript: Use Destructuring Assignment over Function Parameters

    And pull out the parameters we want into its own variable: If we aren't sure a variable exists, we can easily provide a default value: If we want to rename one of the variables, we can do so ...

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

  7. JavaScript: Don't Reassign Your Function Arguments

    The numbered properties of the Arguments Object are synonymous with the local variables that hold the named function parameters. They both reference the same address in the stack. If the function body has code that changes the value of a parameter either via a name reference or the arguments[] array reference, both referenced values will ...

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

  9. 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++;

  10. How to pass a TypeScript function as a parameter

    type AddOperator = (a: number, b: number) => number; Here, we define a type alias named AddOperator using the type keyword. It represents a function type that takes two parameters (a and b) of type number and returns a value of type number. Another way to declare a function type is to use interface syntax.

  11. The arguments object

    The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0.. For example, if a function is passed 3 arguments, you can access them as follows:

  12. JavaScript Function Parameters

    Function Parameters and Arguments. Earlier in this tutorial, you learned that functions can have parameters: function functionName(parameter1, parameter2, parameter3) {. // code to be executed. } Function parameters are the names listed in the function definition. Function arguments are the real values passed to (and received by) the function.

  13. Arrow function expressions

    Remove the word "function" and place arrow between the argument and opening body brace (a) => { return a + 100; }; // 2. Remove the body braces and word "return" — the return is implied. (a) => a + 100; // 3. Remove the parameter parentheses a => a + 100; In the example above, both the parentheses around the parameter and the braces around ...

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

  15. TypeScript Reactjs: 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; interface SideBar { sideisOpen: ...

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

    We read every piece of feedback, and take your input very seriously. Include my email address so I can be contacted. Cancel Submit feedback ... Why assignment to property of function parameter is bad style. #1217. Closed zhaoxiongfei opened this issue Dec 21, 2016 · 14 comments · Fixed by #1325.

  17. javascript

    i have that lint error: Assignment to property of function parameter 'item' What is the correct way to remove this error? const resp = await getData(payload) resp.forEach((item) =&gt; { item[...

  18. Default string paramaters

    The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. ... If you want to be able to call the script with an optional parameter that has a default value if no value is input when called use: [parameter(Mandatory ... I had created a function to break out some of the script that ...

  19. Assignment to function parameter 'value' no-param-reassign

    Assignment to property of function parameter (no-param-reassign) 2 ReactJS es-lint: Return statement should not contain assignment. 2 "Parsing error: Argument expression expected. eslint" with Typescript map function in React. 0 Fixing no-param-reassign Eslint issue in function ...