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

In JavaScript, a function parameter is a variable that is declared inside the function’s parentheses. When a function is called, the value of the argument passed to the function is assigned to the function parameter.

For example, the following function takes a string argument and prints it to the console:

js function greet(name) { console.log(`Hello, ${name}`); }

greet(“world”); // prints “Hello, world”

In this example, the `name` parameter is assigned the value of the `”world”` argument.

Assignment to property of function parameter

Assignment to property of function parameter is a JavaScript feature that allows you to assign a value to a property of a function parameter. This can be useful for initializing the value of a parameter or for passing a reference to an object.

For example, the following code assigns the value `”hello”` to the `name` property of the `greet` function parameter:

js function greet(name) { name.value = “hello”; }

greet({ value: “world” }); // prints “hello”

In this example, the `name` parameter is a JavaScript object. The `value` property of the `name` object is assigned the value of the `”hello”` argument.

When to use assignment to property of function parameter?

You should use assignment to property of function parameter when you need to:

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

Avoid creating a new object

Initializing the value of a parameter

You can use assignment to property of function parameter to initialize the value of a parameter. For example, the following code initializes the `name` property of the `greet` function parameter to the value of the `”world”` argument:

js function greet(name) { name.value = “world”; }

Passing a reference to an object

You can use assignment to property of function parameter to pass a reference to an object. For example, the following code passes a reference to the `person` object to the `greet` function:

js function greet(person) { console.log(`Hello, ${person.name}`); }

const person = { name: “John Doe” };

greet(person); // prints “Hello, John Doe”

You can use assignment to property of function parameter to avoid creating a new object. For example, the following code uses assignment to property of function parameter to avoid creating a new object for the `name` parameter:

greet(“John Doe”); // prints “Hello, John Doe”

In this example, the `name` parameter is a string literal. The `name` property of the `name` parameter is assigned the value of the `”John Doe”` string literal. This avoids creating a new object for the `name` parameter.

Assignment to property of function parameter is a JavaScript feature that can be used to initialize the value of a parameter, pass a reference to an object, and avoid creating a new object. It is a powerful feature that can be used to improve the performance and readability of your code.

Additional resources

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

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

To use assignment to property of function parameter, you can simply assign a value to the property of the function parameter. For example, the following code assigns the value `”hello”` to the `name` property of the `greet` function parameter:

In this example, the `greet` function is called with the argument `”world”`. The `name` property of the `greet` function parameter is then assigned the value `”hello”`. When the `greet` function is called, the value of the `name` property is used to print the message `”Hello, world”`.

Assignment to property of function parameter can be used to initialize the value of a parameter, pass a reference to an object, or avoid creating a new object.

You can use assignment to property of function parameter to initialize the value of a parameter. For example, the following code initializes the value of the `name` property of the `greet` function parameter to the value of the `name` variable:

js function greet(name) { name = “world”; console.log(`Hello, ${name}`); }

In this example, the `name` variable is assigned the value `”world”` before the `greet` function is called. The `name` property of the `greet` function parameter is then assigned the value of the `name` variable. When the `greet` function is called, the value of the `name` property is used to print the message `”Hello, world”`.

You can use assignment to property of function parameter to pass a reference to an object. For example, the following code passes a reference to the `user` object to the `greet` function:

js function greet(user) { console.log(`Hello, ${user.name}`); }

const user = { name: “John Doe”, };

greet(user); // prints “Hello, John Doe”

In this example, the `user` object is passed to the `greet` function as a parameter. The `greet` function then uses the `name` property of the `user` object to print the message `”Hello, John Doe”`.

Avoiding creating a new object

You can use assignment to property of function parameter to avoid creating a new object. For example, the following code uses assignment to property of function parameter to avoid creating a new object for the `user` variable:

In this example, the `user` variable is assigned the value of the `user` object. The `greet` function then uses the `name` property of the `user` variable to print the message `”Hello, John Doe”`.

By using assignment to property of function parameter, you can avoid creating a new object for the `user` variable. This can improve the performance of your code and reduce the amount of memory that is used.

4. Pitfalls of assignment to property of function parameter

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

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

js function greet(name) { name = “hello”; console.log(`Hello, ${name}`); }

greet(“world”); // prints “Hello, hello” greet(“hello”); // prints “Hello, hello”

A: Assignment to property of function parameter occurs when you assign a value to a property of a function parameter. This can be done by using the dot operator (.) to access the property, or by using the bracket operator ([]) to index into the property.

For example, the following code assigns the value “10” to the `x` property of the `foo()` function’s parameter `y`:

const foo = (y) => { y.x = 10; };

foo({ x: 5 }); // { x: 10 }

Q: Why is assignment to property of function parameter dangerous?

A: Assignment to property of function parameter can be dangerous because it can change the value of the property in the calling scope. This can lead to unexpected behavior and errors.

For example, the following code changes the value of the `x` property of the global variable `a`:

foo({ x: 5 }); // a.x is now 10

This behavior can be difficult to debug, as it may not be obvious that the change to the `x` property is being caused by the `foo()` function.

Q: How can I avoid assignment to property of function parameter?

There are a few ways to avoid assignment to property of function parameter. One way is to use the `const` keyword to declare the function parameter as a constant. This will prevent the value of the parameter from being changed.

Another way to avoid assignment to property of function parameter is to use the `readonly` keyword to declare the function parameter as read-only. This will prevent the value of the parameter from being changed, even by assignment to a property of the parameter.

Finally, you can also use the `Object.freeze()` method to freeze the object that is passed as the function parameter. This will prevent any changes to the object, including changes to the values of its properties.

Q: What are the best practices for assignment to property of function parameter?

The best practices for assignment to property of function parameter are as follows:

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

Here are some key takeaways from this article:

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

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

Author Profile

Marcus Greenwood

Latest entries

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

Similar Posts

Java 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:…

How to Override or Implement a Supertype Method in Java

Overriding and Implementing Supertype Methods When you’re writing a class that extends another class, you’ll often need to override or implement one or more of the methods from the superclass. This is because the superclass’s methods may not be appropriate for the subclass, or you may need to add additional functionality to the method. In…

Next.js Get Current URL: A Guide for SEO

Next.js Get Current URL: A Comprehensive Guide Next.js is a React framework that makes it easy to build fast, modern web applications. One of the most important features of Next.js is its ability to get the current URL. This information can be used for a variety of purposes, such as routing, state management, and data…

How to Convert BigDecimal to Double in Java

Java BigDecimal to Double Conversion: A Comprehensive Guide Converting a BigDecimal to a double is a common task in Java programming. BigDecimal is a class that represents a decimal number with arbitrary precision, while double is a primitive data type that represents a floating-point number with a limited precision. There are a few different ways…

Java.net.SocketException: Connection or outbound has closed

Java.net.SocketException: Connection or Outbound Has Closed Have you ever been working on a Java project and encountered the dreaded `java.net.SocketException: Connection or Outbound Has Closed` error? If so, you’re not alone. This error is a common one, and it can be caused by a variety of factors. In this article, we’ll take a look at…

AngularJS Radio Button: A Complete Guide

Radio Buttons in AngularJS Radio buttons are a common UI element that allow users to select one option from a group. In AngularJS, radio buttons can be easily created and styled using the `ng-model` directive. This article will provide a brief overview of how to create and use radio buttons in AngularJS. We will cover…

no-param-reassign

Disallow reassigning function parameters

Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object when not in strict mode (see When Not To Use It below). Often, assignment to function parameters is unintended and indicative of a mistake or programmer error.

This rule can be also configured to fail when function parameters are modified. Side effects on parameters can cause counter-intuitive execution flow and make errors difficult to track down.

Rule Details

This rule aims to prevent unintended behavior caused by modification or reassignment of function parameters.

Examples of incorrect code for this rule:

Examples of correct code for this rule:

This rule takes one option, an object, with a boolean property "props" , and arrays "ignorePropertyModificationsFor" and "ignorePropertyModificationsForRegex" . "props" is false by default. If "props" is set to true , this rule warns against the modification of parameter properties unless they’re included in "ignorePropertyModificationsFor" or "ignorePropertyModificationsForRegex" , which is an empty array by default.

Examples of correct code for the default { "props": false } option:

Examples of incorrect code for the { "props": true } option:

Examples of correct code for the { "props": true } option with "ignorePropertyModificationsFor" set:

Examples of correct code for the { "props": true } option with "ignorePropertyModificationsForRegex" set:

When Not To Use It

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

Strict mode code doesn’t sync indices of the arguments object with each parameter binding. Therefore, this rule is not necessary to protect against arguments object mutation in ESM modules or other strict mode functions.

