Search code examples
javascriptfunctionreturnreturn-valuereturn-type

How to break out of a function in Javascript?


Here is the piece of code, note I have commented of what I would like to achieve in the code

const extraHot = () => {
   if (hot === "h") {
      return `extra hot`
   }
// otherwise, do nothing, don't return anything
// (not even an empty string or undefined object)
// I want to break here
}

if (givenAmount >= dict){
// I would like to return "Drink maker makes 1 extra hot sugar and 1 stick"
    return `Drink maker makes 1 ${extraHot()} sugar and 1 stick`
}

The following code will return "undefined" between "makes" and "sugar"

const extraHot = () => {
   if (hot === "h") {
      return `extra hot`
   }
   return
}

The following code will return a space between "makes" and "sugar"

const extraHot = () => {
   if (hot === "h") {
      return `extra hot`
   }
   return ""
}

Solution

  • Your problem is not what the function returns if hot !== "h", but how you write your template string. In case of if evaluates to true, return ' extra hot ', and write the template string like

    Drink maker makes 1${extraHot()}sugar and 1 stick