Nesting IF in expression

Describe the issue/error/question

Hello n8n community!
Is it possible to add IF conditional logic within an expression?
I’m building the body of an email within a node and would like to conditionally include a string in the Nodes output, only if a parameter is present in the input. I know I could do this with additional IF nodes but hoping to simplify the Workflow.

So IF $json[“field name”] exists “insert this” else “insert this instead” kind of thing

Thanks in advance!

What is the error message (if any)?

Please share the workflow

(Select the nodes and use the keyboard shortcuts CMD+C/CTRL+C and CMD+V/CTRL+V to copy and paste the workflow respectively)

Share the output returned by the last node

Information on your n8n setup

  • n8n version:
  • Database you’re using (default: SQLite):
  • Running n8n with the execution process [own(default), main]:
  • Running n8n via [Docker, npm, n8n.cloud, desktop app]:

Hi @Felix_is_stuck, that should be possible using something like {{$json["field_name"] || 'foo'}}.

If field_name exists and has a value, the expression would return that value. Otherwise it would return foo.

Thank you!!

An extension of this theme:

Let’s say I have a variable called Name, that is not always set. I want to write an expression that says if Name (is Set), insert “My name is “&Name&”,\n”, else, once again I tried to amend your expression and failed :confused:

Also, is there an online resource that explains more about the different functions and operators available to use within n8n - I had a little look in the n8n docs but not finding much there about expressions.

Hey @Felix_is_stuck,

Sounds like you might want the ternary option, check this out and see if it is close to what you are after: JavaScript Code Snippets | Docs

1 Like

That’s perfect! Thank you - really appreciate the additional reading too.

3 Likes

No problem, happy automating :tada:

2 Likes