Clojure offers many control flow conditionals, like if-else blocks. In this chapter, we'll study the API of a few such methods.
Clojure lets you write concise code. A major factor that supports this is its rich standard library. So far we have studied syntax, build tools, and nREPL. In this module, we'll build on top of that knowledge to understand the most commonly used functions.
We highly recommend that you follow along and try the examples yourself using inline eval. This is also a good time to practice some Paredit commands. We'll reuse the setup for
first-project and create a new namespace for each chapter. So start your
watch, start the Node runtime, and connect your editor to the REPL. It's time to code.
If you need a reminder on the
watch command and the REPL, check the chapters on Shadow CLJS API and NREPL under the Language Semantics section.
In this chapter, we'll learn about various conditional functions. The code examples are present in the
first-project.conditionals namespace. By now, you should be comfortable figuring out the disk path of the file that holds this namespace.
Q: What is the correct disk path for this namespace?
If you guessed it right, great. If you got it wrong, you might want to review the chapter on
Project Structure again.
We have seen the
if function already. It takes three arguments:
a variable to check
an S-Expression to execute if the variable is truthy
an S-Expression to execute if the variable is falsy
The inline comment starting with
=> denotes the result of inline evaluation with nREPL.
Empty data structures (lists, vectors, maps, and sets) are truthy.
nil is falsy.
You might find yourself in a position where you need to execute more than one S-Expression in the
else block. For example, instead of just returning a string, you may want to print and return it, like this :
This S-Expression is invalid (wrapped in a
comment so it doesn't interfere with other examples). In cases like these, you can use a
do takes an arbitrary number of S-Expressions and executes them in order: