We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

The Initial Statement of an If Block

An if conditional can have an "initial" statement. The variable(s) created in the initial statement are only defined within the scope of the if, else if, and else blocks.

if INITIAL_STATEMENT; CONDITION {
}

Why Would I Use This?

It has two valuable purposes:

  1. It's a bit shorter
  2. It limits the scope of the initialized variable(s) to the if statement

For example, instead of writing:

length := getLength(email)
if length < 10 {
    fmt.Printf("Email must be at least 10 characters, is %d\n", length)
}

We can do:

if length := getLength(email); length < 10 {
    fmt.Printf("Email must be at least 10 characters, is %d\n", length)
}

In the example above, length isn't available in the parent scope, which is nice because we don't need it there - we won't accidentally use it elsewhere in the function. It would still be available in any else if or else blocks attached to that if.