This code is kind of ambiguous.
arguments
represents all arguments given to a function as array-like object.
charAt
is a function defined on String.prototype
So if (x.chatAt(0) == '[') { … }
will only work if x
is a String, otherwise you will get the Error as described above.
All in all (in es6):
const foo = (...args) => {
for (let arg of args) {
if (arg.chatAt(0) == '[') { … }
}
}
foo({}) // Error
foo('[', {}) // Error, because arg2 is not a string
foo('[', ']') // No Errors, because each arg is a String
So there are two things you could do:
convert each arg to a string, before running the test: if (''+ arg.charAt(…)) …
, or if (arg.toString().charAt())
throw an Error if an Argument is not a string. To test if a variable is a String can be found here