Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

my function won't iterate over each item and log them to the console

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 –

  1. Rest Parameters
  2. Spread Operator
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading