Table of contents
Definition
In programming, a positional argument refers to an argument [→] that is passed to a function or method based on its position in the function signature. The order in which the arguments are passed matters because the function assigns values to its parameters according to the sequence in which the arguments are provided.
When you call a function, positional arguments must be passed in the exact order that the function expects them. This is different from keyword arguments [→], where you specify the parameter name when passing the argument, and the order doesn’t matter.
Example or Use Case
Let’s consider an example in JavaScript with a function that calculates divides two numbers.
01: function divider(numerator, denominator) {
02: return numerator / denominator;
03: }
04:
05: // Usage
06: const result = divider(10, 5); // 10 is the numerator, 5 is the denominator
07: console.log(`The answer is ${result}`); // 2
In this case, the function divider
expects the numerator to be the first argument and the denominator to be the second argument. The order matters, so if you swap the arguments, you will get a different result:
01: const result = divider(5, 10); // Wrong order: 5 as numerator, 10 as denominator
02: console.log(`The answer is ${result}`); // 0.5
Here, the order of the arguments determines their meaning, making them positional arguments.
Conclusion
Positional arguments are obvious to developers and become second nature to anyone with programming experience. However, for those new to programming, they can take some time to get used to and are often a common source of errors when debugging code.
Here is another article you might like 😊 What Is Memoization?