• 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.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: package does not exist – causes and solutions.

Java: Package Does Not Exist One of the most common errors that Java programmers encounter is the “package does not exist” error. This error occurs when the compiler cannot find the package that a class or interface is declared in. There are a few different reasons why this error might occur, and the solution will…

Get Element by ID in AngularJS: A Guide to Finding Elements by Their Unique Identifier

Getting an Element by ID in AngularJS AngularJS is a popular JavaScript framework for building dynamic web applications. One of the most basic tasks in AngularJS is getting an element by its ID. This can be done using the `getElementById()` method. The `getElementById()` method takes a single argument, which is the ID of the element…

How to Fix the no sqljdbc_auth in java.library.path Error

No `sqljdbc_auth` in `java.library.path` If you’re trying to use the SQL Server JDBC driver with Java and you’re getting an error message like “no `sqljdbc_auth` in `java.library.path`,” don’t despair. This is a common problem, and there are a few simple solutions. In this article, I’ll walk you through the steps to troubleshoot this error and…

How to Convert a Stack to an Array in Java

How to Convert a Stack to an Array in Java Stacks and arrays are both common data structures in Java. Stacks are LIFO (last-in, first-out) data structures, meaning that the last element added to the stack is the first element to be removed. Arrays, on the other hand, are ordered collections of elements that can…

How to Convert cURL Requests to Axios in JavaScript

Introducing Axios: A Better Alternative to Curl Curl is a popular command-line tool for transferring data over the network. It’s fast, efficient, and supports a wide range of protocols. However, curl can be difficult to use for beginners, and it doesn’t offer many features that modern web developers need. Axios is a newer HTTP client…

Javax.net.ssl.SSLException: Unrecognized SSL message: plaintext connection

Have you ever been trying to connect to a website and received an error message like “javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection”? If so, you’re not alone. This is a common error that can occur for a variety of reasons. In this article, we’ll take a look at what causes this error and how to…

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript function parameters.

A JavaScript function does not perform any checking on parameter values (arguments).

Function Parameters and Arguments

Earlier in this tutorial, you learned that functions can have parameters :

Function parameters are the names listed in the function definition.

Function arguments are the real values passed to (and received by) the function.

Parameter Rules

JavaScript function definitions do not specify data types for parameters.

JavaScript functions do not perform type checking on the passed arguments.

JavaScript functions do not check the number of arguments received.

Default Parameters

If a function is called with missing arguments (less than declared), the missing values are set to undefined .

Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:

Default Parameter Values

ES6 allows function parameters to have default values.

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

Function Rest Parameter

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

Advertisement

The Arguments Object

JavaScript functions have a built-in object called the arguments object.

The argument object contains an array of the arguments used when the function was called (invoked).

This way you can simply use a function to find (for instance) the highest value in a list of numbers:

Or create a function to sum all input values:

If a function is called with too many arguments (more than declared), these arguments can be reached using the arguments object .

Arguments are Passed by Value

The parameters, in a function call, are the function's arguments.

JavaScript arguments are passed by value : The function only gets to know the values, not the argument's locations.

If a function changes an argument's value, it does not change the parameter's original value.

Changes to arguments are not visible (reflected) outside the function.

Objects are Passed by Reference

In JavaScript, object references are values.

Because of this, objects will behave like they are passed by reference:

If a function changes an object property, it changes the original value.

Changes to object properties are visible (reflected) outside the function.

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

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

The arguments object

arguments is an array-like object accessible inside functions that contains the values of the arguments passed to that function.

Description

Note: In modern code, rest parameters should be preferred.

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:

The arguments object is useful for functions called with more arguments than they are formally declared to accept, called variadic functions , such as Math.min() . This example function accepts any number of string arguments and returns the longest one:

You can use arguments.length to count how many arguments the function was called with. If you instead want to count how many parameters a function is declared to accept, inspect that function's length property.

Assigning to indices

Each argument index can also be set or reassigned:

Non-strict functions that only have simple parameters (that is, no rest, default, or destructured parameters) will sync the new value of parameters with the arguments object, and vice versa:

Non-strict functions that are passed rest , default , or destructured parameters will not sync new values assigned to parameters in the function body with the arguments object. Instead, the arguments object in non-strict functions with complex parameters will always reflect the values passed to the function when the function was called.

