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?
>Solution :
I can see you are trying to use the spread operator while calling the function, but in that case, you need to use the rest parameter syntax if you want to catch all the arguments being passed to your function.
When you use a spread operator like this –
strings = ["hamza", "Hamza", "name", "Name"]
myfunc(...strings)
This is what it would do behind the scenes for all the values from the array –
strings = ["hamza", "Hamza", "name", "Name"]
myfunc(strings[0], strings[1], strings[2], strings[3]);
// OR
myfunc("hamza", "Hamza", "name", "Name");
If you have a fixed and small number of elements in the array you can do this –
function myfunc(arg1, arg1, arg3, arg4){
console.log(arg1, arg1, arg3, arg4)
}
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.
function myfunc(...str){
console.log(str)
}
strings = ["hamza", "Hamza", "name", "Name"]
myfunc(...strings)
Rest parameters
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.
Check this out for more details –