How (and What) to Name Things in Javascript

Naming conventions in JS generally focus on mechanics, ignoring semantics altogether. As part of a clean coding practice- that is, writing code for other engineers (including Future You) to consume- an ounce of clear writing is worth a pound of comments.

This post will share a some ideas and a simple rubric for how to name variables and functions in Javascript – descriptively – to help your code become self-documenting.

Basic Conventions for Naming in JS

The following are common rules for naming variables in JS, mostly having to do with formatting:

  • -camelCase objects, functions, and instances
  • -PascalCase is for constructors, classes (React components)
  • -UPPERCASE_IS_SUGGESTED for global variables and constants
  • -aVariableName should start with a letter
  • -don’t use single letter variable names, or scrunched abbreviations/concatenations
  • -don’t use leading or trailing underscores
  • -acronyms should be all uppercased, or all lowercased

You can find a good list of these rules with examples in the Airbnb Style Guide on Github. While these are a good starting point, they don’t really touch on writing self-documenting code.

Semantic Guidelines for Naming Variables

Where the common resources fall short is in what to name things, rather than how. Quoting Jeff Atwood on Twitter here: “There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.” And here’s a “why” we would care about this, from the Airbnb styleguide: “Names are for readability, not to appease a computer algorithm.”

Outside the trivial world of HackerRank exercises and job interviews, the way you name things has a lasting impact. While you’re “in the zone” it’s conceivable you’d keep the purpose of a throwaway variable in working (human) memory. But as you broaden the scope of work, you’ll have to re-contextualize old variables in the context of new problems.

When naming things in production code, here are a couple heuristics that often fall by the wayside in tutorials/Stack Overflow/code-golfing in algo challenges:

Be Specific

So let’s start with one of the rules from above: “don’t use single letter variable names, or scrunched abbreviations/concatenations.” Unless you’re programming firmware for a microwave or something (probably not in JS, yet) two things are likely:

  1. Your code will get transpiled before it hits production
  2. Your code will get minified before it hits production

This means you can name things with as much specificity as you need to accurately describe the what and the why of it. This means writing descriptive names in code won’t hurt your bundle size. Your variable and function names will be long-gone by the time a client needs to process any code.

Variable names get longer with scope.

A narrower scope needs shorter names to convey full meaning. Take this simple mutation:

const clientList = [...];

const clientNames = clientList.map(client => client.name);

A common temptation in the map() statement could be (c => c.name) for brevity. But when you come back to it later, you have to slow down and contextualize what c is all about. It’s trivial here because the example is trivial.

Complexity tends to grow exponentially. Don’t try to flex on how “smart” you are as an engineer.

When describing complex functionality, it pays to explain your thought process with variable names your mom could understand. If that’s too difficult, consider it a red flag that your “thing” is doing more than one thing. Break it up.

If it takes a very long variable name to describe what’s going on, it’s a red flag you’ve got code that needs further abstraction. For instance, something like clientInvoiceDisclosureAcceptButtonClickHandler in a React component says you should probably break out some subcomponents to narrow the scope.

The temptation in a case like this is to give it a short but meaningless (or otherwise inscrutable) name and move on, rather than fix the bloat. This may be a sign of depression. It’s basically saying your code is hopeless, so why bother? Fixing it now will speed you up in the future.

Imply the Domain and the Return Value

A good name tells a person without domain-specific knowledge what to expect. I once found a variable called balances that returned a boolean, in a React component I had never seen before. The person writing the component knew the use of balances would be truthy or falsy, but that person was long gone.

To avoid the problem of domain knowledge and false assumptions, here’s a simple pattern to follow for creating useful names in JS:

Item

domainNoun clientDetails accountFlags

Flag

is, has, can, will, should hasDetails shouldShowDetails

Function

verbNoun getDetails shouldComponentUpdate

I’ve had feedback about “should” implying a function like shouldComponentUpdate, rather than a boolean variable. The important part about shouldShowDetails and shouldComponentUpdate is the true or false return value, and not the implementation.

Conclusion

Descriptively and accurately naming variables like this can save you, Future You, and the next engineer a lot of headaches when revisiting your code out of context.

As a disclaimer, these are the (strongly-held) opinions of a React developer. I’ve applied a fair amount of the thinking from Clean Code by Robert Martin, from Java into Javascript. Otherwise a lot of these are lessons I learned through working on legacy code.

It seems there are very few resources specific to clean coding in Javascript. The general vibe seems to be that JS is moving too fast for time-tested best practices to be relevant, but that strikes me as throwing the baby out with the bathwater.

Got other best practices for naming things? Resources you’d turn to for clean coding practices? Drop me some ideas in the comments box below!

6 Anti-Patterns in React Functional Components

Stateless/functional components as a React pattern ideally simplify your code. Ideally. I’ve seen some doozies though…

I’ll refactor it later…

Front-end React in the wild is rarely the heavenly, best-practicing code we see in online tutorials and presentations at meetups. Every line is written for a reason, and among the head-scratchers I assume the reason was “I’m in a rush” or “I’ll get back to it later” (which never comes).

This is Part One of a two-part exercise in therapeutic refactoring, where I’ll point out some readability anti-patterns (as I see them). In Part Two I’ll suggest some alternatives to help feng shui a bloated functional component into something more elegant.

This refactoring should be a necessity rather than a luxury when working on business logic, because cognitive energy all comes from the same place- don’t waste it trying to tease understanding out of a hairball component.

About the Repo

I’ll be working with pseudo-code on a create-react-app repo I lovingly named mcfatty-fat-fat because Functional Components are sometimes called “fat arrow functions.” The code is commentary on my own eating habits. I dashed it off with errors and holes galore because #writing-this-on-the-weekend and also cuz the whole point is about inheriting less-than-perfect code.

The Base part has to do with the most reusable components and how excessive abstraction can lead to Hell in the file structure. The Composite part is in some ways a primal scream about anti-patterns I see in day-to-day life as an engineer. That’s where we’ll find the meat (and ice cream) of this post.

The Base Component Library

Yay for reusable components! We’re doing good with the relatively flat file structure before, but going into the danger zone on our DatePicker component.

