DEV Community

Ryan Haskell
Ryan Haskell

Posted on • Edited on

The Simplest Function in JS

The Problem

Hey there, folks! I've got a JS coding challenge for you:

Write a function called "getFruitColor" that has the following behavior:

  • If given "apple", it returns "red"
  • If given "banana", it returns "yellow"
  • If given anything else, return undefined

What's the simplest JS thing you can use to make that function? Let's take a look!

Approach 1: Using an if statement

When I was first learning about functions and logic, I heavily relied on the if statement. It's super flexible and easy to read!

function getFruitColor(fruit) {
  if (fruit === 'apple') {
    return 'red'
  } else if (fruit === 'banana') {
    return 'yellow'
  } else {
    return undefined
  }
}
Enter fullscreen mode Exit fullscreen mode

Testing this code out, it works great!

getFruitColor('apple')    // "red"
getFruitColor('banana')   // "yellow"
getFruitColor('cherry')   // undefined
Enter fullscreen mode Exit fullscreen mode

There's nothing wrong with the code here, but can we do better?

Approach 2: Using a switch statement

Whenever we are doing === repeatedly on the same value, maybe a switch statement could help out with some of the repetition:

function getFruitColor(fruit) {
  switch (fruit) {
    case 'apple': return 'red'
    case 'banana': return 'yellow'
    default: return undefined
  }
}
Enter fullscreen mode Exit fullscreen mode

Amazing! Let's see if it still works:

getFruitColor('apple')    // "red"
getFruitColor('banana')   // "yellow"
getFruitColor('cherry')   // undefined
Enter fullscreen mode Exit fullscreen mode

Looks like the behavior here is the same, and we saved a lot of noisy code.

The most important thing? We made it easy for a reader to see the mapping of inputs to outputs.

But can we do even better?

But first: A tangent about undefined!

If a function in JS doesn't return a value, it returns undefined. This means we didn't need this else case, or the default case in the code.

Sidenote: I like typing the explicit else and default, because it tells the reader that I've thought through the edgecases, instead of just forgetting to handle them.

TLDR; These two are shorter versions of the first two approaches:

// without the else
function getFruitColor(fruit) {
  if (fruit === 'apple') {
    return 'red'
  } else if (fruit === 'banana') {
    return 'yellow'
  }
}

// without the default
function getFruitColor(fruit) {
  switch (fruit) {
    case 'apple': return 'red'
    case 'banana': return 'yellow'
  }
}
Enter fullscreen mode Exit fullscreen mode

Approach 3: Using an object

What's the simplest way to map one value to another? Use an object!

const getFruitColor = {
  apple: 'red',
  banana: 'yellow'
}
Enter fullscreen mode Exit fullscreen mode
getFruitColor['apple']    // "red"
getFruitColor['banana']   // "yellow"
getFruitColor['cherry']   // undefined
Enter fullscreen mode Exit fullscreen mode

We access objects with [] instead of (), but they have the same semantics as functions!

Extra Credit: Using Functions

We've seen this used above for returning values, but can it work with logic? Does it work with other things if and switch support like blocks of code?

You bet! Because JS lets you return functions as values, you can even route blocks of code this way!

With an if statement

function handleCommand(command, args) {
  if (command === 'greet') {
    const name = args[0]
    console.log('Hello ' + name + '!')
  } else if (command === 'compliment') {
    console.log('Looking good!')
  } else {
    console.log('Command not found')
  }
}
Enter fullscreen mode Exit fullscreen mode

With an object

function handleCommand(command, args) {
  const handler = commands[command]

  return handler
    ? handler(args)
    : console.log('Command not found')
}

const commands = {
  greet: (args) => {
    const name = args[0]
    console.log('Hello ' + name + '!')
  },
  compliment: (args) => {
    console.log('Looking good!')
  }
}
Enter fullscreen mode Exit fullscreen mode

That's it!

Remember, choose the code you think is the easiest to read and change. I wanted to share the object technique because it blew my mind when I learned about it!

Maybe next time you're writing a switch case, you'll think of me 😄

Have an awesome day!

Top comments (2)

Collapse
 
jorawarsinghnijjar profile image
Jorawar Singh Nijjar

Thats great and simple technique! Thanks for sharing.

Collapse
 
ryan-haskell profile image
Ryan Haskell

Thanks for the kind words, I'm glad you enjoyed the article 😊