We work with Javascript every day and don’t know Javascript Optional Arguments like a Jerk. Before we begin, let me show you an example. Please tell me that it can run or not.
1. Start with example
function doSomething(x) { return x * 2; } console.log(doSomething(2, true, "Kieblog"));
doSomething function declares with only one argument x. But when we call it in console, we put three arguments, but it’s OK. That’s why I told you that Arguments function in Javascript is a Jerk.
We defined doSomething with only one parameter. Yet when we call it with three, the language doesn’t complain. It ignores the extra arguments and computes the doSomething of the first one.
It takes a little bit difficult for Java developer to understand Javascript Optional Arguments. But we have no choice, need to follow and remember it.
2. Why it happened?
Don’t like Java, Javascript is a rich man. Don’t care about many things about the Arguments. We can pass one, pass two, pass three.
JavaScript is extremely broad-minded about the number of arguments you pass to a function. If you pass too many, the extra ones are ignored.
Otherwise, if you pass too few, the missing parameters get assigned the value undefined
For example, this minus function tries to imitate the-operator by acting on either one or two arguments.
If the argument in function don’t have value when we call it, the default value is undefined.
function minus(a, b) { if (b === undefined) return -a; else return a - b; } console.log(minus(10)); // → -10 console.log(minus(10, 5)); // → 5
3. The default value
When working with Javascript Optional Arguments, we need to know how to set a default value if the function doesn’t pass the value. Like this:
If you write an operator after a parameter, followed by an expression, the value of that expression will replace the argument when it is not given.
For example, this version of power makes its second argument optional. If you don’t provide it or pass the value undefined, it will default to two, and the function will behave like square
// If no pass value -> the exponent will get 2 is default value function power(base, exponent = 2) { let result = 1; for (let count = 0; count < exponent; count++) { result *= base; } return result; } console.log(power(4)); // → 16 console.log(power(2, 6)); // → 64

4. Reference for Javascript Optional Arguments
- Javascript check is a number – 3 cách kiểm tra
- Eloquent Javascript Book
- Optional Parameters in Javascript
Thank for reading my post. Don’t forget to like Facebook page!. Happy coding!