From f825b9c90dbd8e5733efbce8d98ed6dafa182805 Mon Sep 17 00:00:00 2001 From: Jim Nicholls Date: Thu, 16 Jan 2025 09:40:24 +1100 Subject: [PATCH] Demonstrate how to use IIFEs to write complex expressions. --- docs/code/expressions.md | 31 ++++++++----------------------- 1 file changed, 8 insertions(+), 23 deletions(-) diff --git a/docs/code/expressions.md b/docs/code/expressions.md index 1e59ae7bf5b..c462d2a2a46 100644 --- a/docs/code/expressions.md +++ b/docs/code/expressions.md @@ -79,33 +79,18 @@ This expression: ### Example: Writing longer JavaScript -An expression contains one line of JavaScript. This means you cannot do things like variable assignments or multiple standalone operations. +You can do things like variable assignments or multiple statements in an expression, but you need to wrap your code using the syntax for an IIFE (immediately invoked function expression). -To understand the limitations of JavaScript in expressions, and start thinking about workarounds, look at the following two pieces of code. Both code examples use the Luxon date and time library to find the time between two dates in months, and encloses the code in handlebar brackets, like an expression. - -However, the first example isn't a valid n8n expression: - - -```js -// This example is split over multiple lines for readability -// It's still invalid when formatted as a single line -{{ - function example() { - let end = DateTime.fromISO('2017-03-13'); - let start = DateTime.fromISO('2017-02-13'); - let diffInMonths = end.diff(start, 'months'); - return diffInMonths.toObject(); - } - example(); -}} -``` - - -While the second example is valid: +The following code use the Luxon date and time library to find the time between two dates in months. It is included in both the handlebar brackets and the IIFE syntax. ```js -{{DateTime.fromISO('2017-03-13').diff(DateTime.fromISO('2017-02-13'), 'months').toObject()}} +{{(()=>{ + let end = DateTime.fromISO('2017-03-13'); + let start = DateTime.fromISO('2017-02-13'); + let diffInMonths = end.diff(start, 'months'); + return diffInMonths.toObject(); +})()}} ``` ## Common issues