This rule was introduced in ESLint v0.18.0.

Further Reading

Avatar image for spin.atomicobject.com

  • Rule source
  • Tests source

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

JavaScript Object Destructuring, Spread Syntax, and the Rest Parameter – A Practical Guide

TAPAS ADHIKARY

In JavaScript, we use objects to store multiple values as a complex data structure. There are hardly any JavaScript applications that do not deal with objects.

Web developers commonly extract values from an object property to use further in programming logic. With ES6, JavaScript introduced object destructuring to make it easy to create variables from an object's properties.

In this article, we will learn about object destructuring by going through many practical examples. We will also learn how to use the spread syntax and the rest parameter . I hope you enjoy it.

Object Destructuring in JavaScript

We create objects with curly braces {…} and a list of properties. A property is a key-value pair where the key must be a string or a symbol, and the value can be of any type, including another object.

Here we have created a user object with three properties: name, address, and age. The real need in programming is to extract these property values and assign them to a variable.

For example, if we want to get the value of the name and age properties from the user object, we can do this:

This is undoubtedly a bit more typing. We have to explicitly mention the name and age property with the user object in dot(.) notation, then declare variables accordingly and assign them.

We can simplify this process using the new object destructuring syntax introduced in ES6.

JavaScript Object Destructuring is the syntax for extracting values from an object property and assigning them to a variable. The destructuring is also possible for JavaScript Arrays.

By default, the object key name becomes the variable that holds the respective value. So no extra code is required to create another variable for value assignment. Let's see how this works with examples.

Basic Object Destructuring Example

Let's take the same user object that we referred to above.

The expression to extract the name property value using object destructuring is the following:

As you see, on the left side of the expression, we pick the object property key ( name in this case) and place it inside the {} . It also becomes the variable name to hold the property value.

The right side of the expression is the actual object that extracts the value. We also mention the keywords, const , let and so on to specify the variable's scope.

destructure

So, how do we extract values from more than one object property? Simple – we keep adding the object keys inside the {} with commas separating them. In the example below, we destructure both the name and age properties from the user object.

Variable Declaration Rule

The keywords let and const are significant in object destructuring syntax. Consider the example below where we have omitted the let or const keyword. It will end up in the error, Uncaught SyntaxError: Unexpected token '=' .

What if we declare the variable in advance and then try to destructure the same name's key from the object? Nope, not much luck here either. It is still syntactically incorrect.

In this case, the correct syntax is to put the destructuring expression inside parenthesis ( (...) ).

Please note that the parenthesis are required when you want to omit the let or const keyword in the destructuring expression itself.

Add a New Variable & Default Value

We can add a new variable while destructuring and add a default value to it. In the example below, the salary variable is non-existent in the user object. But we can add it in the destructuring expression and add a default value to it.

The alternative way to do the above is this:

There is a considerable advantage to the flexibility of adding a variable with a default value. The default value of this new variable is not necessarily going to be any constant value always. We can compute the value of it from other destructured property values.

Let's take a user object with two properties, first_name and last_name . We can now compute the value of a non-existent full_name using these two properties.

Isn't that elegant and useful!

Add Aliases

You can give an alias name to your destructured variables. It comes in very handy if you want to reduce the chances of variable name conflicts.

In the example below, we have specified an alias name for the property address as permanentAddress .

Please note, an attempt to access the variable address here will result in this error:

image-12

Nested Object Destructuring

An object can be nested. This means that the value of an object property can be another object, and so on.

Let's consider the user object below. It has a property called department with the value as another object. But let's not stop here! The department has a property with the key address whose value is another object. Quite a real-life scenario, isn't it?

How do we extract the value of the department property? Ok, it should be straight-forward by now.

And here's the output when you log department :

image-30

But, let's go one more nested level down. How do we extract the value of the address property of the department ? Now, this may sound a bit tricky. However, if you apply the same object destructuring principles, you'll see that it's similar.

Here's the output when you log address :

image-31

In this case, department is the key we focus on and we destructure the address value from it. Notice the {} around the keys you want to destructure.

Now it's time to take it to the next level. How do we extract the value of city from the department's address? Same principle again!

The output when you log city is "Bangalore".

It can go any level nested down.

The rule of thumb is to start with the top-level and go down in the hierarchy until you reach the value you want to extract.

Dynamic Name Property

Many times you may not know the property name (key) of an object while destructuring it. Consider this example. We have a user object:

