Looking for a function that takes three arguments (x, y, z) and checks if the type of all three is a string

Viewed 78

Don't know what to put before the for loop. Don't know if I need an if/else statement. Trying to have it display in the console if items in an array are strings. So I know I need consol.log

var stringOne = isString('rob','bob','carl')

function isString() {
//I dont know what to put before for loop

    for(let i = 0; i < arguments.length; i++) {
        // Dont know if i need an if/else statement
        // Trying to have it display in the console if items in an array are strings
        // So I know I need consol.log
    }

}
4 Answers

every would be appropriate here, and doing I/O (like console.log) is better left outside of the function. The name of the function suggests that it should return a boolean (true/false):

function isString(...args) {
    return args.every(s => typeof s === "string");
}

console.log(isString('rob','bob','carl'));

Because it seems like you're a beginner, I will expand upon the code that you currently have, although @trincot did the best solution.

In a for loop, you can return a value so the loop won't continue. Because you only need to check if any of them are false, may it be in position 0, 1 or 2 in the array, you can return "false" immediately.

If there are only strings, the loop will continue until it ends, and then return "true" at the end of the method.

So you don't need any code before the for loop, only an if statement that returns "false" if any of the items in the array isn't a string.

var stringOne = isString('rob','bob','carl')
var stringTwo = isString('rob','bob', 1)

function isString() {
    for(let i = 0; i < arguments.length; i++) {
      if (typeof arguments[i] != 'string') {
        return false
      }
    }

  return true
}

console.log({stringOne});
console.log({stringTwo});

Something like this in the loop ought to do it:

this_arg = arguments[i];
if (typeof this_arg === 'string') console.log("arg number " + i + " is a string");

It shows how to do it a bit here

You may find every useful here. It iterates over the array you've made from the arguments and checks to see if each element matches the condition. If they all match it returns true, otherwise false.

function isString() {
  return Array.from(arguments).every(str => {
    return typeof str === 'string';
  });
}

console.log(isString('rob','bob','carl'));
console.log(isString(2,'bob','carl'));

Related