JavaScript: Evolved Thinking

Tech: Javascript in React application

Challenge: refactor an archaic iteration to identify the correct string within an array of objects. A code review by a senior programmer identified a section of code ripe for refactor. JavaScript has some great built-in object methods; let’s fully utilize!

Code:

Here is our array with objects identifying URL paths and additional properties

blog_evolved_thinking_pages

 

And the original iteration to identify the api/database’s value for lastScreenSaved, ex – ‘factor_affect’.

blog_evolved_thinking_original_iteration

What’s wrong?? For starters, the iteration continues after identifying the correct index. Second, there are better tools to identify a substring (which we will see in the refactored code).

 

Let’s take a look at the refactored code:

blog_evolved_thinking_refactored

Wow! Much more compact and clean. Allows for quicker understanding, easier testing, and faster refactoring if URL extension changes in future.

 

Takeaway: I tend to think in basic data structures and iterations from my early coding days. It pays to take a minute prior to merge requests to look for & refactor code to better utilize the tools available in mature languages. 

 

Reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search