Now the method getValue(key) takes a property key name and should return the value of it.

So, how do we write the definition of the getValue(key) method using the destructuring syntax?

Well, the syntax is very much the same as creating aliases. As we don't know the key name to hard-code in the destructuring syntax, we have to enclose it with square brackets ( [...] ).

Destructure to the Function Parameter

This one is my favorites, and it practically reduces lots of unnecessary code. You may want just a couple of specific property values to pass as a parameter to the function definition, not the entire object. Use object destructuring to function parameter in this case.

Let's take the user object example once again.

Suppose we need a function to return a string using the user's name and age. Say something like Alex is 43 year(s) old! is the return value when we call this:

We can simply use destructuring here to pass the name and age values, respectively, to the function definition. There is no need to pass the entire user object and then extract the values from it one by one. Please have a look:

Destructure Function Return Value

When a function returns an object and you are interested in specific property values, use destructuring straight away. Here is an example:

It is similar to the basic object destructuring we saw in the beginning.

Destructure in Loops

You can use object destructuring with the for-of loop. Let's take an array of user objects like this:

We can extract the property values with object destructuring using the for-of loop.

This is the output:

image-27

The Console object

In JavaScript, console is a built-in object supported by all browsers. If you have noticed, the console object has many properties and methods, and some are very popular, like console.log() .

image-13

Using the destructuring object syntax, we can simplify the uses of these methods and properties in our code. How about this?

Spread Syntax in JavaScript

The Spread Syntax (also known as the Spread Operator) is another excellent feature of ES6. As the name indicates, it takes an iterable (like an array) and expands (spreads) it into individual elements.

We can also expand objects using the spread syntax and copy its enumerable properties to a new object.

Spread syntax helps us clone an object with the most straightforward syntax using the curly braces and three dots {...} .

With spread syntax we can clone, update, and merge objects in an immutable way. The immutability helps reduce any accidental or unintentional changes to the original (Source) object.

The Object Destructuring and Spread syntaxes are not the same thing in JavaScript.

Create a Clone of an Object

We can create a cloned instance of an object using the spread syntax like this:

You can alternatively use object.assign() to create a clone of an object. However, the spread syntax is much more precise and much shorter.

The spread syntax performs a shallow copy of the object. This means that none of the nested object instances are cloned.

Add Properties to Objects

We can add a new property (key-value pair) to the object using the spread syntax . Note that the actual object never gets changed. The new property gets added to the cloned object.

In the example below, we are adding a new property ( salary ) using the spread syntax.

Update Properties

We can also update an existing property value using the spread syntax. Like the add operation, the update takes place on the object's cloned instance, not on the actual object.

In the example below, we are updating the value of the age property:

Update Nested Objects

As we have seen, updating an object with the spread syntax is easy, and it doesn't mutate the original object. However, it can be a bit tricky when you try to update a nested object using the spread syntax. Let's understand it with an example.

We have a user object with a property department . The value of the department property is an object which has another nested object with its address property.

Now, how can we add a new property called, number with a value of, say, 7 for the department object? Well, we might try out the following code to achieve it (but that would be a mistake):

As you execute it, you will realize that the code will replace the entire department object with the new value as, {'number': 7} . This is not what we wanted!

image-28

How do we fix that? We need to spread the properties of the nested object as well as add/update it. Here is the correct syntax that will add a new property number with the value 7 to the department object without replacing its value:

The output is the following:

image-29

Combine (or Merge) two Objects

The last practical use of the spread syntax in JavaScript objects is to combine or merge two objects. obj_1 and obj_2 can be merged together using the following syntax:

Note that this way of merging performs a shallow merge . This means that if there is a common property between both the objects, the property value of obj_2 will replace the property value of obj_1 in the merged object.

Let's take the user and department objects to combine (or merge) them together.

Merge the objects using the spread syntax, like this:

The output will be the following:

image-33

If we change the department object like this:

Now try to combine them and observe the combined object output:

The output will be:

image-34

The name property value of the user object is replaced by the name property value of the department object in the merged object output. So be careful of using it this way.

As of now, you need to implement the deep-merge of objects by yourself or make use of a library like lodash to accomplish it.

The Rest Parameter in JavaScript

The Rest parameter is kind of opposite to the spread syntax. While spread syntax helps expand or spread elements and properties, the rest parameter helps collect them together.

In the case of objects, the rest parameter is mostly used with destructuring syntax to consolidate the remaining properties in a new object you're working with.

Let's look at an example of the following user object:

We know how to destructure the age property to create a variable and assign the value of it. How about creating another object at the same time with the remaining properties of the user object? Here you go:

image-26

In the output we see that the age value is 43 . The rest parameter consolidated the rest of the user object properties, name and address , in a separate object.

To summarize,

  • Object destructuring is new syntax introduced in ES6. It helps create variables by extracting the object's properties in a much simpler way.
  • If you are working with (or planning to use) a framework/library like angular , react , or vue , you will be using a lot of object destructuring syntax.
  • Object destructuring and Spread syntax are not the same thing.
  • Spread syntax (also known as the Spread Operator) is used to copy the enumerable properties of an object to create a clone of it. We can also update an object or merge with another object using the spread syntax.
  • The Rest parameter is kind of the opposite of the Spread syntax. It helps to consolidate (or collect) the remaining object properties into a new object while destructuring is done.

Before we go

I hope you've found this article insightful, and that it helps you start using these concepts more effectively. Let's connect. You will find me active on Twitter (@tapasadhikary) . Please feel free to give a follow.

You can find all the source code examples used in this article in my GitHub repository - js-tips-tricks . Are you interested in doing some hands-on coding based on what we have learned so far? Please have a look at the quiz here , and you may find it interesting.

You may also like these articles:

  • How to Learn Something New Every Day as a Software Developer
  • How to find blog content ideas effortlessly?
  • Why do you need to do Side Projects as A Developer?
  • 16 side project GitHub repositories you may find useful

Writer . YouTuber . Creator . Mentor

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp Challenge Guide: Use Destructuring Assignment to Pass an Object as a Function's Parameters

Use destructuring assignment to pass an object as a function’s parameters, problem explanation.

You could pass the entire object, and then pick the specific attributes you want by using the . operator. But ES6 offers a more elegant option!

Get rid of the stats , and see if you can destructure it. We need the max and min of stats .

Code Explanation

Notice that we are destructuring stats to pass two of its attributes - max and min - to the function. Don’t forget to the modify the second return statement. Change stats.max to just max , and change stats.min to just min .

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

JavaScript: Don’t Reassign Your Function Arguments

UPDATE : The point of this post is to raise awareness that reassigning the value of an argument variable mutates the arguments object. The code example is contrived and exists solely to help illustrate that behavior.

Did you know that a JavaScript function’s named parameter variables are synonyms for the corresponding elements in that function’s Arguments object?

I ran into this while experimenting with a function that was written to take either two or three arguments, providing a default for the first argument if only two are passed.

Strangely, all of the values in the result object are set to "green" . I was expecting to see

But when I set favoriteColor to "green" I was also changing arguments[0] to be "green" . The situation only got worse when I set name = arguments[0] effectively changing arguments[1] to be "green" as well.

I had not realized that named arguments are synonyms for the elements of the Arguments object. I found a good explanation on Rx4AJAX:

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 reflect the same value.

Regardless of the language, it is generally not a good idea to reassign the parameter variables inside a function. In JavaScript it turns out to be a really bad idea.

Additional information:

  • Check out this jsFiddle to experiment with the code snippet above.
  • A comment on this StackOverflow question describes this “magical behavior” of JavaScript.
  • JavaScript Garden describes this behavior in its section on the arguments object.

Related Posts

Remix is incredible — if it fits your use case, vercel: a valuable debugging tool, common css pitfalls and how to avoid them, keep up with our latest posts..

We’ll send our latest tips, learnings, and case studies from the Atomic braintrust on a monthly basis.

' src=

So the arguments object isn’t a “real” array, so you run into problems when you treat it as such.

Here’s a working example where you turn the arguments object into an array with Array.prototype.slice()

http://jsfiddle.net/wookiehangover/yZPj8/4/

This is a pretty common beginner’s mistake and is covered in most advanced books, such as Javascript Patterns or High Performance Javascript.

Here’s a good resource about how the arguments object works: https://developer.mozilla.org/en/JavaScript/Reference/functions_and_function_scope/arguments

' src=

If you slice the Arguments, the get aan array, which is not “live”. This way, you can reassign the arguments without any problems. http://jsfiddle.net/Avorin/yZPj8/6/

' src=

