You hear a lot of programmers joke about JavaScript not being a “real” programming language.

Besides not having a Class based system of inheritance, JS is also dynamically typed unlike C#, Java, Scala… you know, all those real programming languages. But the speed, flexibility and ease of use are what led us to write JS! Types be damned!

Of course there is a cost to the flexibility that JS offers, some of which may be negated if you’re using Typescript, but using the following defense tactics while writing code can save you a pesky bug down the road (that also rhymes so you know it’s true 😉).

Use Default Params

If you have a function which depends on an argument being present and being of a certain type then you should consider using default parameters in your function’s signature.

const addNameToNameArray = (name, nameArray) => {
  if(name.length){
   nameArray.push(name)
  }
  return nameArray
}

Simple enough right? We take a name and a name array and then simply add the name to the array if one is present. We are making some assumptions here however that the name will be of a type that has a length property and that our nameArray will be, well, an array. If either one of these conditions is not met, we will fail spectacularly.

const addNameToNameArray = (name = '', nameArray = []) => {
  if(name.length){
   nameArray.push(name)
  }
  return nameArray
}

Ahh, much better. Now we can sleep at night, knowing this useless function won’t break production once it’s deployed if it’s called with a missing argument.

#javascript

Writing Defensive Javascript
1.15 GEEK