-1

How can I take all arguments (args) in an array and combine them into one variable with spaces in-between, but infinitely and less sketchy. I'm somewhat new to JavaScript, so I apologize if I'm missing something apperent.

var keyword = (args[0]);
if (args.length == 2) {
    keyword = (args[0] + " " + args[1])
} else if (args.length == 3) {
    keyword = (args[0] + " " + args[1] + " " + args[2])
};
2

2 Answers 2

3

args is an array. So you can join that array using array.join() method.

const keyword = args.join(' ');
Sign up to request clarification or add additional context in comments.

Comments

1

A more safe and straight forward approach would be:

function formatKeywords(...items) {
  return items.join(' ');
}

function formatKeywords(...items) {
  return items.join(' ');
}

console.log('Handle empty args:', formatKeywords());
console.log('With args:', formatKeywords('aa', 'bb'));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.