When I want to pass a varying number of parameters to a function, I either use a predefined object or an object literal myself to begin with (I presume this example function is simplified).

You can also clutter up the function calls with things like makePerson(null, “Joe”, 18) and test for nulls, too, instead of array lengths.

This is the solution I found, using this. instead of an args array. I’m not sure which solution is better.

http://jsfiddle.net/Q2LMT/

' src=

Or simply refer to the arguments by name when changing their values.

' src=

This article roughly says:

When you misuse the arguments object, unexpected results happen.

The solution: don’t misuse the arguments object. Leave the param list empty and use your logic to fill out variable names if you need that

' src=

This is why I love working with Rails… most Rails functions take hashes as arguments, so you can your real arguments in in any order, and it guarantees code verbosity. Example:

button_to ‘Add to Cart’, line_items_path(:product_id => product), :remote => true

where :remote=>true is the third argument, a hash, and contains all optional parameters you could add (in this case, :method, :disabled, :confirm, and :remote).

' src=

var makePerson = function(favoriteColor, name, age) { if (arguments.length < 3) { favoriteColor = "green"; name = arguments[0]; age = arguments[1]; } return { name: name, age: age, favoriteColor: (arguments.length < 3 ? "green" : favoriteColor) }; };

' src=

How very Perl-ish of Javascript.

Ignore this blog post’s advice. It is perfectly fine to reassign function arguments in Javascript. If you just follow the convention of putting option arguments at the end of the argument list instead of the beginning, you avoid this problem all together and simplify your code:

var makePerson = function(name, age, favoriteColor) { favoriteColor = favoriteColor || “green”; return { name: name, age: age, favoriteColor: favoriteColor }; };

' src=

Who makes the first argument optional? Seriously? There are numerous things wrong with your code.

' src=

What a terrible programming language.

' src=

Larry Clapp, this isn’t perlish at all. In Perl you do named parameters through local variables. They’re duplicated not ref-copied.

use strict; use warnings;