This is the same behavior exhibited by all strict-mode functions , regardless of the type of parameters they are passed. That is, assigning new values to parameters in the body of the function never affects the arguments object, nor will assigning new values to the arguments indices affect the value of parameters, even when the function only has simple parameters.

Note: You cannot write a "use strict"; directive in the body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw a syntax error .

arguments is an array-like object

arguments is an array-like object, which means that arguments has a length property and properties indexed from zero, but it doesn't have Array 's built-in methods like forEach() or map() . However, it can be converted to a real Array , using one of slice() , Array.from() , or spread syntax .

For common use cases, using it as an array-like object is sufficient, since it both is iterable and has length and number indices. For example, Function.prototype.apply() accepts array-like objects.

Reference to the currently executing function that the arguments belong to. Forbidden in strict mode.

The number of arguments that were passed to the function.

Returns a new Array iterator object that contains the values for each index in arguments .

Defining a function that concatenates several strings

This example defines a function that concatenates several strings. The function's only formal argument is a string containing the characters that separate the items to concatenate.

You can pass as many arguments as you like to this function. It returns a string list using each argument in the list:

Defining a function that creates HTML lists

This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is "u" if the list is to be unordered (bulleted) , or "o" if the list is to be ordered (numbered) . The function is defined as follows:

You can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. For example:

Using typeof with arguments

The typeof operator returns 'object' when used with arguments

The type of individual arguments can be determined by indexing arguments :

Specifications

Browser compatibility.

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

  • Functions guide
  • Rest parameters

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

no-param-reassign

Disallows reassignment of function parameters.

Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object. Often, assignment to function parameters is unintended and indicative of a mistake or programmer error.

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

Rule Details

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

Examples of incorrect code for this rule:

Examples of correct code for this rule:

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

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

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

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

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

When Not To Use It

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

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

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

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.

Tell Us About Your Project

We’d love to talk with you about your next great software project. Fill out this form and we’ll get back to you within two business days.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers, Type Conversion and Mathematics
  • Python List
  • Python Tuple
  • Python Sets
  • Python Dictionary

Python Functions

Python Function Arguments

  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension

Python Lambda/Anonymous Function

  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json

Python *args and **kwargs

Python Tutorials

Python User-defined Functions

  • Python map() Function

In computer programming, an argument is a value that is accepted by a function.

Before we learn about function arguments, make sure to know about Python Functions .

  • Example 1: Python Function Arguments

In the above example, the function add_numbers() takes two parameters: a and b . Notice the line,

Here, add_numbers(2, 3) specifies that parameters a and b will get values 2 and 3 respectively.

  • Function Argument with Default Values

In Python, we can provide default values to function arguments.

We use the = operator to provide default values. For example,

In the above example, notice the function definition

Here, we have provided default values 7 and 8 for parameters a and b respectively. Here's how this program works

1. add_number(2, 3)

Both values are passed during the function call. Hence, these values are used instead of the default values.

2. add_number(2)

Only one value is passed during the function call. So, according to the positional argument 2 is assigned to argument a , and the default value is used for parameter b .

3. add_number()

No value is passed during the function call. Hence, default value is used for both parameters a and b .

  • Python Keyword Argument

In keyword arguments, arguments are assigned based on the name of the arguments. For example,

Here, notice the function call,

Here, we have assigned names to arguments during the function call.

Hence, first_name in the function call is assigned to first_name in the function definition. Similarly, last_name in the function call is assigned to last_name in the function definition.

In such scenarios, the position of arguments doesn't matter.

  • Python Function With Arbitrary Arguments

Sometimes, we do not know in advance the number of arguments that will be passed into a function. To handle this kind of situation, we can use arbitrary arguments in Python .

Arbitrary arguments allow us to pass a varying number of values during a function call.

We use an asterisk (*) before the parameter name to denote this kind of argument. For example,

In the above example, we have created the function find_sum() that accepts arbitrary arguments. Notice the lines,

Here, we are able to call the same function with different arguments.

Note : After getting multiple values, numbers behave as an array so we are able to use the for loop to access each value.

Table of Contents

  • Introduction

Video: Python Function Arguments: Positional, Keywords and Default

Sorry about that.

Related Tutorials

Python Tutorial

Python Function Examples – How to Declare and Invoke with Parameters

