- Assignment to property of function parameter no-param-reassign
Last updated: Mar 7, 2024 Reading time · 3 min
# 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.
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.
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
Borislav Hadzhiev
Web Developer
Copyright © 2024 Borislav Hadzhiev
HatchJS.com
Cracking the Shell of Mystery
How to Assign to the Property of a Function Parameter in JavaScript
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.
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
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 convert a string to a map in java.
String to Map in Java In Java, a string is a sequence of characters enclosed in double quotes. A map is a data structure that stores key-value pairs. Keys are unique, and values can be of any type. Converting a string to a map is a common task, and there are several ways to do…
Java: Package Lombok Does Not Exist
Java: Package Lombok Does Not Exist If you’re a Java developer, you’ve probably heard of Lombok. Lombok is a popular library that can save you a lot of time by automatically generating boilerplate code. However, you may have also encountered the error message “package lombok does not exist.” This error can be caused by a…
Java Lang IllegalStateException: Logback Configuration Error Detected: How to Fix
Java.lang.IllegalStateException: Logback Configuration Error Detected Logback is a popular logging framework for Java applications. It’s easy to use and configure, and it provides a variety of features for logging, including log file rotation, compression, and filtering. However, logback can also throw a variety of exceptions, including the java.lang.IllegalStateException. This article will discuss the java.lang.IllegalStateException in…
What is Radix in Java? (Explained with Examples)
What is Radix in Java? Radix is a mathematical concept that refers to the base of a number system. In the decimal system, which is the system we use in everyday life, the radix is 10. This means that each digit in a decimal number represents a power of 10. For example, the number 123…
Exception in Thread main java.util.InputMismatchException
Exception in Thread Main: Java.util.InputMismatchException Have you ever been working on a Java program and suddenly been interrupted by a java.util.InputMismatchException? This error can be a real pain, especially if you’re not sure what caused it. In this article, we’ll take a look at what an InputMismatchException is, what causes it, and how to fix…
Java: How to Fix java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
Java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0 Have you ever tried to access an element of an array or list using an index that is out of bounds? If so, you’ve probably encountered a Java.lang.IndexOutOfBoundsException. This error occurs when you try to access an element of an array or list that doesn’t exist….
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
- 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
Understanding ESLint's `no-param-reassign` Rule for Clearer Functions
When you define a function, you can specify variables that the function will receive as input. These are called parameters. The no-param-reassign rule discourages directly changing the value of these parameters within the function.
There are two reasons for this:
- Unexpected behavior In JavaScript, there's a concept called the arguments object. This object holds the values of all the arguments passed to a function. If you change a parameter inside the function, it can also unintentionally modify the arguments object, leading to unexpected results.
- Clarity If you modify a parameter inside the function, it can be confusing for someone reading the code to understand what the function does. They might expect the parameter value to stay the same throughout the function.
Are there exceptions?
There are some cases where reassigning a parameter might be necessary. For instance, you might be working with an object and want to modify one of its properties. In these cases, ESLint provides ways to configure the no-param-reassign rule to allow such modifications while still catching unintended changes.
Strict mode and no-param-reassign
If your code is written in strict mode (a more secure way to write JavaScript), the no-param-reassign rule becomes less important. Strict mode already offers some protections against unintended modifications of the arguments object.
- You'll see an error message from ESLint when you try to directly reassign a parameter value within a function. This typically looks like no-param-reassign: Assignment to function parameter '<parameter_name>' .
Troubleshooting
Configure no-param-reassign ESLint allows some configuration for this rule. You can:
- Ignore Specific Parameters If certain parameters are meant to be modified (like state in state management libraries), you can configure no-param-reassign to ignore those specific names.
- Allow Property Modifications You can allow modifications to properties of objects passed as parameters while still disallowing complete reassignment.
Code Examples for no-param-reassign Rule
This code triggers a no-param-reassign error because it tries to change the value of the x parameter directly:
Fix: Working with the Parameter's Value
Here, we avoid the error by using the original parameter value ( num ) within the function:
Error: Modifying an Object Property
This code attempts to modify a property ( name ) of the object passed as a parameter, which can also trigger the error in some configurations:
Fix: Ignoring Property Modifications (Configuration)
If modifying object properties is intended, you can configure no-param-reassign to allow it:
Allowed Scenario: Working with Copies (Array)
This code demonstrates a case where creating a copy of the parameter (array) is necessary for modification:
Destructuring with Default Values
- When defining the function, you can use destructuring with default values for parameters. This allows you to provide a fallback value if no argument is passed, avoiding the need to reassign later.
Early Return with Modified Copy
- If you need to modify data passed as a parameter (like an object or array), consider creating a copy early on and working with the copy. Then, return the modified copy from the function.
Functional Programming Techniques
Helps enforce coding standards and prevent potential issues.Controls which imports are allowed in your JavaScript code.Use Cases
ESLint is a popular tool for JavaScript developers that helps enforce coding style and identify potential errors. It does this by following a set of rules that you can configure for your project
Benefits By catching undeclared variables early on, you can avoid bugs and make your code more maintainable. It helps identify typos in variable names or accidental usage of implicit globals
Here's how it works:Then it checks if the variable is ever used throughout the code. This includes things like:Assigning a value to another variable (let x = y;)Using the variable in an expression (if (x === 0) { ... })Calling the variable if it's a function (doSomething();)
Why it's useful While JavaScript allows for hoisting of function declarations (meaning they can be used before they are defined), using a variable or class before definition can lead to errors
Simply re-throwing the error If your catch block just catches an error and then throws it again without any modification or handling
Unnecessary Escapes The "no-useless-escape" rule identifies situations where you've used a backslash to escape a character that wouldn't cause any problems within the string
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
- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- Remember language
- Português (do Brasil)
Destructuring assignment
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Description
The object and array literal expressions provide an easy way to create ad hoc packages of data.
The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable.
Similarly, you can destructure objects on the left-hand side of the assignment.
This capability is similar to features present in languages such as Perl and Python.
For features specific to array or object destructuring, refer to the individual examples below.
Binding and assignment
For both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern , with slightly different syntaxes.
In binding patterns, the pattern starts with a declaration keyword ( var , let , or const ). Then, each individual property must either be bound to a variable or further destructured.
All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice — once with let , once with const .
In many other syntaxes where the language binds a variable for you, you can use a binding destructuring pattern. These include:
- The looping variable of for...in for...of , and for await...of loops;
- Function parameters;
- The catch binding variable.
In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with var or let , or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.
Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.
{ a, b } = { a: 1, b: 2 } is not valid stand-alone syntax, as the { a, b } on the left-hand side is considered a block and not an object literal according to the rules of expression statements . However, ({ a, b } = { a: 1, b: 2 }) is valid, as is const { a, b } = { a: 1, b: 2 } .
If your coding style does not include trailing semicolons, the ( ... ) expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.
Note that the equivalent binding pattern of the code above is not valid syntax:
You can only use assignment patterns as the left-hand side of the assignment operator. You cannot use them with compound assignment operators such as += or *= .
Default value
Each destructured property can have a default value . The default value is used when the property is not present, or has value undefined . It is not used if the property has value null .
The default value can be any expression. It will only be evaluated when necessary.
Rest property
You can end a destructuring pattern with a rest property ...rest . This pattern will store all remaining properties of the object or array into a new object or array.
The rest property must be the last in the pattern, and must not have a trailing comma.
Array destructuring
Basic variable assignment, destructuring with more elements than the source.
In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N , only the first N variables are assigned values. The values of the remaining variables will be undefined.
Swapping variables
Two variables values can be swapped in one destructuring expression.
Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).
Parsing an array returned from a function
It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.
In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.
Ignoring some returned values
You can ignore return values that you're not interested in:
You can also ignore all returned values:
Using a binding pattern as the rest property
The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.
These binding patterns can even be nested, as long as each rest property is the last in the list.
On the other hand, object destructuring can only have an identifier as the rest property.
Unpacking values from a regular expression match
When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.
Using array destructuring on any iterable
Array destructuring calls the iterable protocol of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.
Non-iterables cannot be destructured as arrays.
Iterables are only iterated until all bindings are assigned.
The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.
Object destructuring
Basic assignment, assigning to new variable names.
A property can be unpacked from an object and assigned to a variable with a different name than the object property.
Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo .
Assigning to new variable names and providing default values
A property can be both
- Unpacked from an object and assigned to a variable with a different name.
- Assigned a default value in case the unpacked value is undefined .
Unpacking properties from objects passed as a function parameter
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 does not define the property.
Consider this object, which contains information about a user.
Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value { id } indicates that the id property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.
You can define the name of the unpacked variable. Here we unpack the property named displayName , and rename it to dname for use within the function body.
Nested objects can also be unpacked. The example below shows the property fullname.firstName being unpacked into a variable called name .
Setting a function parameter's default value
Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.
Below we show a function where the default size is 'big' , default co-ordinates are x: 0, y: 0 and default radius is 25.
In the function signature for drawChart above, the destructured left-hand side has a default value of an empty object = {} .
You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. Otherwise, you need to at least supply an empty object literal.
For more information, see Default parameters > Destructured parameter with default value assignment .
Nested object and array destructuring
For of iteration and destructuring, computed object property names and destructuring.
Computed property names, like on object literals , can be used with destructuring.
Invalid JavaScript identifier as a property name
Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.
Destructuring primitive values
Object destructuring is almost equivalent to property accessing . This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.
Same as accessing properties, destructuring null or undefined throws a TypeError .
This happens even when the pattern is empty.
Combined array and object destructuring
Array and object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:
The prototype chain is looked up when the object is deconstructed
When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.
Specifications
Browser compatibility.
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
- Assignment operators
- ES6 in Depth: Destructuring on hacks.mozilla.org (2015)
IMAGES
VIDEO
COMMENTS
This behavior is prohibited by the rule. To resolve it, copy the argument to a temporary variable and work on it instead: const result = {...res}; // if result is object. // const result = [...res]; // if result is array. // Rest of your code can work without change.
I have a method which's main purpose is to set a property on a DOM object. el.expando = {}; I use AirBnB's code style which makes ESLint throw a no-param-reassign error: error Assignment to function parameter 'el' 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 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.
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.
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.
You'll see an error message from ESLint when you try to directly reassign a parameter value within a function. This typically looks like no-param-reassign: Assignment to function parameter '<parameter_name>'. Troubleshooting. Configure no-param-reassign ESLint allows some configuration for this rule. You can:
A safer way to define your functions. With ES6 comes the ability to leverage destructuring assignment. For those who aren’t familiar with the syntax, it can seem a little weird.
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.
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Try it. Syntax. js.