0

I want to check out whether the arguments provided in a function are strings and for this I'm using the following condition:

function someFunction (variable1, variable2, variable3) {
   ["variable1", "variable2", "variable3"].forEach(function (each) {
      if (!(/*something*/[each].constructor.name === "String")) throw new TypeError(
         each + " must be a string. " + /*something*/[each].constructor.name +
         " was given instead."
      );
      else ...
   });
}

Had the check occurred in the global namespace, I could've used window[each], since variables are properties of window, like below:

var variable1, variable2, variable3;

["variable1", "variable2", "variable3"].forEach(function (each) {
   if (!(window[each] instanceof String)) throw new TypeError(
      each + " must be a string. " + window[each].constructor.name + " was given instead."
   );
   else ...
});

How can the above be achieve inside a function?

2
  • 1
    There's no way to access local variables by name. window[name] can only be used with global variables, there's nothing equivalent for local variables. Commented Aug 30, 2016 at 18:42
  • Thanks for letting me know @Barmar Commented Aug 30, 2016 at 21:25

2 Answers 2

1

You only want to allow strings, right? If so - use arguments, typeof and the code below:

function someFunction(variable1, variable2, variable3) {
    [].forEach.call(arguments, function(each) {
        console.log(typeof each);
        if (typeof each != 'string') {
            throw new TypeError(
                each + " must be a string. " + /*something*/ each.constructor.name +
                " was given instead."
            );
        } else {
            console.log("its a string")
        }
    });
}

someFunction("foo", "bar", ["baz"])
Sign up to request clarification or add additional context in comments.

Comments

1

inside forEach, each loops over the variables

function someFunction (variable1, variable2, variable3) {
   [variable1, variable2, variable3].forEach(function (each) {
      if (!(each.constructor.name === "String")) throw new TypeError(
         each + " must be a string. " + each.constructor.name +
         " was given instead."
      );
      else ...
   });
}

2 Comments

Fixed to use the variables. Not sure what OP is asking for.
Your answer works fine @JeromeWAGNER. I edited the condition inside if, because it only accepted strings created through String().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.