my $makePerson = sub { my ( $favoriteColor, $name, $age ) = @_;

if ( @_ $name , age => $age , favoriteColor => $favoriteColor }

use Data::Dumper; die Dumper $makePerson->(‘Joe’, 18);

What you’re confusing is Perl’s special array variable `@_` which is used to store references to the parameters from the caller, making them accessible in the callee. So the sub implementation themselves are pass-by-reference, but the assignment itself requires a total copy. Not to say you couldn’t achieve the same effect with Perl if you *really wanted too*, but it requires a ton of non-accidental (contrived) work.

my $makePerson = sub { my ( $favoriteColor, $name, $age ) = ( \$_[0], \$_[1], \$_[2] ); #my ( $favoriteColor, $name, $age ) = @_;

if ( length @_ $$name , age => $$age , favoriteColor => $$favoriteColor }

use Data::Dumper; my $name = ‘Joe’; my $age = 18; die Dumper $makePerson->($name, $age);

' src=

How about just using a configuration object?

var person = makePerson({name:”Joe”, age:18})

Inside the function look for the property you want to default.

' src=

JavaScript reveals more and more of its awful design. NaN != NaN ?????

' src=

the problem isn’t with using arguments , the problem is with your use of it.

Writing the code: function example (x, y, z) { x = 1; y = arguments[0]; z = arguments[1]; }

will make every value 1 because I wasn’t very careful about the order of my actions.

As the article you quoted states, the variables x, y, and z are synonymous with arguments [0], [1], and [2] respectively, so if I called example(3,4) all I would be doing in my function is assigning 3 to x and 4 to y with the function call, then assigning 1 to x, the value of x to y, then the value of y to z. All of my values would be the same (and 1) afterwards.

You do the same thing in your code. You pass in (favoriteColor: Joe, name: 18) and then set the favoriteColor to “green” before taking the value of “green” and pasting it on to the name, then taking the new value of name (also “green”) and pasting it in to the value of age. If you had instead written that code in the reverse order, it would have worked as you had initially expected.

[…] service allows you to react immediately to spikes in website traffic. Just recently our blog had a post go viral on Reddit causing an extreme spike in traffic. Using a live information radiator on our office […]

' src=

There are special edge cases like Array.prototype.reduce where assign to accumulator argument passed between iterations is only good practice:

const aggregate = someArray.reduce((acc, item) => { acc[item.prop] = (acc[item.prop] || 0) + 1; }, {} /* this is initial state */);

' src=

Choose Parameters or Arguments….but using both is asking for trouble.

If you are using Parameters defined in the Function signature, then you have no need to refer to the arguments information.

If you plan on using arguments, then do not define Parameters.

Mixing the two, is asking for problems and the reason for the overall purpose of this post.

Comments are closed.

Destructuring assignment

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

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

However, when we pass these to a function, we may not need all of it. The function might only require certain elements or properties.

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.

Destructuring also works well with complex functions that have a lot of parameters, default values, and so on. Soon we’ll see that.

Array destructuring

Here’s an example of how an array is destructured into variables:

Now we can work with variables instead of array members.

It looks great when combined with split or other array-returning methods:

As you can see, the syntax is simple. There are several peculiar details though. Let’s see more examples to understand it better.

It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. However, the array itself is not modified.

It’s just a shorter way to write:

Unwanted elements of the array can also be thrown away via an extra comma:

In the code above, the second element of the array is skipped, the third one is assigned to title , and the rest of the array items are also skipped (as there are no variables for them).

…Actually, we can use it with any iterable, not only arrays:

That works, because internally a destructuring assignment works by iterating over the right value. It’s a kind of syntax sugar for calling for..of over the value to the right of = and assigning the values.

We can use any “assignables” on the left side.

For instance, an object property:

In the previous chapter, we saw the Object.entries(obj) method.

We can use it with destructuring to loop over the keys-and-values of an object:

The similar code for a Map is simpler, as it’s iterable:

There’s a well-known trick for swapping values of two variables using a destructuring assignment:

Here we create a temporary array of two variables and immediately destructure it in swapped order.

We can swap more than two variables this way.

The rest ‘…’

Usually, if the array is longer than the list at the left, the “extra” items are omitted.

For example, here only two items are taken, and the rest is just ignored:

If we’d like also to gather all that follows – we can add one more parameter that gets “the rest” using three dots "..." :

The value of rest is the array of the remaining array elements.

We can use any other variable name in place of rest , just make sure it has three dots before it and goes last in the destructuring assignment.

Default values

If the array is shorter than the list of variables on the left, there will be no errors. Absent values are considered undefined:

If we want a “default” value to replace the missing one, we can provide it using = :

Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.

For instance, here we use the prompt function for two defaults:

Please note: the prompt will run only for the missing value ( surname ).

Object destructuring

The destructuring assignment also works with objects.

The basic syntax is:

We should have an existing object on the right side, that we want to split into variables. The left side contains an object-like “pattern” for corresponding properties. In the simplest case, that’s a list of variable names in {...} .

For instance:

Properties options.title , options.width and options.height are assigned to the corresponding variables.

The order does not matter. This works too:

The pattern on the left side may be more complex and specify the mapping between properties and variables.

If we want to assign a property to a variable with another name, for instance, make options.width go into the variable named w , then we can set the variable name using a colon:

The colon shows “what : goes where”. In the example above the property width goes to w , property height goes to h , and title is assigned to the same name.

For potentially missing properties we can set default values using "=" , like this:

Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided.

In the code below prompt asks for width , but not for title :

We also can combine both the colon and equality:

If we have a complex object with many properties, we can extract only what we need:

The rest pattern “…”

What if the object has more properties than we have variables? Can we take some and then assign the “rest” somewhere?

We can use the rest pattern, just like we did with arrays. It’s not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones.

It looks like this:

In the examples above variables were declared right in the assignment: let {…} = {…} . Of course, we could use existing variables too, without let . But there’s a catch.

This won’t work:

The problem is that JavaScript treats {...} in the main code flow (not inside another expression) as a code block. Such code blocks can be used to group statements, like this:

So here JavaScript assumes that we have a code block, that’s why there’s an error. We want destructuring instead.

To show JavaScript that it’s not a code block, we can wrap the expression in parentheses (...) :

Nested destructuring

If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.

In the code below options has another object in the property size and an array in the property items . The pattern on the left side of the assignment has the same structure to extract values from them:

All properties of options object except extra that is absent in the left part, are assigned to corresponding variables:

Finally, we have width , height , item1 , item2 and title from the default value.

Note that there are no variables for size and items , as we take their content instead.

Smart function parameters

There are times when a function has many parameters, most of which are optional. That’s especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, items list and so on.

Here’s a bad way to write such a function:

In real-life, the problem is how to remember the order of arguments. Usually IDEs try to help us, especially if the code is well-documented, but still… Another problem is how to call a function when most parameters are ok by default.

That’s ugly. And becomes unreadable when we deal with more parameters.

Destructuring comes to the rescue!

We can pass parameters as an object, and the function immediately destructurizes them into variables:

We can also use more complex destructuring with nested objects and colon mappings:

The full syntax is the same as for a destructuring assignment:

Then, for an object of parameters, there will be a variable varName for property incomingProperty , with defaultValue by default.

Please note that such destructuring assumes that showMenu() does have an argument. If we want all values by default, then we should specify an empty object:

We can fix this by making {} the default value for the whole object of parameters:

In the code above, the whole arguments object is {} by default, so there’s always something to destructurize.

Destructuring assignment allows for instantly mapping an object or array onto many variables.

The full object syntax:

This means that property prop should go into the variable varName and, if no such property exists, then the default value should be used.

Object properties that have no mapping are copied to the rest object.

The full array syntax:

The first item goes to item1 ; the second goes into item2 , all the rest makes the array rest .

It’s possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one.

We have an object:

Write the destructuring assignment that reads:

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

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

The maximal salary

There is a salaries object:

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

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

P.S. Use Object.entries and destructuring to iterate over key/value pairs.

Open a sandbox with tests.

Open the solution with tests in a sandbox.

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

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Assignment (=)

The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .

An expression specifying the value to be assigned to x .

Return value

The value of y .

Thrown in strict mode if assigning to an identifier that is not declared in the scope.

Thrown in strict mode if assigning to a property that is not modifiable .

Description

The assignment operator is completely different from the equals ( = ) sign used as syntactic separators in other locations, which include:

  • Initializers of var , let , and const declarations
  • Default values of destructuring
  • Default parameters
  • Initializers of class fields

All these places accept an assignment expression on the right-hand side of the = , so if you have multiple equals signs chained together:

This is equivalent to:

Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:

Simple assignment and chaining

Value of assignment expressions.

The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.

Unqualified identifier assignment

The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .

Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:

So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.

In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.

Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

Assignment with destructuring

The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.

For more information, see Destructuring assignment .

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Assignment operators in the JS guide
  • Destructuring assignment

COMMENTS

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

    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

    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.

  4. no-param-reassign

    If you want to allow assignment to function parameters, then you can safely disable this rule. Strict mode code doesn't sync indices of the arguments object with each parameter binding. Therefore, this rule is not necessary to protect against arguments object mutation in ESM modules or other strict mode functions. Version

  5. no-param-reassign

    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.

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

  7. JavaScript: Use Destructuring Assignment over Function Parameters

    Destructuring Assignment with objects is just a way to take any JavaScript object: And pull out the parameters we want into its own variable: If we aren't sure a variable exists, we can easily ...

  8. JavaScript Object Destructuring, Spread Syntax, and the Rest Parameter

    Destructure to the Function Parameter. This one is my favorites, and it practically reduces lots of unnecessary code. You may want just a couple of specific property values to pass as a parameter to the function definition, not the entire object. Use object destructuring to function parameter in this case. Let's take the user object example ...

  9. Working with objects

    A method is a function associated with an object, or, put differently, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. See also method definitions for more details. An example is:

  10. Object.assign()

    Later sources' properties overwrite earlier ones. The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.

  11. Use Destructuring Assignment to Pass an Object as a Function's Parameters

    Use Destructuring Assignment to Pass an Object as a Function's Parameters Problem Explanation You could pass the entire object, and then pick the specific attributes you want by using the . operator. But ES6 offers a more elegant option! Hints Hint 1 Get rid of the stats, and see if you can destructure it. We need the max and min of stats.

  12. 15-use-destructuring-assignment-to-pass-an-object-as-a-functions

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

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

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

  15. Mastering JavaScript Object.defineProperty: A Comprehensive ...

    It is called on an object and takes a property name as an argument. If the specified property exists on the object and is enumerable, the function returns true; otherwise, it returns false. This ...

  16. Destructuring assignment

    If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions. In the code below options has another object in the property size and an array in the property items. The pattern on the left side of the assignment has the same structure to extract values from them:

  17. 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 ... How to avoid no-param-reassign when setting a property on a DOM object. Hot Network Questions Short story with a witch, party crackers, and something prophetic stitched in a hem ...

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

  19. Assignment (=)

    The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...