Hi, I'm Aasim Ashraf 👋. This is my first post
Today, we'll explore an interesting quirk in JavaScript regarding the use of the arguments object and function parameters.
Consider the following code:
function add(num1, num2) {
num1 = 3;
return arguments[0] + arguments[1];
}
const output = add(1, 2);
console.log(output); // Guess Output?Guessing the Output
If you guessed 3, you're Wrong! ❌ The output is 5 ✅. The arguments object is a local variable available within all non-arrow functions. If you change the parameters values, it will also change the arguments value and vice versa.
Solutions to Fix It?
- Strict Mode: In strict mode (
"use strict";), the link betweenargumentsandparametersis broken entirely.
function add(num1, num2) {
"use strict";
num1 = 3;
return arguments[0] + arguments[1];
}
const output = add(1, 2);
console.log(output); // Guess Output = 3- Destructring: You can use
destructuringto avoid this issue.
function add({num1, num2}) {
num1 = 3
return arguments[0] + arguments[1];
}
const output = add(1, 2);
console.log(output); // Guess Output = 3- Default parameters values: You can also use
default parametersto avoid this issue.
function add(num1, num2 = 2) {
num1 = 3
return arguments[0] + arguments[1];
}
const output = add(1, 2);
console.log(output); // Guess Output = 3- Rest Parameters: You can also use
rest parametersto avoid this issue.
function add(num1, num2, ...rest) {
num1 = 3
return arguments[0] + arguments[1];
}
const output = add(1, 2);
console.log(output); // Guess Output = 3Conclusion
The arguments object is a powerful tool in JavaScript, but it can lead to unexpected behavior if not used carefully. By understanding how it interacts with function parameters, you can avoid common pitfalls and write more robust code. Happy Coding! 🚀
I hope you found this post helpful. Thanks for reading! 👋