DEV Community

Cover image for Codewars Return To Sanity JavaScript
Dylan Attal
Dylan Attal

Posted on

Codewars Return To Sanity JavaScript

This article explains how to solve the kata Return To Sanity from Codewars in JavaScript.

Instructions

This function should return an object, but it's not doing what's intended. What's wrong?

Provided Code

function mystery() {
  var results =
    {sanity: 'Hello'};
  return
    results;
}
Enter fullscreen mode Exit fullscreen mode

Discussion

This kata is testing our understanding of the keyword return.

The return keyword ends function execution and specifies what value the function outputs.

One point to consider: since return stops the function from running, any code after a return statement that is executed will not be run.

Another point to consider: if no value follows the return keyword, the function will return undefined.

A final point to consider: JavaScript has a feature called automatic semicolon insertion. Basically, writing semicolons in some places in JavaScript is optional. The compiler is smart enough to figure out where it needs to insert semicolons into your code so that it runs successfully. For example:

// What you write
const firstName = "Nadia"
const lastName = "Montoya"

// What the compiler converts it to
const firstName = "Nadia";
const lastName = "Montoya";
Enter fullscreen mode Exit fullscreen mode

This feature can have unintended consequences if you're not cognizant of it. For example in the below code, the compiler will insert a semicolon after return because nothing follows it on the same line.

// What you write
function createAPersonObject() {
    return 
    {
        age: 28,
        name: "Dylan",
        hairColor: "brown",
        likesPineappleOnPizza: false
    }
}

// What the compiler converts it to (which will return undefined)
function createAPersonObject() {
    return;
    {
        age: 28,
        name: "Dylan",
        hairColor: "brown",
        likesPineappleOnPizza: false
    }
}
Enter fullscreen mode Exit fullscreen mode

There are a lot of nuances when it comes to where you can omit semicolons in your code and count on automatic semicolon insertion to help you out. If you want to dive into the nitty gritty, I enjoyed reading this article.

Solution

So the whole crux of the issue in this kata is that the return keyword is on a line by itself. We need to make sure automatic semicolon insertion doesn't make the function return undefined instead of results.

function mystery() {
  var results =
    {sanity: 'Hello'};
  return results;
}
Enter fullscreen mode Exit fullscreen mode

Hope you enjoyed the article!
Follow me on LinkedIn and GitHub!

Top comments (0)