Day 9: Return Length of Arguments Passed
Write a function argumentsLength that returns the count of arguments passed to it.
Example 1:
Input: args = [5]
Output: 1
Explanation:
argumentsLength(5); // 1
One value was passed to the function so it should return 1.
Example 2:
Input: args = [{}, null, "3"]
Output: 3
Explanation:
argumentsLength({}, null, "3"); // 3
Three values were passed to the function so it should return 3.
Constraints:
argsis a valid JSON array0 <= args.length <= 100
Overview:
We need to count the number of arguments passed to function argumentsLength. Here the arguments are passsed in the form of rest parameters.
Rest Parameter:
In Javascript, the rest parameter is a feature that allows a function to accept an indefinite number of arguments. It is denoted by three dots (...) followed by a parameter name. The rest parameter collects all the remaining arguments passed to a function into an array, even if the number of arguments is not known in advance. If no additional arguments are passed, the rest parameter will be an empty array.
- Syntax:
function functionName(...args) {
// Function body
}
The rest parameter (args in the above example) can have any valid identifier name, but it is conventionally named args or rest to indicate its purpose.
The rest parameter is placed as the last parameter in the function's parameter list.
You can have other parameters before the rest parameter, but the rest parameter must be the last one.
-
Accessing Arguments:
Inside the function, you can treat the rest parameter (args) as an ordinary array.
You can access the elements of the array using array indexing or array methods likeforEach(),map(),filter(), etc. -
Example:
function sum(...args) {
let total = 0;
for (let number of args) {
total += number;
}
return total;
}
console.log(sum(1, 2, 3, 4)); // Output: 10
console.log(sum(5, 10, 15)); // Output: 30
console.log(sum()); // Output: 0 (no arguments passed)
The sum() function uses a rest parameter (args) to collect all the arguments passed to it. It then iterates over the args array and calculates the sum of all the elements. The rest parameter provides flexibility and eliminates the need to explicitly define a fixed number of parameters in the function declaration, making the code more concise and adaptable. It is important to note that the rest parameter only collects the additional arguments passed to the function and does not include arguments passed through named parameters or default parameter values.
Spread Operator / Rest Parameter:
After seeing the rest parameter you may feel that it is similar to spread operator but well it is not. The spread operator and the rest parameter both looks same because they both use the same syntax (...) in Javascript, but they serve different purposes and are used in different contexts.
Let's explore the differences between the two:
The spread operator is used to unpack elements from an array or an iterable object (like a string or a set) into individual elements. It spreads the elements out. It's commonly used in situations where you need to combine or clone arrays, pass individual elements of an array as arguments to a function, or convert an iterable into an array. While the rest parameter is useful when you want to write functions that can accept a variable number of arguments i.e., It allows you to handle a dynamic number of function arguments without explicitly defining individual parameters.
To conclude let's take a example for spread syntax:
Example:
const array = [1, 2, 3];
console.log([...array]); // Output: [1, 2, 3]
const string = "hello";
console.log([...string]); // Output: ['h', 'e', 'l', 'l', 'o']
const set = new Set([1, 2, 3]);
console.log([...set]); // Output: [1, 2, 3]
Approach 1: Using argument object
To solve this problem, we can leverage the fact that Javascript provides the arguments object, which is an array-like object that contains all the arguments passed to a function. We can simply retrieve the length of the arguments object and return it.
To be more specific, In Javascript, arguments are passed as an array-like object. Because of this, you can use a lot of the same kind of functions on arguments as you can on arrays, including using arguments.length.
Note1: The arguments object is automatically available inside functions and holds the arguments passed to the function.
Note2: Usingarguments.lengthprovides direct access to the length without creating an intermediate array (args), which may be beneficial in certain scenarios.
Implementation:
var argumentsLength = function(...args) {
return arguments.length;
};
Complexity Analysis:
-
Time complexity: O(1)O(1)O(1)
-
Space complexity: O(1)O(1)O(1)
Approach 2: Using rest parameter
We can use the rest parameter syntax (...args) to gather all the arguments into an array called args.
The args.length expression is used to access the length property of the args array, which represents the number of arguments passed to the function.
Implementation:
var argumentsLength = function(...args) {
return args.length
};
Complexity Analysis:
-
Time complexity: O(1)O(1)O(1)
-
Space complexity: O(1)O(1)O(1)
The main difference between the above two code snippets lies in how they access the length of the arguments:
- The first code snippet (
arguments.length) accesses the length property on the special arguments object itself, without explicitly converting it to an array. - The second code snippet (
args.length) accesses the length property directly on the array created by the rest parameter.
Since the question was too simple, let us expand our understanding of arguments and arrays.
Given that "arguments are passed as an array-like object" in the approach part, don't you believe javascript will include some methods or properties to cope with common capabilities for manipulating, transforming, querying, and iterating?. Yup, you got it right but does that mean that arguments and array are same? Nope. Let's discuss where the difference lies!!
The arguments object in Javascript is a special object that is automatically available inside functions. It holds the arguments passed to the function when it is invoked. Although arguments can be accessed using index notation like an array, it is not a true Javascript array. The main reasons are its type methods supporting, some difference in behavious when using the same property.
Here are some important distinctions between array-like objects, such as the arguments object in Javascript, and actual arrays in more detail:
- Type: The arguments object is not an instance of the Array class. It is an array-like object, which means it has some array-like characteristics but lacks many of the built-in methods and properties that are available to arrays.
- Array Methods: Arrays in Javascript have numerous built-in methods like
forEach(),map(),push(),pop(), and more. However, the arguments object does not have these array methods available. It does not inherit the array methods from theArray.prototype. - Length: Both arrays and the arguments object have a length property that indicates the number of elements. However, the length property of the arguments object is automatically updated to reflect the number of arguments passed to the function, whereas in arrays, the length property represents the number of elements in the array.
- Modifiability: Arrays can be modified using methods like
push(),pop(),splice(), and more. In contrast, while the arguments object's entries can be modified in non-strict mode (a practice that is generally discouraged), you cannot change its length or use array methods likepush(),pop(), andsplice()