1

This should be simple question.

I have been using JavaScript for a couple years, and strongly typed languages (such as Java and C++) for even longer. I recall learning that, in the strongly typed languages, having to check types of arguments before doing stuff with them is symptom of bad code. However, does this carry over to languages like JavaScript?

/* in client-side JavaScript, for example, I find myself automatically doing stuff like this:

function myFunction(array1, array2) { if (array1 !== Array.from(array1)) return null; if (array2 !== Array.from(array2)) return null; // some array action here with arrays array1,array2 } 

*/

1
  • 2
    It is ok to check for types in Javascript, wether you do it when is useful or do it always because you're used to typed languages is a personal preference. You can always rely on Typescript if you absolutely need taxonomy to develop. Commented Sep 23, 2017 at 17:19

2 Answers 2

2

Yes, before using it, you could take Array.isArray for checking if a variable is an array.

The Array.isArray() function determines whether the passed value is an Array.

The check for type is necessary if data comes from an unknown source, like to work with a alibrary, where the vendor does not know in advance what type of data the user supplies.

Some libraries uses a mixed mode for data where the data could be a single item or an array of items. In this case a check is necessary to determine if the item has to be wrapped in an array or not.

function myFunction(array1, array2) { if (!Array.isArray(array1)) return null; if (!Array.isArray(array2)) return null; // some array action here with arrays array1,array2 } 
Sign up to request clarification or add additional context in comments.

Comments

0

The only place I have checked it was while writing the test cases.

I would say test case is the perfect example. We will be checking for both positive and negative scenarios. I hope you understand, if not let me know.

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.