The Simplest Function in JS
Tags: javascript, webdev
Published: 2020-09-06 20:09:52

---
title: The Simplest Function in JS
published: true
description: I stole cool tricks from other programming languages to make writing JS nicer!
tags: javascript, webdev
//cover_image: https://direct_url_to_image.jpg
---

## 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!

```js
function getFruitColor(fruit) {
  if (fruit === 'apple') {
    return 'red'
  } else if (fruit === 'banana') {
    return 'yellow'
  } else {
    return undefined
  }
}
```

Testing this code out, it works great!
```js
getFruitColor('apple')    // "red"
getFruitColor('banana')   // "yellow"
getFruitColor('cherry')   // undefined
```

__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:

```js
function getFruitColor(fruit) {
  switch (fruit) {
    case 'apple': return 'red'
    case 'banana': return 'yellow'
    default: return undefined
  }
}
```

Amazing! Let's see if it still works:
```js
getFruitColor('apple')    // "red"
getFruitColor('banana')   // "yellow"
getFruitColor('cherry')   // undefined
```

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:

```js
// 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'
  }
}
```

## Approach 3: Using an `object`

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

```js
const getFruitColor = {
  apple: 'red',
  banana: 'yellow'
}
```

```js
getFruitColor['apple']    // "red"
getFruitColor['banana']   // "yellow"
getFruitColor['cherry']   // undefined
```

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__ 

```js
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')
  }
}
```

__With an object__

```js
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!')
  }
}
```

### 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 :smile:

__Have an awesome day!__