Dionysia Lemonaki

Python has a bunch of helpful built-in functions you can use to do all sorts of stuff. And each one performs a specific task.

But did you know that Python also allows you to define your own functions?

This article will show you how to create and call your own Python functions. It will also give you an overview of how to pass input parameters and arguments to your functions.

What is a Function?

A function is an isolated block of code that performs a specific task.

Functions are useful in programming because they eliminate needless and excessive copying and pasting of code throught a program.

If a certain action is required often and in different places, that is a good indicator that you can write a function for it. Functions are meant to be reusable.

Functions also help organize your code.

If you need to make a change, you'll only need to update that certain function. This saves you from having to search for different pieces of the same code that have been scattered in different locations in your program by copying and pasting.

This complies with the DRY (Don't Repeat Yourself) principle in software development.

The code inside a function runs only when they the function is called.

Functions can accept arguments and defaults and may or not return values back to the caller once the code has run.

How to Define a Function in Python

The general syntax for creating a function in Python looks something like this:

Let's break down what's happening here:

  • def is a keyword that tells Python a new function is being defined.
  • Next comes a valid function name of your choosing. Valid names start with a letter or underscore but can include numbers. Words are lowercase and separated by underscores. It's important to know that function names can't be a Python reserved keyword.
  • Then we have a set of opening and closing parentheses, () . Inside them, there can be zero, one, or more optional comma separated parameters with their optional default values. These are passed to the function.
  • Next is a colon, : , which ends the function's definition line.
  • Then there's a new line followed by a level of indentation (you can do this with 4 spaces using your keyboard or with 1 Tab instead). Indentation is important since it lets Python know what code will belong in the function.
  • Then we have the function's body. Here goes the code to be executed – the contents with the actions to be taken when the function is called.
  • Finally, there's an optional return statement in the function's body, passing back a value to the caller when the function is exited.

Keep in mind that if you forget the parentheses () or the colon : when trying to define a new function, Python will let you know with a SyntaxError .

How to Define and Call a Basic Function in Python

Below is an example of a basic function that has no return statement and doesn't take in any parameters.

It just prints hello world whenever it is called.

Once you've defined a function, the code will not run on its own.

To execute the code inside the function, you have make a function invokation or else a function call .

You can then call the function as many times as you want.

To call a function you need to do this:

Here's a breakdown of the code:

  • Type the function name.
  • The function name has to be followed by parentheses. If there are any required arguments, they have to be passed in the parentheses. If the function doesn't take in any arguments, you still need the parentheses.

To call the function from the example above, which doesn't take in any arguments, do the following:

How to Define and Call Functions with Parameters

So far you've seen simple functions that don't really do much besides printing something to the console.

What if you want to pass in some extra data to the function?

We've used terms here like parameter and arguments .

What are their definitions exactly?

Parameters are a named placeholder that pass information into functions.

They act as variables that are defined locally in the function's definition line.

In the example above, there is one parameter, name .

We could've used f-string formatting instead – it works the same way as the previous example:

There can be a list of parameters inside the parentheses, all separated by commas.

Here, the parameters in the function are name and age .

When a function is called, arguments are passed in.

Arguments, like parameters, are information passed to functions.

In particular, they are the actual values that correspond to the parameters in the function definition.

Calling the function from a previous example and passing in an argument would look like this:

The function can be called many times, passing in different values each time.

The arguments presented so far are called positional arguments .

All positional arguments are very much required .

The number of positional arguments matters

When calling functions, you need to pass the correct number of arguments, otherwise there will be an error.

When it comes to positional arguments, the number of arguments passed in to the function call has to be exactly the same as the number of parameters in the function's definition.

You can't leave any out or add in any more.

Say that you have this function that takes in two parameters:

If the function is called with just one argument passed in, like this, there will be an error:

If the function is called with three arguments passed in, there will again be an error:

There will also be an error if we pass in no arguments.

Instead, we need two arguments, since two parameters are listed in the function definition.

The order of positional arguments matters

Besides including the correct number of arguments, it is important to note that the order in which the arguments are passed in matters.

Arguments need to be passed in the exact same order as the order of the parameters that have been declared in the function's definition.

It works like variable assignment.

The first argument is the value of the first parameter in the function's definition. The second argument is the value of the second parameter in the function's ddefinition – and so on.

If the order is not correct, the output might not make much sense and not be what you intended it to be.

How to use keyword arguments in Python functions

So far you've seen one type of argument, positional arguments.

With positional arguments, functions are called with just the values passed in the function call. There, each value directly corresponds with the number, order, and position of each parameter in the function definition.

However, functions in Python can accept another type of argument, that is keyword arguments .

In this case, instead of just passing in values in the function call, you instead specify the name of the parameter and then the value you want to assign it, in the form of key = value .

Each key matches each parameter in the function definition.

Explicitely calling the name of parameters and the values they take helps in being extra clear about what you're passing in and avoids any possible confusion.

Keyword arguments, as seen above, can be in a particular order. But they are more flexible than positional arguments in the sense that order of arguments now does not matter.

So you could do this and there would be no errors:

But you still have to give the correct number of arguments.

You can use both positional and keyword arguments together in a function call, like the example below where there is one positional argument and one keyword argument:

In this case, order matters again.

Positional arguments always come first and all keyword arguments should follow the positional arguments. Otherwise there will be an error:

How to define a parameter with a default value in Python

Function arguments can also have default values. They are known as default or optional arguments .

For a function argument to have a default value, you have to assign a default value to the parameter in the function's definition.

You do this with the key=value form, where value will be the default value for that parameter.

As you see, default arguments are not required in the function call, and the value of language will always default to Python if another value isn't provided in the call.

However, default values can be easily overriden if you provide another value in the function's call:

There can be more than one default value passed to the function.

When the function is called, none, one, some, or all of the default arguments can be provided and order does not matter.

Default arguments can be combined with non-default arguments in the function's call.

Here is a function that accepts two arguments: one positional, non-default ( name ) and one optional, default ( language ).

The default argument, langyage="Python" , is optional . But the positional argument, name , will always always required. If another language is not passed in, the value will always default to Python.

Another thing to mention here is that, when defaults and non defaults are used together, the order they are defined in the function defintion matters.

All the positional arguments go first and are followed by the default arguments.

This will not work:

In this article, you learned how to declare functions and invoke them with parameters in the Python programming language.

This was an introduction on how to create simple functions and how to pass data into them, with parameters. We also went over the different types of arguments like positional , keyword , and default arguments.

  • The order and number of positional arguments matters.
  • With keyword arguments, order does not matter. Number does matter, though, since each keyword argument corresponds with each parameter in the function's definition.
  • Default arguments are entirely optional. You can pass in all of them, some of them, or none at all.

If you are interested in going more in-depth and learning more about the Python programming language, freeCodeCamp has a free Python certification .

You'll start from the basics and fundamentals of the language and then progress to more advanced concepts like data structures and relational databases. In the end you'll build 5 projects to put to practice what you've learnt.

Thank you for reading and happy learning.

Read more posts .

If this article was helpful, share it .

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

What does something: number mean in parameters?

I always see people using something like this in functions:

I’m confused on why there is a name: string there instead of just name . Does it do anything, or is it just for looks and easier to read?

Thanks in advanced.

A string is simply text(characters). So in other words the name is text.

Type checking. Basically, you force the code to assume that name is a string, and amount is a number, so autocomplete gives you the correct members for that variable.

This is called type checking, basically it tells the code that the variable name is supposed to be a string instead of the default any (meaning any possible type). This helps to catch common non-runtime coding errors early on without having to run the code, however it won’t change the behaviour of the code itself.

So type checking doesn’t prevent any errors from occurring or change code behaviour. It just warns the programmer about said type checking errors by redlining the code within the script editor and in a way “annoying” them till they fix the issue.

Type checking is highly useful for organizing code, helping other programmers decode what you did and for even helping your future self when revisiting your code.

Just for looks. It helps with autocompletion aka intellisense.

Parameter hints

Functions calls with positional-only arguments can get quite unreadable:

Some IDE’s support inlay hints, but these can get cut off and make line length hard to measure:

image

Could we add a notation to hint the parameter names, but which is ignored at runtime?

Edit: with 6+ people against, I won’t follow through with this.

Why use positional-only arguments then? They’re not the default.

This is just an example, this mostly applies to built-in functions such as range() . Although I also use it when the signature of a class is incompatible with its super class. e.g.

Also, using parameter hints would be faster than keyword arguments:

Yes, I know this is pre-mature optimisation, but it would be as readable as keywords.

I think this is a needless complication to work around a poor API design.

Something like this?

Yes, both, I would put them on separate lines anyway when they don’t fit on a single line:

But this is overkill for functions like range() , and it makes more sense if the parameter name comes first.

I see 6 people disagree with me. OK, then not.

If you find that someone else’s interface is awkward because it uses positional-only arguments, make a wrapper.

For Python code, you can probably use the inspect module to automate this. It’s not trivial, though.

The problem is that built-ins don’t actually have names for those positional-only arguments, because they’re implemented in a context that doesn’t need names - the C code receives the arguments via the C API which has already stuffed them into a tuple, and assuming those arguments are unpacked into local variables in the C code, those names aren’t exposed anywhere (even in a debug build, they’d only be visible to a C debugger). So we can’t support something like range(step=2) “automatically”, because range doesn’t just reject passing the arguments by keyword - it doesn’t have any keywords to use.

I don’t really understand why. That doesn’t seem like a good way to signal the issue. But aside from that, __init__ and __new__ are special, because they’re concerned with object creation. Beyond that point, methods should uphold the Liskov Substitution Principle .

Related Topics

  • Building Responsive Applications with Visual Builder Studio
  • Develop Applications
  • Work With Code
  • Work With JavaScript

Use Variables with a JavaScript Module

You can't directly get or set variables from within your JavaScript modules. However, you can use the Call Function action to access your JS module. This action takes an array of parameters which can include variables and can return a result that you can assign to a variable.

This approach ensures that the variable has a consistent state from the beginning to the end of your action chain's execution.

To "get" a value, pass the variable in as a parameter to the module function that you are calling using a Call Function action in the action chain.

To "set" a variable based on the return value from that Call Function action, use an Assign Variable action to copy the result of the function into the desired variable in whatever scope.

R-bloggers

R news and tutorials contributed by hundreds of R bloggers

Estimating chi-square distribution parameters using r.

Posted on April 14, 2024 by Steven P. Sanderson II, MPH in R bloggers | 0 Comments

Introduction

In the world of statistics and data analysis, understanding and accurately estimating the parameters of probability distributions is crucial. One such distribution is the chi-square distribution, often encountered in various statistical analyses. In this blog post, we’ll dive into how we can estimate the degrees of freedom (“df”) and the non-centrality parameter (“ncp”) of a chi-square distribution using R programming language.

The Chi-Square Distribution

The chi-square distribution is a continuous probability distribution that arises in the context of hypothesis testing and confidence interval estimation. It is commonly used in goodness-of-fit tests, tests of independence, and tests of homogeneity.

The distribution has two main parameters: – Degrees of Freedom (df) : This parameter determines the shape of the chi-square distribution. It represents the number of independent variables in a statistical test. – Non-Centrality Parameter (ncp) : This parameter determines the deviation of the distribution from a null hypothesis. It’s particularly relevant in non-central chi-square distributions.

The Goal: Estimating Parameters

Our goal is to create a function within the TidyDensity package that can estimate the df and ncp parameters of a chi-square distribution based on a vector of observed data. Let’s walk through the steps involved in achieving this.

Working Example

Setting the stage: libraries and data.

First, we load the necessary libraries: tidyverse for data manipulation and bbmle for maximum likelihood estimation. We then generate a grid of parameters (degrees of freedom and non-centrality parameter) and sample sizes to create a diverse set of chi-square distributed data.

Function Exploration: Unveiling the Estimation Process

The core of our exploration lies in several functions designed to estimate the chi-square parameters:

dof / k Functions: These functions focus on estimating the degrees of freedom (df) using different approaches:

  • mean_x : Calculates the mean of the data.
  • mean_minus_1 : Subtracts 1 from the mean.
  • var_div_2 : Divides the variance of the data by 2.
  • length_minus_1 : Subtracts 1 from the length of the data.

ncp Functions: These functions aim to estimate the non-centrality parameter (ncp) using various methods:

  • mean_minus_mean_minus_1 : A seemingly trivial calculation that serves as a baseline.
  • ie_mean_minus_var_div_2 : Subtracts half the variance from the mean, ensuring the result is non-negative.
  • ie_optim : Utilizes optimization techniques to find the ncp that maximizes the likelihood of observing the data.
  • estimate_chisq_params : This is the main function that employs maximum likelihood estimation (MLE) via the bbmle package to estimate both df and ncp simultaneously. It defines a negative log-likelihood function based on the chi-square distribution and uses mle2 to find the parameter values that minimize this function.

Simulating and Evaluating: Putting the Functions to the Test

To assess the performance of our functions, we simulate chi-square data using the parameter grid and apply each function to estimate the parameters. We then compare these estimates to the true values and visualize the results using boxplots.

Visual Insights: Assessing Estimation Accuracy

The boxplots reveal interesting insights:

assignment to function parameter 'params'

df Estimation:

  • mean_x - 1 and var(x) / 2 show potential as df estimators but exhibit bias depending on the true df value.
  • length(x) - 1 performs poorly, consistently underestimating df.
  • The MLE approach from estimate_chisq_params demonstrates the most accurate and unbiased estimates across different df values.

ncp Estimation:

  • The simple methods ( mean(x) - mean(x) - 1 and mean(x) - var(x) / 2 ) show substantial bias and variability.
  • The optimization-based method ( optim ) performs better but still exhibits some bias.
  • The MLE approach again emerges as the most reliable option, providing accurate and unbiased estimates across various ncp values.

Conclusion: The Power of Maximum Likelihood

Our exploration highlights the effectiveness of MLE in estimating the parameters of a chi-square distribution. The estimate_chisq_params function, utilizing the bbmle package, provides a robust and accurate solution for this task. This function will be a valuable addition to the TidyDensity package, empowering users to delve deeper into the analysis of chi-square distributed data.

Stay tuned for further developments and exciting additions to the TidyDensity package!

Copyright © 2024 | MH Corporate basic by MH Themes

Never miss an update! Subscribe to R-bloggers to receive e-mails with the latest R posts. (You will not see this message again.)

assignment to function parameter 'params'

  • Sign In / Suggest an Article

Current ISO C++ status

Upcoming ISO C++ meetings

Upcoming C++ conferences

Compiler conformance status

Pure Virtual C++ 2024

April 30, Online  

C++ Now 2024

May 7-12, Aspen, CO, USA

ISO C++ committee meeting

June 24-29, St. Louis, MO, USA

July 2-5, Folkestone, Kent, UK

Why you shouldn't have virtual member functions with default parameters -- Andreas Fertig

By Blog Staff | Apr 26, 2024 12:32 PM | Tags: None

Ep49-Fertig.png

C++ Insights Episode 49: Why you shouldn't have virtual member functions with default parameters by Andreas Fertig

Share this Article

Add a comment, comments (0).

There are currently no comments on this entry.

COMMENTS

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

    function createEmployee(emp) { // ⛔️ Assignment to property of function parameter 'emp'. eslint no-param-reassign. emp.name = 'bobby hadz'; emp.salary = 500; return emp; } The ESLint rule forbids assignment to function parameters because modifying a function's parameters also mutates the arguments object and can lead to confusing behavior.

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

    This is a common ESLint issue that appears frequently on old codebase. You have modified the result variable which was passed as parameter. This behavior is prohibited by the rule. To resolve it, copy the argument to a temporary variable and work on it instead: export const fn = article => article.categoryValueDtoSet.reduce((res, item) => {.

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

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

    You can use assignment to property of function parameter to initialize the value of a parameter. For example, the following code initializes the `name` property of the `greet` function parameter to the value of the `"world"` argument: js. function greet (name) {. name.value = "world"; }

  5. JavaScript Function Parameters

    The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value. Changes to arguments are not visible (reflected) outside the function.

  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. The arguments object

    This is the same behavior exhibited by all strict-mode functions, regardless of the type of parameters they are passed.That is, assigning new values to parameters in the body of the function never affects the arguments object, nor will assigning new values to the arguments indices affect the value of parameters, even when the function only has simple parameters.

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

  9. no-param-reassign

    Side effects on parameters can cause counter-intuitive execution flow and make errors difficult to track down. Rule Details. This rule aims to prevent unintended behavior caused by modification or reassignment of function parameters. Examples of incorrect code for this rule: /*eslint no-param-reassign: "error"*/ function foo (bar) { bar = 13 ...

  10. Destructuring assignment

    Smart function parameters. There are times when a function has many parameters, most of which are optional. That's especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, items list and so on. Here's a bad way to write such a function:

  11. No-param-reassign

    Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, ... If you want to allow assignment to function parameters, then you can safely disable this rule. Version. This rule was introduced in ESLint v0.18.. Further Reading.

  12. JavaScript: Don't Reassign Your Function Arguments

    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.

  13. JavaScript: Use Destructuring Assignment over Function Parameters

    We can go one step further and actually use destructuring assignments right in the function's parameters: And if we don't like the (purposefully vague) parameter names, we can always rename them!

  14. Python Function Arguments (With Examples)

    Here, we have assigned names to arguments during the function call. Hence, first_name in the function call is assigned to first_name in the function definition. Similarly, last_name in the function call is assigned to last_name in the function definition. In such scenarios, the position of arguments doesn't matter.

  15. Python Function Examples

    Function arguments can also have default values. They are known as default or optional arguments. For a function argument to have a default value, you have to assign a default value to the parameter in the function's definition. You do this with the key=value form, where value will be the default value for that parameter.

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

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

  17. Error: "Security/No-assign-param": Avoid assigning to function parameters

    Disable the security/no-assign-params rule in either the file, or the line. Please refer to solium documentation; Fix the security problem pointed out by solium. Make a copy of the param (uint number), so you don't assign value to it in number /= 10

  18. What does something: number mean in parameters?

    A string is simply text (characters). So in other words the name is text. Type checking. Basically, you force the code to assume that name is a string, and amount is a number, so autocomplete gives you the correct members for that variable. This is called type checking, basically it tells the code that the variable name is supposed to be a ...

  19. Parameter hints

    The problem is that built-ins don't actually have names for those positional-only arguments, because they're implemented in a context that doesn't need names - the C code receives the arguments via the C API which has already stuffed them into a tuple, and assuming those arguments are unpacked into local variables in the C code, those ...

  20. Use Variables with a JavaScript Module

    To "get" a value, pass the variable in as a parameter to the module function that you are calling using a Call Function action in the action chain. To "set" a variable based on the return value from that Call Function action, use an Assign Variable action to copy the result of the function into the desired variable in whatever scope.

  21. Estimating Chi-Square Distribution Parameters Using R

    The core of our exploration lies in several functions designed to estimate the chi-square parameters: dof / k Functions: These functions focus on estimating the degrees of freedom (df) using different approaches: mean_x: Calculates the mean of the data. mean_minus_1: Subtracts 1 from the mean. var_div_2: Divides the variance of the data by 2.

  22. How to assign value to function parameter in python

    1. First of all python function passes the value by object and the reference name here param is just a reference to a value hold by n. Now coming to the solution, yes it could be possible provided you pass the variable name. def init_param(var_name): globals()[var_name] = 10. n = 1. init_param('n') print n.

  23. Revisiting Enterprise Policy as Code v10

    Policy Assignment and effect parameters Using JSON for parameters works great for smaller Initiatives and single Policy Assignments. However, when assigning the big security and compliance-oriented Initiatives, such as 'Microsoft cloud security benchmark', 'NIST 800-53', and 'CIS' (often multiple of them), defining 'effect ...

  24. assignment operator within function parameter C++

    19. Those are not assignment operators. Those are default arguments for the function. A function can have one or more default arguments, meaning that if, at the calling point, no argument is provided, the default is used. void foo(int x = 10) { std::cout << x << std::endl; } int main()

  25. Why you shouldn't have virtual member functions with default parameters

    In this episode, you learn how default parameters work and why you shouldn't put them on virtual member functions. C++ Insights Episode 49: Why you shouldn't have virtual member functions with default parameters. by Andreas Fertig

  26. Using assignment operator in the parameter of a function call

    The built-in assignment operator =. is right-associative which means it groups to right, e.g. a = b = c means a = (b = c), is an lvalue expression that refers to the left hand side.. Note that in C an assignment produces a pure value, while in C++ it produces a reference (in the common language meaning of referring).. This means that you can assign a value to multiple variables:

  27. Rationale for allowing unnamed parameters in function definitions

    0. From Annex M of this document: — parameter names may be omitted in function definitions; One use I see for this is not having to cast anything to void, or using an unused attribute. But was that the rationale?