Our venture into fs.Hell begins with the effort it takes to determine which of these is even the top-level component. Does Container hold DatePicker? Or is DatePicker the parent? Is the pattern consistent between other Base components? Can I just get to coding already?

OK start coding. Don’t forget to import everything with the correct relative paths! Hope you like counting dots…

This is a question of balance. Sometimes it makes sense to separate concerns, but the judgment call is how far apart those concerns actually are.

In a lot of cases, what looks pleasing to the component’s author will cause the next engineer to spend a lot of effort tabbing between files, kind of like chasing the Gingerbread man. Treat engineer clicks like customer clicks: the fewer the better.

The Composite Component

Refer to <CheatDay /> and <SlimDown /> side-by-side: both of them describe my guilty enjoyment of burgers and ice cream, but <SlimDown /> has better intentions than <CheatDay /> in terms of readability.

The <CheatDay /> component has all the anti-patterns I’ll discuss, and they’re cleaned up in the <SlimDown /> component. Let’s start with anti-patterns from the top!

Anti-Pattern 1: Ambivalent Prop De-structuring

The ambivalence is mostly mine. Sometimes it helps to be explicit about certain constants coming from props, like in <CheatDay />:

const CheatDay = (props) => {
  const {
    items,
    healthWarnings,
    iAmSad,
    highFructoseCornSyrup,
  } = props;

  ...

Or you can be more DRY about it and de-structure the props upon entry, like in <SlimDown />:

const CheatDay = ({
  items,
  healthWarnings,
  iAmSad,
  highFructoseCornSyrup,
  }) => {

  ...

The problem with this ambivalence is when multiple engineers touch the repo and treat this pattern like it’s only a stylistic decision (which it mostly is). When multiple files lack consistency in this or other decisions (for instance, where to put PropTypes), that’s when it gets hard to read.

Anti-Pattern 2: Cryptic Booleans That Make You Wonder

This anti-pattern is best to observe on wider screens because it has to do with line spacing, which I’ve broken on mobile to prevent horizontal overflow

const overIndulge = iAmSad && items.mcDonalds.bigMac
  || items.mcDonalds.nuggets && healthWarnings.splice(0, 2).find('unheeded');

What a clever developer! 👏👏. #stackOverflowPoints

One of the first ways to clean this up would be to space it out into discrete, human-readable statements:

const overIndulge =
  iAmSad &&
  items.mcDonalds.bigMac || items.mcDonalds.nuggets &&
  healthWarnings.splice(0, 2).find('unheeded');

We write code for people, not computers. Err on the side of semantics and don’t make people think.

Anti-Pattern 3: Declarations Living Far from Actual Usage

The next issue is how distant a declaration is from where it’s actually used. Try finding where overIndulge does anything in <CheatDay />. Give up? Trick question: the engineer wrote it and never actually used it.

This is something a linter would pick up, but still instructive. Code is harder to read (and generally more error-prone) when functions and variables are declared far from where they’re used.

In <CheatDay />, const overIndulge is defined on Line 13 and never used. If overIndulge was a factor in say, a <PunishingMeal /> subcomponent, you could define it under the relevant namespace like in <SlimDown />:

const PunishingMeal = () => {
  const overIndulge =
    iAmSad &&
    items.mcDonalds.bigMac || items.mcDonalds.nuggets &&
    healthWarnings.splice(0, 2).find('unheeded');

  return (
  <div className="classes more-classes flex">
    <h1 className="heading-six for-some-reason">
      {
        guiltyPleasures
      }
    </h1>
  </div>
  );
};

At this distance it’s not hard to see how conditions about whether to overIndulge play no actual role in the makeup of my <PunishingMeal />.

Anti-Pattern 4: Subverting Core HTML Properties with CSS

Let’s say you need prominence on a screen reader for accessibility, but the UI calls for something smaller. So you do this quick-and-dirty thing:

<div className="header super-stylish-header">
  <h1>Cheat Day is like, super healthy and stuff</h1>
  <span>Enjoy your { highFructoseCornSyrup }</span>
</div>
<div className="classes more-classes flex">
  <h1 className="heading-six for-some-reason">
    {
      guiltyPleasures
    }
  </h1>
</div>

In this example you have a couple of no-no’s. To begin with, your page should only have one <h1> tag. Using an <h1> again and then formatting it as an <h6> is hacky. There are better ways to get visual styling to play along with accessibility, without making the next person think.

Anti-Pattern 5: Complexity is More than a Performance Issue

Nested loops are often a clever trick that gets the job done when you’re laser-focused on a particular component working like right now. Try revisiting the code in six weeks though. Take this clever piece of nonsense I dashed off:

const guiltyPleasures = items
  .map(item => {
    const foodItems = Object.keys(item);
    const ingredients = foodItems.map(foodItem => foodItems[foodItem]);

    const ignoreFullness = () => {
      consume(highFructoseCornSyrup);
      iAmSad ? ignore(healthWarnings[0]) : ignore(healthWarnings[2]);

      ...

While the nested map() statements appear trivial at the time of writing, they add up to a confusing mess where suddenly all sorts of weird brackety shit (technical term) becomes justifiable.

This is where engineer performance becomes more of a problem. We talk about “Big O” considerations in coding interviews, but getting clever about how tersely we can jam out some code can cause serious readability problems for the humans who consume your components.

Considering that software engineers are notoriously bad with people, good code should prevent anyone from trying to read your mind.

Anti-Pattern: Conditional Logic Inside of JSX

Here’s an example of how being able to do something doesn’t mean you should do something.

/* eslint-disable no-unused-expressions */
return (
  do {
    if (iAmSad) {
      <Container>
        ...
      </Container>
    } else if (!iAmSad && items.häagenDazs) {
      <Container>
        ...
      </Container>
    } else {
      null
    }
  }
)
}
/* eslint-disable no-unused-expressions */

Manually disabling eslint in the first place is a red flag. But beyond that, where are the semantics? Return do if? What the Hell?

There’s no good reason code can’t more-or-less read like natural language, especially in React where we get to name things however we want. return (verb) output (noun). (verb – “do”) 什么 (noun – “something”). Works in English, Mandarin, Javascript, probably not PHP but that’s a different conversation.

Anti-Pattern 6: Obscure Patterns Because You’re So Smart

Back to the example above:

/* eslint-disable no-unused-expressions */
return (
  do {
    if (iAmSad) {
      <Container>
        ...
      </Container>
    } else if (!iAmSad && items.häagenDazs) {
      <Container>
        ...
      </Container>
    } else {
      null
    }
  }
)
}
/* eslint-disable no-unused-expressions */

The do block works, and I’m sure it has a place in JS- namely your side project.

I’m all about learning new functionality, new patterns, etc. I aspire to be Billy Badass senior dev passionate ninja cyborg from the future. Good for me!

When I’m writing code for pay though, I have to write it for the next engineer- in all likelihood the one who’s doing it as a job more than a calling. There are more of them in the world than there are of me.

Using things like static methods, context above props, state, or Redux, refs, etc. is clever. Look at you, Mr./Ms. Fancypants developer! You did a thing!

Also, whatever the Hell this is:

{ iAmSad && <div
  className="confusing-logic mixed-in-view"
  position="bottom">
    <p>Treat yo-self! You deserve this for being you.</p>
</div>  }

Umm… what!? Isn’t && supposed to return true or false? This is only half a rhetorical question. Even if you can explain why or how this horrible thing works, the unexpected pattern causes friction for the next engineer trying to make heads or tails of the component.

Good code is something junior devs and indifferent old-timers can wrap their head around with minimal effort. The Golden Rule is “don’t make people think”. Respect the limits of other peoples’ attention.

And Here’s the Whole Shebang of Our Horrible Component

import React from 'react';
import PropTypes from 'prop-types';
import { Container, Input } from '../Base';

const CheatDay = (props) => {
  const {
    items,
    healthWarnings,
    iAmSad,
    highFructoseCornSyrup,
  } = props;

  const overIndulge = iAmSad && items.mcDonalds.bigMac
    || items.mcDonalds.nuggets && healthWarnings.splice(0, 2).find('unheeded');

  const guiltyPleasures = items
    .map(item => {
      const foodItems = Object.keys(item);
      const ingredients = foodItems.map(foodItem => foodItems[foodItem]);

      const ignoreFullness = () => {
        consume(highFructoseCornSyrup);
        iAmSad ? ignore(healthWarnings[0]) : ignore(healthWarnings[2]);

        /* eslint-disable no-unused-expressions */
        return (
          do {
            if (iAmSad) {
              <Container>
                <Input type={ items.mcDonalds }>
                  <ul>
                    { items.mcDonalds.bigMac.map(ingredient => (
                      <li>
                        { ingredient }
                      </li>
                    )) }
                  </ul>
                </Input>
              </Container>
            } else if (!iAmSad && items.häagenDazs) {
              <Container>
                <Input type={ items.mcDonalds }>
                  <ul>
                    { items.häagenDazs.iceCream.map(ingredient => (
                      <li>
                        { ingredient }
                      </li>
                    )) }
                  </ul>
                </Input>
              </Container>
            } else {
              null
            }
          }
        )
      }
      /* eslint-disable no-unused-expressions */
    });

  return (
    <Container className="bag paper-bag brown-paper-bag bag-xl">
      <div className="header super-stylish-header">
        <h1>Cheat Day is like, super healthy and stuff</h1>
        <span>Enjoy your { highFructoseCornSyrup }</span>
      </div>
      <div className="classes more-classes flex">
        <h1 className="heading-six for-some-reason">
          {
            guiltyPleasures
          }
        </h1>
      </div>
      <div className="footer footerClasses">
        { iAmSad && <div
          className="confusing-logic mixed-in-view"
          position="bottom">
            <p>Treat yo-self! You deserve this for being you.</p>
        </div>  }
        { !iAmSad && <div
          className="confusing-logic mixed-in-view"
          position="bottom">
            <ul>
              { healthWarnings.map( warning => (<li>{ warning }</li>))}
            </ul>
        </div>  }
      </div>
    </Container>
  );
}

CheatDay.propTypes = {
  items: PropTypes.shape({
    mcDonalds: PropTypes.shape({
      bigMac: PropTypes.shape({
        allBeefPatties: PropTypes.array,
        specialSauce: PropTypes.mystery.isRequired,
        lettuce: PropTypes.vegetable,
        cheese: PropTypes.dairy,
        pickles: PropTypes.monster,
        onions: PropTypes.vegetable,
        sesameSeedBun: PropTypes.carbs,
      }),
      nuggets: PropTypes.shape({
        chickenProduct: PropTypes.mystery.isRequired,
        sauce: PropTypes.string.isRequired,
      }),
      fries: PropTypes.shape({
        potato: PropTypes.starch.isRequired,
        oil: PropTypes.oil.isRequired,
        salt: PropTypes.deliciousness,
      }).isRequired,
    }),
    häagenDazs: PropTypes.shape({
      iceCream: PropTypes.shape({
        ice: PropTypes.coldness.isRequired,
        cream: PropTypes.umami.isRequired,
      }).isRequired,
      toppings: PropTypes.shape({
        reeses: PropTypes.bestCandyEver,
        whippedCream: PropTypes.umami,
      })
    }),
  }),
  healthWarnings: PropTypes.array,
  iAmSad: PropTypes.boolean.isRequired,
  highFructoseCornSyrup: PropTypes.hazard.isRequired,
};

Continue to Part 2 for the Refactor

A Semantic Pattern for Simplifying Functional Components

Harnessing the power of hoisting (no longer just an interview question), you can rearrange a functional React component however you want by cutting it into smaller sections that flow from top to bottom. So for instance you can describe the overall structure of your component at the top of your component. When you first see it, it becomes a table of contents:

const CheatDay = ({
  items,
  healthWarnings,
  iAmSad,
  highFructoseCornSyrup,
  }) => {

  const CheatDayComponent = () => (
    <Container className="bag paper-bag brown-paper-bag bag-xl">
      <CheatDayHeader />
      <PunishingMeal />
      <CheatDayFooter />
    </Container>
  );

  ...

Progressing downward, you then define the subcomponents from top to bottom:

const CheatDayHeader = () => (
  <div className="header super-stylish-header">
    <h1>Cheat Day is like, super healthy and stuff</h1>
    <span>Enjoy your { highFructoseCornSyrup }</span>
  </div>
);

...

During the process, all of your props, etc. stay in scope because each subcomponent is a simple arrow function. When you’re cutting the component into subcomponents like this, you can then encapsulate specific logic to bring it closer to where it’s actually used, like this:

const PunishingMeal = () => {
  const overIndulge =
    iAmSad &&
    items.mcDonalds.bigMac || items.mcDonalds.nuggets &&
    healthWarnings.splice(0, 2).find('unheeded');

  return (
    <div className="classes more-classes flex">
      <h1 className="heading-six for-some-reason">
        {
          guiltyPleasures
        }
      </h1>
    </div>
  );
};

Right here it becomes glaringly obvious that whether to overIndulge is not a factor in my <PunishingMeal /> logic.

Then, dealing with funky conditional logic, you can swing output on a let variable:

let output;

consume(highFructoseCornSyrup);
iAmSad ? ignore(healthWarnings[0]) : ignore(healthWarnings[2]);

if (iAmSad) {
  output = (
    <Container>
      <Input type={ items.mcDonalds }>
        ...
      </Input>
    </Container>
  );
}

if (!iAmSad && items.häagenDazs) {
  output = (
    <Container>
      <Input type={ items.häagenDazs }>
        ...
      </Input>
    </Container>
  );
};

return output || null;

Each if statement above can now read similar to natural language: If I am sad, output equals .... Here we can easily tell that my love of ice cream transcends whether I’m sad. If it’s around I’ll eat it.

Otherwise, the return statement again reads like natural language: return output or null. This pattern makes it safe to remove conditional logic from JSX because it will simply do nothing if the return is null.

Next, by a similar pattern you can assign a semantic name to default content and change it on conditional logic:

let footerContent = (
  <div
    className="default-excuse"
    position="bottom">
      <p>Treat yo-self! You deserve this for being you.</p>
  </div>
);

if (!iAmSad) {
  footerContent = (
    <div
      className="maybe-get-chopt"
      position="bottom">
        <ul>
          { healthWarnings.map(warning => (<li>{ warning }</li>)) }
        </ul>
    </div>
  );
};

In this case, I’m more likely to pay attention to health warnings and consider getting Chop’t when I’m not sad. By default though, I’m going to give myself a flimsy excuse for overindulging when it’s time for a <CheatDay />.

Wrapping it up, I can then return some very straightforward JSX that’s easy to read:

return (
  <div className="footer footerClasses">
    { footerContent }
  </div>
);

Finally when I’m done, I can simply return the top-level component as if it were any JS function:

return <CheatDayComponent />;

At first the simplicity of the return statement could be a little jarring because it’s unusual to see JSX outside of parens. The point here again is semantics- it’s literally a natural language statement for what’s happening here.

And Here’s the Whole Shebang

import React from 'react';
import PropTypes from 'prop-types';
import { Container, Input } from '../Base';

const CheatDay = ({
  items,
  healthWarnings,
  iAmSad,
  highFructoseCornSyrup,
  }) => {

  const CheatDayComponent = () => (
    <Container className="bag paper-bag brown-paper-bag bag-xl">
      <CheatDayHeader />
      <PunishingMeal />
      <CheatDayFooter />
    </Container>
  );

  const CheatDayHeader = () => (
    <div className="header super-stylish-header">
      <h1>Cheat Day is like, super healthy and stuff</h1>
      <span>Enjoy your { highFructoseCornSyrup }</span>
    </div>
  );

  const PunishingMeal = () => {
    const overIndulge =
      iAmSad &&
      items.mcDonalds.bigMac || items.mcDonalds.nuggets &&
      healthWarnings.splice(0, 2).find('unheeded');

    return (
      <div className="classes more-classes flex">
        <h1 className="heading-six for-some-reason">
          {
            guiltyPleasures
          }
        </h1>
      </div>
    );
  };

  const guiltyPleasures = items.map(item => {
    const foodItems = Object.keys(item);
    const ingredients = foodItems.map(foodItem => foodItems[foodItem]);

    const ignoreFullness = () => {
      let output;

      consume(highFructoseCornSyrup);
      iAmSad ? ignore(healthWarnings[0]) : ignore(healthWarnings[2]);

      if (iAmSad) {
        output = (
          <Container>
            <Input type={ items.mcDonalds }>
              <ul>
                { items.mcDonalds.bigMac.map(ingredient => (
                  <li>
                    { ingredient }
                  </li>
                )) }
              </ul>
            </Input>
          </Container>
        );
      }

      if (!iAmSad && items.häagenDazs) {
        output = (
          <Container>
            <Input type={ items.häagenDazs }>
              <ul>
                { items.häagenDazs.iceCream.map(ingredient => (
                  <li>
                    { ingredient }
                  </li>
                )) }
              </ul>
            </Input>
          </Container>
        );
      };

      return output || null;
  });

  const CheatDayFooter = () => {
    let footerContent = (
      <div
        className="default-excuse"
        position="bottom">
          <p>Treat yo-self! You deserve this for being you.</p>
      </div>
    );

    if (!iAmSad) {
      footerContent = (
        <div
          className="maybe-get-chopt"
          position="bottom">
            <ul>
              { healthWarnings.map(warning => (<li>{ warning }</li>)) }
            </ul>
        </div>
      );
    };

    return (
      <div className="footer footerClasses">
        { footerContent }
      </div>
    );
  };

  return <CheatDayComponent />;
};

CheatDay.propTypes = {
  items: PropTypes.shape({
    mcDonalds: PropTypes.shape({
      bigMac: PropTypes.shape({
        allBeefPatties: PropTypes.array,
        specialSauce: PropTypes.mystery.isRequired,
        lettuce: PropTypes.vegetable,
        cheese: PropTypes.dairy,
        pickles: PropTypes.monster,
        onions: PropTypes.vegetable,
        sesameSeedBun: PropTypes.carbs,
      }),
      nuggets: PropTypes.shape({
        chickenProduct: PropTypes.mystery.isRequired,
        sauce: PropTypes.string.isRequired,
      }),
      fries: PropTypes.shape({
        potato: PropTypes.starch.isRequired,
        oil: PropTypes.oil.isRequired,
        salt: PropTypes.deliciousness,
      }).isRequired,
    }),
    häagenDazs: PropTypes.shape({
      iceCream: PropTypes.shape({
        ice: PropTypes.coldness.isRequired,
        cream: PropTypes.umami.isRequired,
      }).isRequired,
      toppings: PropTypes.shape({
        reeses: PropTypes.bestCandyEver,
        whippedCream: PropTypes.umami,
      })
    }),
  }),
  healthWarnings: PropTypes.array,
  iAmSad: PropTypes.boolean.isRequired,
  highFructoseCornSyrup: PropTypes.hazard.isRequired,
};

Programmatically Edit Any File in NodeJS

NodeJS is useful for way more than just installing packages or running servers. For instance, using the npx package and Node’s filesystem methods, you can create complex logic for interacting with files as if they were plain-ol’ Javascript objects. No BASH required.

This little piece documents a way to programmatically modify package.json. In this example I append JSON output to my existing test script and add a new script into package.json Using this pattern and these methods, you can do basically anything you want inside your repo.

Install NPX

npm i -g npx

Create a File for your NPX Script

touch fs-demo.js

Load package.json as an object

const fs = require('fs');
const pkgJson = require('./package.json’);

CRUD your key/value pairs like any object

const { test: testScript } = packageJson.scripts;

if(testScript.includes('--outputFile')){
  console.log('No changes needed in test script')
} else{
  packageJson.scripts.test = testScript + ' --json --outputFile=jest-test-results.json';
  console.log('Updating test script');
}

packageJson.scripts.foo = 'bar';

Write the updated ‘package.json’ to fs

fs.writeFileSync('package.json', JSON.stringify(packageJson, null, 2));
console.log('Package saved');

NOTE: the additional arguments to JSON.stringify() are there to pretty-print the result. Otherwise you’ll wind up with an unreadable JSON string for the next engineer to prettify. Please practice good coding etiquette 😉

Finally: Run the NPX Script

npx ./fs-demo.js

Here’s the Whole Shebang

const fs = require('fs');
const packageJson = require('./package.json');

const { test: testScript } = packageJson.scripts;

if(testScript.includes('--outputFile')){
  console.log('No changes needed in test script')
} else{
  packageJson.scripts.test = testScript + ' --json --outputFile=jest-test-results.json';
  console.log('Updating test script');
}

packageJson.scripts.foo = 'bar';

fs.writeFileSync('package.json', JSON.stringify(packageJson, null, 2));
console.log('Package saved');

Gotcha: Working with Arbitrary File Types

Working with other file types (say, .gitignore) can be a problem because require doesn’t know what to do with them. It only thinks in terms of Javascript.

To get around this, you can fs.read files into memory and interact with them like strings:

const gitIgnore = fs.readFileSync('./.gitignore', 'utf-8');

You can then chop up your string however you want. For instance in the example below, you can split it on the new-line.

let myGitIgnore = gitIgnore.split(/\n/);

At this point all you’re doing is transforming string data. When you’re done, you reassemble it like above and simply fs.write back to your target file.

How I Got My First Dev Job (Without Applying Online)

Career changing is a daunting task, and for my part I’m a little over a month into my first full-time job as a front-end engineer. Common wisdom says it’s hardest to get that first foot in the door, and for me it only happened after I stopped applying online.

The process was brutal and often felt hopeless- that is, until I finally stepped out of what I call The Cave (more on that later) and tried something different. In the end, I went to coding bootcamp and landed a job without applying through even a single unsolicited online portal.

This is a long post with a fair amount of biographical details, so if you want the tl;dr of it just scroll to the bottom.

A Bit About My Background

As a little kid I was totally into computers and coding, until I learned the importance of being cool (5th grade). Then I forgot about it. Sometimes I dabbled as a hobbyist, but that was about it.

I graduated with a Classics degree in 2008, which prepared me to do… nothing. Well, sales. It was 2008- jobs with base pay were basically not even a thing back then.

Not saying I never had a leg up, but ten years later no one’s Applicant Tracking System was about to screen me into tech interviews. I had to get unconventional.

Disillusionment, Freelancing, and The Cave

Queue up the Fight Club references. Work life sucked for me, and I felt like I was doomed for permanent underemployment.

I kept finding myself frustrated seeing my employers paying other people so much money for web work, when I knew I could do it just as well myself. At a certain point I had to stop complaining and start actually doing something about it.

Warning: survivorship bias. OK, so I happened to have outside interests that regularly put me in real live rooms with real live people outside my immediate social circle. And one of these people became my first (and best) client as a freelance web developer slash social media person slash web-whatever.

I learned pretty early on as a freelancer that trying to find clients online was a great way to tread water (thrash, really) while appearing productive (to myself). Still, I put a lot of time and effort into cultivating my online presence to impress strangers in cyberspace.

Ultimately all the real money and work came from meatspace. I did solid work for my clients and they referred me, or I met people randomly IRL (one of them in my building’s elevator- literally an elevator pitch).

Hiding Out in The Cave

As time went on, anything marketing-related began to feel like a necessary evil to get more technical. Designers cringe at the phrase “make it pop,” and then there’s pouring your heart and soul into a creative project only to have your client tell you they’re not feeling it. Crushing.

Eventually I got it in my head I could enjoy working in software if I leveled-up enough. I spent a year or so doing an hour worth of online coding courses every morning, practicing the new skills as much as I could on client projects. Then I started applying online.

And here’s where I went into what I call The Cave: hiding out in front of the computer, frantically sending out resumes to as many places as possible, treating my resume and portfolio like magical spells that would work if only I could get the words perfect:

Hermione Granger: It's LeviOsa, not LeviosAR!

More cave-y: rather than face dangers (rejection) in the wild, I tried expanding my cave’s walls with a hammer-and-chisel until I felt like I was exhausted and starving to death. “But it’s 2017- how else do people connect!?”

After months of silence from online portals and ghosting from tech recruiters, I became desperate enough to do the unthinkable- go out and be seen. Scary! #vulnerable

Coding Bootcamp

After a year-plus of trying to go it alone through online codealongs, I realized it was time to stop fucking around and finally take a firm stance on where I meant to go. It was time I got so good they couldn’t help but hire me.

I took four months out of my life to do an immersive, in-person bootcamp at the Flatiron School. It felt like kind of a scorched-earth way of making the transition, but then again people take years out of their lives (and often hundreds of thousands in debt) to become certified for basically anything comparable in terms of pay/benefits/etc.

When I finished I had gotten what I paid for: I had grown into a competent, full-time-employable software developer. More than just a freelancer who knew how to hack some code together when the job called for it.

Staying Out of The Cave (Easier Said Than Done)

Post-Bootcamp job search empowered me with the only thing I’ve hated more than putting myself out there for work- the spreadsheet.

As part of a money-back guarantee, I was eligible for a tuition refund if I regularly followed certain steps and documented them:

  • - Contact X amount of new people every week
  • - Follow up with them and track application status
  • - Make X amount of Git commits per week
  • - Write a new blog post every week
  • - Keep regular appointments with my career coach

I’m the furthest thing from a Type-A personality. Feeling responsible to stay on top of this thing motivated me to get out there and face my fears of meeting people IRL, rather than spend the next six months in a spreadsheet maintaining the illusion of progress.

Tools of Survival Outside The Cave

Go to Meetups – Go solo, and don’t only sit with your friends. Two meaningful conversations with strangers are enough to call the event a success.

Unlike online dating, walking up to someone and saying “Hi” is good enough. Literally. “Hi” is the first thing I said to the stranger who wound up getting me hired.

Don’t Commiserate – I quickly felt that other job seekers were dragging me down. Sorry, not sorry.

Going through one of the most uncertain and vulnerable periods of my life, the last thing I needed was to compare notes with other people who also hadn’t landed a job yet.

The anxiety is contagious, and we were basically competitors for the same thing. Not helpful.

Listen to Podcasts – Controlling your inputs is super important. Garbage in/garbage out. If I want to become a senior dev, it makes sense to listen to senior devs. And it’s free.

I burned through:

Don’t Only Look for Work – Avoiding burnout is easier said than done, especially when there’s too much free time and not enough money.

That said, you’re a human being, not a piece of factory equipment. For me the most important work happens when my brain can process things in the background, which means putting some attention into unrelated activities.

Actually Follow Up – Before landing a job, I didn’t realize how unusual it was for people to actually follow up on leads. And follow up more than once.

As a job seeker I was laser-focused on my job search. As a job haver, that laser focus goes into doing my actual job.

For my part, I take it as a responsibility/privilege to help the next person now that I have my foot in the door. That said, it’s hard to help a ghost.

Outside Recruiters Only Count for Practice – Companies pay big fees for recruiter-sourced candidates, and almost only for senior-level positions.

Don’t hold out hope for follow-through on their part if it’s your first dev job. Take every conversation you can though, because it’s useful (and free) interview practice for real positions you might actually land.

Busy Doesn’t Mean Effective – Creating a digital paper trail doesn’t mean you’re doing anything useful. Think of your attention as a very limited resource to use wisely.

Reading articles, “liking” things on social networks, spending hours learning oddball subjects some jerk might throw at you in an interview- it’s a waste of time if you’re not meeting real people who can get you a job.

And One Last Thing to Remember

Software employers need people who can figure out how to solve unique problems on a team, not people who already know all the answers. That’s the difference between you and Stack Overflow.

The learning curve at a new company is likely going to have the most to do with understanding what’s going on in their own codebase, more than anything you can research ahead of time.

I hope this helps! Feel free to share it around if you know someone who’s trying to land their first developer job. I’m not on social media, apart from the occasional LinkedIn post. You can reach out to me by email for any reason other than trying to hire me- I am very happy to say I’m off the market 🙂

Handling Dev vs Production API Calls using create-react-app

This post documents a brute-force approach I took to alternating between development and production databases in the PLURview app.

I built a simple apiAdapter.js file in my src/ directory, which sets an API_URL variable for my fetch() calls. PLURview is based on create-react-app, which has the ability to distinguish between dev and production through process.env variables.

The Problem

There were about 10 different calls to PLURview’s internal API spread throughout the front-end codebase. The API URLs were hard-coded, which required a project-wide search-and-replace for every commit (local vs production).

The other problem was complexity of information when it came to researching how to accomplish this. The app is hosted on Heroku and it automatically updates from Github.

I looked into using Heroku’s environment variables, which I had found useful in the past for storing API keys. All of my calls to external APIs go through the back-end, which is a private repo.

Ultimately a proper DevOps style solution appeared to be too heavy a solution for the amount of time I had to research and implement a solution.

The Solution

First, I modified my NPM scripts to set the dev environment variable:

"scripts": {
    "start": "REACT_APP_STAGE=dev react-scripts start",
    ...
  }

When you set a variable starting with REACT_APP you’ll have access to it in your app along the pattern of process.env.REACT_APP_STAGE.

Next, in apiAdapter.js I created a simple ternary based on the environment variable:

let API_URL

process.env.REACT_APP_STAGE === 'dev'
  ? API_URL = 'http://localhost:3001/api/v1'
  : API_URL = 'https://plurview-api.herokuapp.com/api/v1'

Finally, I collected all those fetch calls into apiAdapter.js so I could interpolate the API_URL based on the environment:

export const fetchArtists = () => {
  return fetch(`${API_URL}/artists`)
}

The adapter works the same way in the app as Redux actions. A component can import and use only the calls it needs:

import {fetchColorGuide} from '../../apiAdapter'

...

toggleDetails = () => {
    fetchColorGuide()
    .then(res => res.json())

Conclusion

This was a good intermediate step between ad hoc fetch() calls and something more elegant. In the process I found I probably had more API calls going on than necessary, and some of my naming conventions could use better semantics.

The process of abstracting these calls also shined some light on components and endpoints I was no longer using, which helped me pare down the codebase a bit overall.

PLURview’s Visual Language for Music

PLURview uses color gradients to describe what sort of EDM show you can expect from an artist. The colors create a new visual language for describing music without relying on labels. With a general understanding of what the 6 basic colors represent, you can tell at a glance whether an unknown artist is in your taste range.

Some background on this: the PLURview database currently has 243 subgenres of EDM associated with various artists. If these were split evenly for every artist in the database, each artist would have nearly 10 subgenres to describe their sound. The system is broken.

The PLURview Vibe System

Here’s the answer to DJs’ “Death to Genres!” battle cry: no more genres. Use vibes instead. Some shows will have more of a Deep House vibe to them. Sometimes they’ll get you bouncing with something more Big Room, drop after drop. The mosh pit at a Dubstep show is probably not the best place to make out with someone. You’ll often find dubstep mixed with Trap music, which has more hip-hop influences. If you want something more chill, go to a Trance show or get weird with some Bass Music.

Most shows will be a blend of styles, although some artists can fit snugly into one vibe or another. Here’s the visual breakdown:

Red – Deep House

Carl Cox is one of the big names to think of when it comes to the red color bar. In fact, the red lighting of the Carl Cox Megastructure at Ultra Music Festival played a big role in assigning this color.

Pink – Big Room

Expect to jump! Big bass drops here. Also you might get cake thrown on you if you stay to the end of a Steve Aoki set. Pink is all about high energy and positive vibes.

Yellow – Trap & Hardstyle

Yellow Claw inspired the color choice. This Amsterdam duo brings the heat with hardstyle drops that segue into hip-hop beats.

Green – Dubstep

DEEP bass- dark, and often a bit on the slower side. This is head-banging, moshing type of music. Inspiration for the green color palette came from Snails and his personal subgenre “Vomitstep”. However, 12th Planet is a better example of what to expect out of a full-green show.

Blue – Trance

More of a chill vibe here. Get deep into it or let it set the mood. The blue is good for cooling off. Eric Prydz is very popular in this category.

Purple – Bass Music

Experimental music with generally more of a weird vibe to it. Rezz is a cool example of this:

Color Blends

This is where the magic really happens with PLURview. The underlying algorithm sets a gradient based on numerous factors, in various weights. Some artists have a darker or lighter shade to them. They also vary in terms of more subdued or vibrant colors. No two artists are completely the same, and the gradient reflects the differences.

High Energy Blend – Borgeous

Part Big Room/Part Trance – Gabriel & Dresden

Conclusion

No two artists are alike, but you’ll find a lot of common combinations: yellow/green with dubstep and trap, red/pink is common with big room, as is red/blue with trance. As you become more comfortable with the color scheme, the hope with PLURview is to give you an effective shorthand to see if an artist is worth your time to explore.

The algorithm is by no means perfect or complete. This project is still in its infancy. Many artists in the database have too few data points to produce a reasonably accurate gradient. For those, you’ll find the neutral gradient below:

Optimizing SQL Queries in a Rails API

Here are a few cautions and suggestions for improving load times from a Ruby-on-Rails API, based on what I experienced developing the back-end for the PLURView App.

For background, PLURView analyzes EDM artists’ audio features to create a color gradient describing their vibe. The back-end is Ruby-on-Rails, and the front-end is a React/Redux app.

Prime the app with a subset of your data

The PLURView data store rapidly grew from a handful of artists I manually added into a database with thousands of entries. Artists have related artists (a reciprocal relationship) and multiple subgenres.

In the beginning it wasn’t a huge problem to “splat” (*) out the entire dataset to see if the algorithm was returning sensible gradients for artists. Once I was north of 100 or so entries though, loading times became excessive.

On the front-end, Redux was calling the entire dataset into the store at page load. As the dataset got heavier, it became important to cull the amount of information to pull in for the initial view. I did this by reducing the first data call to only the list of artists coming to New York City in the near future.

Serializers are great- but not always

Ideally when I make an API call, I want to receive a discrete JSON object containing every relevant data point. ActiveRecord allows for this, with no opinion on whether your tactics are performant.

Between core artist information, related artists, and genres, there are several tables getting hit per artist entry. On the front-end it would be nice to call in some sort of a God-object containing everything I could ever want to know, but it’s taxing on the back-end. Especially when there’s little specificity to which data should load.

In earlier development it saved some time to describe the object in a serializer, but things got pretty messy pretty quick.

Eventually it made more sense to use serializers to reduce the scope of information coming from an API call, rather than expanding it. The models contain fields the front-end doesn’t need, so they don’t need to wind up in a response.

Oh CRUD! There’s more to routing…

Thinking of Index and Show routes specifically, every bit of data doesn’t need loading by default. In PLURView, it wound up making more sense to build more specific routes to ping on the back-end for extended data.

Artist relations and subgenre information are useful for discovering acts, but these data take up a bunch of rows per artist. For performance it made more sense to call them on demand, hidden behind a “more details” type of pattern with a chevron icon on the Artist view on the front-end.

Shameless plug

I’m available for hire! My stack is Ruby-on-Rails on the back-end with React and Redux on the front-end. Email me if you want to get in contact 🙂

Creating a React Front-End for a WordPress Site

WordPress 4.7+ comes with a built-in REST API for developers to access a powerful, well-documented content management system with non-Wordpress view engines. This means you can separate your front end from your back end on WordPress, and write out your views any way you choose using JSON.

For comparison’s sake, the old paradigm was to write out templates in PHP using WordPress’ well-documented but rather arcane view system. This made WordPress development itself a specialized skillset, and making custom themes like this one (if you’re reading this on the WordPress version of my portfolio) was not for the faint of heart.

How to do it

First, shake off the residual frustration you might have had developing traditional WordPress templates. We’re out of PHP land. All we’re doing is tapping your WordPress as an API:

fetch('https://www.nephewapps.com/wp-json/wp/v2/tags')

The /wp-json/wp/v2/ endpoint gives you access to all the information you’d ordinarily query through PHP, returned as a JSON object:

<br />{
        "id": 15,
        "count": 2,
        "description": "",
        "link": "https://nephewapps.com/tag/css/",
        "name": "CSS",
        "slug": "css",
        "taxonomy": "post_tag",
        "meta": [],
        "_links": {
            "self": [
                {
                    "href": "https://nephewapps.com/wp-json/wp/v2/tags/15"
                }
            ],
            "collection": [
                {
                    "href": "https://nephewapps.com/wp-json/wp/v2/tags"
                }
            ],
            "about": [
                {
                    "href": "https://nephewapps.com/wp-json/wp/v2/taxonomies/post_tag"
                }
            ],
            "wp:post_type": [
                {
                    "href": "https://nephewapps.com/wp-json/wp/v2/posts?tags=15"
                }
            ],
            "curies": [
                {
                    "name": "wp",
                    "href": "https://api.w.org/{rel}",
                    "templated": true
                }
            ]
        }
    }

For a full reference to the endpoints available, check out the WP REST API V2 docs.

Limitations and Caveats

The setup for simple views is relatively straightforward, and with some very basic familiarity with WordPress you can deploy a site with Javascript views and a familiar CMS. Functionality for posting/editing/auth will get a bit hairier, and I’d suggest looking into the NodeJS API wrapper if you want to get more fancy.

I deployed my WordPress site using Softaculous on cPanel hosting, with a standard install- nothing special. For the React side of things, I found Heroku the most straightforward.

The caveat for separately hosting the WordPress install and the React front-end is, you need to serve your WordPress data over HTTPS. Otherwise Heroku will give you a mixed content error.

For me this meant migrating my site away from InMotion Hosting into a GoDaddy VPS that allows you to use AutoSSL on your sites. As of this writing, the options on InMotion are to pay $100 for an SSL (plus $25 for installation), or purchase and manually install a 3rd Party SSL. I prefer free.

Once you’re serving from behind an SSL, install the SSL Content Fixer plugin on your WordPress site so your React front-end can access images, etc. from your WordPress.

Dynamic HSL Gradients

What is HSL color?

HSL is a pattern for generating colors based on Hue, Saturation, and Lightness. This is a somewhat rare pattern, and it usually takes a back seat to Hex color codes (#000000 to #FFFFFF) in front-end design, or RGB(A) values that blend color with opacity. Rendering colors programmatically with HSL is useful for specifying where on the color spectrum it should fall, while letting the computer handle the rest.

What are HEX and RGB(A)?

HEX and RGB(A) are basically the same thing except for the (A) part, which affects the color’s opacity. Red, Green, and Blue (plus Alpha for transparency) combine in values up to 255 for the colors and up to 1 for opacity, making basically any color imaginable. HEX is a quick shorthand for RGB: it combines a pair of hex digits for each color (as in, #FF equates to 255 in hex math), so pure white #FFFFFF is the same as rgba(255, 255, 255, 1.0). So HEX is a bit more efficient to write out- especially considering you can further abbreviate colors pairs in HEX if each pair is the same- #AABBCC in other words can translate to #ABC.

Knowing off-hand what some of these values adds up to can be useful for coding CSS on the fly because there is ample tooling to pick up color values with an eyedropper and paste them around. When it comes to letting an algorithm do the work though, HEX and RGB(A) are less than intuitive for expressing the emotional value of a color.

Why use HSL instead?

Designers tend to memorize a few set HEX or RGB(A) codes, and otherwise use color-pickers to manually select different shades fitting a brand palette or other specification. Services like Paletton can help in terms of providing color suggestions, but ultimately a person has judge and set values for use in the wild.

What if we took more of a centaur-style approach? Human head/horse body: give the computer a general idea how values match up to colors (as a proxy for sentiment), and let the machine handle the details.

Using HSL, a designer can assign intuitive value judgments to data analysis on 3 dimensions. Maybe it starts with green/red- a positive or negative value judgment. But HOW positive? HOW negative? Is it dull or throbbing (Saturation)? Well-supported or speculative (could be lightness)?

Now, magnify that by the rest of the rainbow. Then, consider the fact you can shift to multiple colors within a gradient. Finally, how about making predominant data occupy a greater portion of your gradient?

Once you establish a basic visual language in terms of how you’re applying color values, a user can interpolate a thousand words with a glance at a color bar. Think of this as a decision engine for whether a data point is worth further exploration: does this spectrum appeal to my needs? What about then sorting data by color? The possibilities are endless.

HSL values and emotional impact

Color values can express a range of emotions- “this product is HOT”/”our company is COOL”- and designers spend a lot of time picking them out manually, by feel. Computers don’t struggle to understand how much red, green, and blue go into making yellow but designers do. Designers don’t struggle with understanding emotions- at least not as much as computers do- and our intuition allows us to judge the meaning behind numbers we crunch.

A quick description of how HSL values work:

Hue– A number from 0 - 360, indicating its place on a color wheel. This is the general vibe of your color- a cool blue at hsl(200, ...), a warm magenta at hsl(310, ...), so on.

Saturation– A number from 0 - 1, which affects how vibrant your color will be. S values closer to 0 will come out more grey.

Lightness– A number from 0 - 1, ranging from black at 0 to white at 1.

Top value (in parens) is HSL: the first parameter is a color value- 99 for green, 0 for red- and only the saturation and lightness change. The bottom values are the HEX codes. It’s less than intuitive to find patterns for predicting the end result.

Using HSL values in a gradient

After mapping out how your data relates to relative values in HSL, you can drop them into a CSS gradient the same as if they were HEX or RGB(A) colors:

linear-gradient(to right, hsl(348, 34%, 58%) 0%, hsl(348, 14%, 34%) 100%})

Note the 0% and the 100% after the HSL color declaration: these percentages refer to the point on the gradient at which your color will show its declared value. If you’re combining two computed colors and weighing one more heavily in your gradient than the other, you’ll have to account for where they’ll peak rather than what percentage of the gradient you’ll want them to occupy.

Brute-force gradient setting in React (example)

Here’s a very simple example of setting these values to appear on the fly- brute force in the sense of applying them as inline CSS. Programmatically setting HSL as part of your component’s state allows for dynamic gradient updating as part of your app, with the fewest moving parts in terms of stylesheets.

<div style={{background: `linear-gradient(to right, ${this.state.hsl})`}} /> 

Consider storing gradient values alongside your data on the back-end in order to save processing time when rendering your data.

Mark Bello

Mark Bello