Skip to content

Rework if/2 docs and mention variable scope #14452

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 26, 2025
Merged

Conversation

sabiwara
Copy link
Contributor

The structure of the if doc was a bit hard to understand, since:

  • we now had the following 3 sections: "One-liner examples" / "Blocks examples" / "Examples"
  • some examples were far away from the points they were illustrating (e.g. "Otherwise, nil will be
    returned.")
  • mixing of the if(foo, do: bar) and if foo, do: bar form, but AFAIK the former is less common and idiomatic nowadays?

I also noticed that the fact we can define a variable in the if condition wasn't explicitly documented, as well as scope rules more broadly (even if they aren't specific to if, it's probably the more common place people encounter it). Inspired from this

Co-authored-by: Parker Selbert <[email protected]>
@@ -3898,51 +3898,63 @@ defmodule Kernel do

## One-liner examples

if(foo, do: bar)
iex> if 7 > 5, do: "yes"
"yes"

In the example above, `bar` will be returned if `foo` evaluates to
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the example above, "yes" is returned because 7 > 5 evaluates to a truthy value (true in this case). nil will be returned if the condition evaluates to a falsy(nil or false) value:

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @dmitrykleymenov, good catch!
Fixed in 96bbccf

@dmitrykleymenov
Copy link
Contributor

dmitrykleymenov commented Apr 26, 2025

I'm just curious if it should be mentioned that the code inside unmatched blocks isn't even evaluated, and it's not only about a return value.

@sabiwara
Copy link
Contributor Author

I'm just curious if it should be mentioned that the code inside unmatched blocks isn't even evaluated, and it's not only about a return value.

It's true that it wasn't explicitly called out, added an example in 6d56287

Co-authored-by: José Valim <[email protected]>
@sabiwara sabiwara merged commit 5e050f2 into elixir-lang:main Apr 26, 2025
11 checks passed
@sabiwara sabiwara deleted the if-doc branch April 26, 2025 07:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

4 participants