JavaScript

How to insert default arguments in a function in JavaScript

April 11, 2022

How to insert default arguments in a function in JavaScript

In this article you will learn how to insert default arguments in a function in JavaScript, that is, insert the value for an argument of a function

default arguments in a function in JavaScript thumb

Hey you programmer, ok? Let’s learn more about JavaScript functions and arguments.

Currently in JavaScript it is not possible to insert default value for arguments in functions, not in their declaration

But there are alternatives to insert and check arguments in another way

Every JavaScript function receives a special variable called arguments and we can query the arguments through it.

Here’s a hypothesis:

function test(x) {
 if(arguments[0] === undefined) {
  x = 10;
 }
 console.log(x);
}

test();
test(5);

Here we will have outputs 10 and 5, respectively, that’s why we check arguments and modify its value if it came as undefined

So we managed to change the function’s argument this way and add a default value

The ES6

In JavaScript version ES6 it is already possible to add the argument with default value in the function definition itself

See this example:

function test(x = 10) {
 console.log(x);
}

test();
test(5);

This way we have the same output as the previous example, but with much less code.

Be careful when using ES6 features as they are not standardized in all browsers and may result in errors in your software

Conclusion

In this article we learned how to add default arguments in a JavaScript function

For the current version of JavaScript it is necessary to access the special variable arguments and check if the argument came with the function call

In ES6, the resource is native and can be written in the definition of a function

Do you want to learn more about JS? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x