my function won’t log all items to the console.
function myfunc(str){
//return str.split('')[0].match(/[A-Z]/)
console.log(str)
}
strings = ["hamza", "Hamza", "name", "Name"]
myfunc(...strings)
I’ve tried the spread operator and the apply function but both methods only log the first item. why does it not iterate over each item?
3
Answers
Try this:
I can see you are trying to use the
spread
operator while calling the function, but in that case, you need to use therest parameter
syntax if you want to catch all the arguments being passed to your function.When you use a
spread
operator like this –This is what it would do behind the scenes for all the values from the array –
If you have a fixed and small number of elements in the array you can do this –
But if the number of arguments is not fixed then you can use the
rest operator
, the rest operator will catch all arguments being passed to function in an array.Rest parameters
Check this out for more details –
A function specified with a single parameter will always take single parameter. It cannot take more than that. You are spreading the
string
variable and it is passing the first element of the array to the function since it can only take one parameter.If you have specified two parameters then spread operator would pass first two elements of the array.
If you want to spread the array, then just simply pass it to the function without spreading it. And then spread it inside the
console.log()
. For example:Output:
Or, if you want to print them in new lines. You could use
join()
method of Array data type. For example:Output: