8 Techniques to Write More Concise JavaScript Code

aifou
9 min readMar 12, 2024
  1. Pure Functions

Pure functions are functions that always return the same output given the same input. Apart from the inputs provided, it does not depend on any external variables, nor does it affect/change any external variables. Having pure functions makes testing easier because they make testing super easy as you can stub/mock the inputs and test your expected values anytime. Let’s look at an example below

let name = "Yu DongSu";
const splitName = () => {
name = name.split(' ');
}
name = splitName();
console.log(name); // outputs [ 'Yu', 'DongSu' ]

While the above code looks alright. No kidding. This is because the `splitName` function depends on an external variable named `name`, if someone else starts changing this variable, the function `splitName` will start giving different outputs. Making it an impure function, because we would still be calling `splitName()` but the output would be different.

Let’s make it a pure function and see what it looks like:

let name = "Yu DongSu";
const splitName = (nameString) => {
return nameString.split(' ');
}
name = splitName(name);
console.log(name); // outputs [ 'Yu', 'DongSu' ]

With the above changes, `splitName` is now a pure function because:

* It only depends on the input (`nameString` input).
* It does not mutate/reassign any external variables

--

--