Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Functions: Use Properties As Arguments

Monday, July 23, 2018

JavaScript Functions: Use Properties As Arguments

To make your functions developer friendly it is sometime useful to define your a arguments as properties.  This way your code is self documented, instead of having the developers read documentation on the code you can just use the arguments to document the code so that it would reduce the confusion from the developer.


        var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        var copiedNumbers = [];

        function copyNumbers(args) {

            function copyAll(original, copy, size) {
                for (var i = 0; i < size; i++) {
                    copy[i] = original[i];

        copyNumbers({ orignal: numbers, copy: copiedNumbers, size: numbers.length });

        console.log("original " + numbers);
        console.log("copies " + copiedNumbers);


The code above encapsulates the copyAll function inside the copyNumbers function, which performs a for loop to copy an array of numbers.  Since the arguments object is an object, it can have properties.  So we pass in properties instead of parameters to make the code more readable.  However, the code is not as efficient as a direct call to the function.  Just like anything in programming there's a trade-off.  It's up to you, whether you are willing to make that trade-off.

No comments:

Post a Comment

Search This Blog