skip to Main Content

I recently found a function in some code that I’m analyzing but I don’t understand what’s going on.

In this function I have an if with a condition and then a return.

if (condition) return

In this if there are no keys {} that determine the scope of the if.

I’ve seen cases where we have the if with the keys {} and inside it we have the return that can even be a component.

In that case what is happening in this if? I noticed that the statement I call after the if doesn’t happen even with the condition returning TRUE, but the setState is working.

const fireScreenDisplayed = (props = {}) => {
    _checkScreenValidity()
    if (checkDone && done && !props.force) return
    setDone(true)
    publishCdmEvent(_buildEvent('ScreenDisplayed', props))
  }

See that after the return we have the setState and below it a function.

This if returns the function too?

What is returning from this if?

I want to understand this technique and why it is used and if there are alternatives.

2

Answers


  1. I think what you’re talking about here is a so-called "one-line if". You can read a bit more about this here. The upshot is that in javascript, if the if block is just one line long, you can put it on the same line as the condition without any curly braces.

    It’s not uncommon to see a pattern like this in javascript, where if a condition is met, then the programmer just wants to return nothing in order to stop execution of the function. In this case, a return statement is used simply to exit the function. There is nothing being returned from the if block.

    An alternative, for example, would be to reverse the if conditional and place the remaining functionality within the if block e.g.:

    const fireScreenDisplayed = (props = {}) => {
        _checkScreenValidity()
        if (!checkDone || !done || props.force)) {
          setDone(true)
          publishCdmEvent(_buildEvent('ScreenDisplayed', props))
        }
      }
    
    
    Login or Signup to reply.
  2. Using return inside a function, automatically leaves the function block, thereby ending the function. Any code after the return statement is not executed.

    In other words if the condition is true, exit the function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search