"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Take advantage of rest parameters

Take advantage of rest parameters

Published on 2024-11-08
Browse:733

Take advantage of rest parameters

I went through the node.js material today and I used path.join method. This method is used widely in node.js.

path.join("/foo", "bar"); // Returns: '/foo/bar'
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'

As you could realize, you can execute this method with as many parameters you want. That's how I got the idea for this short post.

The concept which is used behind is named rest parameters in js.

let's imitate path.join

const imitatePathJoin = (...args) => {
  return args.join("/");
}

console.log(imitatePathJoin('/home', 'js', 'dist', 'app.js')); 
// "/home/js/dist/app.js" 
console.log(imitatePathJoin('/home', 'js', 'dist', 'app.js', "something", "something")); 
// "/home/js/dist/app.js/something/something

Simple as that. This concept can be really useful if you find yourself in a situation that you want to have the function which could accept indefinite number of arguments and do something with them.

Conclusion

There are many more things which path.join method does. For example, it will throw the error if parameter is not a string. But rest parameters is the crucial concept how it is implemented and that is the thing I wanted to show in the post.

Hope you could learn something new from this one. Take care!

Release Statement This article is reproduced at: https://dev.to/machy44/take-advantage-of-rest-parameters-3km1?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3