DEV Community

Jasterix
Jasterix

Posted on • Updated on

Working with JavaScript objects

JavaScript arrays are great. There are so many methods and strategies for working with JavaScript arrays. But the exact opposite can be said about JavaScript objects.

That's why, when saw the prompt for the RNA Transcription challenge on Exercism, it took a few days to get started. I could just tell it would be a JavaScript objects challenge.

Given a DNA strand, its transcribed RNA strand is formed by replacing
each nucleotide with its complement:

G -> C
C -> G
T -> A
A -> U
Enter fullscreen mode Exit fullscreen mode

My first solution was a little clumsy. When I Googled JavaScript methods, most results focused showcased Object.keys() and Object.values. My first solution didn't work for a couple of reasons:

  1. It was too complicated. With a for...of loop, an object method, a .map() method and an if statement, it was an obviously meek first attempt.
  2. My mentor disagreed with using res as a default parameter, saying "since res is not really an input, you can declare it inside the function body rather than in its signature"
  3. It tried to force the object into array unnecessarily
const transcription = {
  G: "C",
  C: "G",
  T: "A",
  A: "U"
};
export const toRna = (string, res = "") => {
  for (let char of string) {
    Object.entries(transcription).map(([key, value]) => {
      if (key === char) {
        res += value;
      }
    });
  }
  return res;
};
Enter fullscreen mode Exit fullscreen mode

This final solution is a lot cleaner:

  1. It uses only one .map() method
  2. It makes use of bracket notion, rather than forcing the object into an array
  3. It uses explicit returns, rather than saving the results to a variable
const transcription = {
  G: "C",
  C: "G",
  T: "A",
  A: "U"
};

export const toRna = string => {
  return [...string].map(letter => {
      return transcription[letter];
    })
    .join("");
};
Enter fullscreen mode Exit fullscreen mode

This exercise was a great reminder to get more comfortable working with JavaScript objects. One thing with studying alone is that its' easy to get into a comfort zone and stay there. In terms of data structures, my comfort zone is arrays. So I need to resist defaulting to arrays.

If you'd also like a refresher on working objects, check out this blog post on accessing JavaScript object properties .

Top comments (0)