# Indents with IF, ELSE and other stuff

**URL:** https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991
**Category:** General
**Created:** [14 March 2025 10:42 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991 "2025-03-14T10:42:54Z")
**Posts on this page:** 20
**Page:** 1

<div class="post-metadata">

### Author: ![Trying\_to\_learn](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/trying_to_learn/32/28400_2.png) [@Trying\_to\_learn](https://discourse.nodered.org/u/Trying_to_learn)
#### Post date: [14 March 2025 10:42 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/1 "2025-03-14T10:42:54Z")

</div>

I'm going nuts trying to get this _new_ bug worked out.

I know I am making my life difficult by using a `function` node and not ..... using the stock nodes.

I am doing this to try and get a better understanding of how to structure code.

So I do this bit of code - which I get:

```auto
if (something == something_else) {
    code here
}

```

But what about when I have an `else` in there?

```auto
if (something == something_else) {
    code here
} else
    if (blah ==blah_blah) {
        other code here
        } else
            if (and_again == what_ever) {
                and so on
             }

```

That seems excessive indenting.

---

<div class="post-metadata">

### Author: ![E1cid](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/e1cid/32/77971_2.png) [@E1cid](https://discourse.nodered.org/u/E1cid)
#### Post date: [14 March 2025 10:49 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/2 "2025-03-14T10:49:44Z")

</div>

```auto
if (something == something_else) {
    code here
} else if (blah ==blah_blah) {
    other code here
} else if (and_again == what_ever) {
    and so on
}

```

When you close a } you start again where to opening { line starts.  
Whether on same line or below is a preference

---

<div class="post-metadata">

### Author: ![Trying\_to\_learn](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/trying_to_learn/32/28400_2.png) [@Trying\_to\_learn](https://discourse.nodered.org/u/Trying_to_learn)
#### Post date: [14 March 2025 10:51 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/3 "2025-03-14T10:51:58Z")

</div>

Thanks.

I must have missed that _trick_.

---

<div class="post-metadata">

### Author: ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)
#### Post date: [14 March 2025 11:04 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/4 "2025-03-14T11:04:34Z")

</div>

The curly braces in JavaScript indicate a "code block". They create a new "context" as well for things like `const` and `let`. You can even use them stand-alone for the odd occasion you might want to constrain some variables - though it is generally best to use a function for that.

So any JavaScript statement, like `if`, that takes only a single line of code, has to use a code block in order to execute multiple lines of code. You may see this with inline arrow functions as well where, if you only need to execute a single line of code, you can omit the braces.

---

<div class="post-metadata">

### Author: ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)
#### Post date: [14 March 2025 11:05 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/5 "2025-03-14T11:05:14Z")

</div>

> [@Trying\_to\_learn](#):
>
> But what about when I have an `else` in there?

![chrome_wU9MClvohf](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/d/0/d02f4dea8e1aec75643d43664e4fa8d25e0618a0.gif)

---

<div class="post-metadata">

### Author: ![Trying\_to\_learn](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/trying_to_learn/32/28400_2.png) [@Trying\_to\_learn](https://discourse.nodered.org/u/Trying_to_learn)
#### Post date: [14 March 2025 11:07 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/6 "2025-03-14T11:07:04Z")

</div>

I just hope I have the right version that allows that.

Thanks Steve.

---

<div class="post-metadata">

### Author: ![Trying\_to\_learn](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/trying_to_learn/32/28400_2.png) [@Trying\_to\_learn](https://discourse.nodered.org/u/Trying_to_learn)
#### Post date: [14 March 2025 11:08 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/7 "2025-03-14T11:08:46Z")

</div>

If the blocks have `return` in them, is the `else` helpful or not?

The `return` being either that or a bigger version that sends stuff.....  
(just to cover the bases of ambiguity)

Oh, this is something else that is tripping me up.

(example)

```auto
        //==============================================================================

        // Error acknowledgement message.
        if (msg.payload == "ERROR_ACK") {
            msg1 = { "payload": '<font color = "lime" i class="fa fa-exclamation-circle fa-2x"></i></font>', "topic": device + "/On-line", "device_ID": device, "background": "lime" }
            context.set("LOCK", 0)
            return msg1
        } else

            //==============================================================================

            // Health message received.
            if (msg.payload == "HEALTH") {
                // Working
                msg1 = { "payload": '<font color = "red" i class="fa fa-heartbeat fa-2x"></i></font>', "topic": device + "/Unhealthy", "device_ID": device }

                context.set("LOCK", 1) // Lock changes to node mode until reset.
                node.status({ fill: "red", shape: "dot", text: "HEALTH ALERT" })
                return msg1
            } else

                //==============================================================================

                if (msg.payload == "HEALTH_ACK") {
                    msg1 = { "payload": '<font color = "lime" i class="fa fa-heartbeat fa-2x"></i></font>', "topic": device + "/On-line", "device_ID": device, "background": "lime" }
                    context.set("LOCK", 0)
                    return msg1
                }

```

The `//============` to break up the blocks.

How would I do it in this new format?

---

<div class="post-metadata">

### Author: ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)
#### Post date: [14 March 2025 11:17 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/8 "2025-03-14T11:17:12Z")

</div>

> [@Trying\_to\_learn](#):
>
> If the blocks have `return` in them, is the `else` helpful or not?

Best practice is not to include a return in a final `else`. It is better to simply place that after the if blocks. It isn't a big deal though as either way works, it is simply that the best practice way helps avoid some hard to track down code typo's and is easier to read.

```js
// Error acknowledgement message.
if (msg.payload == "ERROR_ACK") {

    msg1 = { "payload": '<font color = "lime" i class="fa fa-exclamation-circle fa-2x"></i></font>', "topic": device + "/On-line", "device_ID": device, "background": "lime" }
    context.set("LOCK", 0)
    return msg1

} else if (msg.payload == "HEALTH") {
    // Health message received.

    // Working
    msg1 = { "payload": '<font color = "red" i class="fa fa-heartbeat fa-2x"></i></font>', "topic": device + "/Unhealthy", "device_ID": device }

    context.set("LOCK", 1) // Lock changes to node mode until reset.
    node.status({ fill: "red", shape: "dot", text: "HEALTH ALERT" })
    return msg1

} else if (msg.payload == "HEALTH_ACK") {

    msg1 = { "payload": '<font color = "lime" i class="fa fa-heartbeat fa-2x"></i></font>', "topic": device + "/On-line", "device_ID": device, "background": "lime" }
    context.set("LOCK", 0)
    return msg1

}

// Are you missing a final return statement? Or don't you want to return anything if the 3 conditions are not met?

```

Note that consistency of code layout, while not necessary, massively helps you scan and parse code. It helps reduce mental stress and lets you train yourself to spot many errors at a glance.

* * *

Some other thoughts.

I prefer to use single quotes for strings because on the UK keyboard, you don't have to press shift. You should also use either double or single quotes rather than a mix which distracts from reading.

Similarly, it is generally best not to put object property names in quotes unless you are using a non-standard name such as one with a dash or space. Obviously though, when using JSON rather than JavaScript, double quotes are mandatory.

---

<div class="post-metadata">

### Author: ![Trying\_to\_learn](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/trying_to_learn/32/28400_2.png) [@Trying\_to\_learn](https://discourse.nodered.org/u/Trying_to_learn)
#### Post date: [14 March 2025 11:21 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/9 "2025-03-14T11:21:43Z")

</div>

> [@TotallyInformation](#):
>
> Note that consistency of code layout, while not necessary, massively helps you scan and parse code. It helps reduce mental stress and lets you train yourself to spot many errors at a glance.

I fully agree with you on that and I am still so messed up with it.

With the example you posted:  
Yes, there would be more testing happening further down so that seems to be what I want.

Alas this is about 416 lines of JS that are driving me crazy.

I also realise that I am going to have to either reverse some of the testing or put `return`s in in the code.

I am good at digging myself into holes of code.

😉

Thanks.

The `//============` lines...

Thoughts on how I put them in with the `else if( )` structure?

---

<div class="post-metadata">

### Author: ![bakman2](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/bakman2/32/6207_2.png) [@bakman2](https://discourse.nodered.org/u/bakman2)
#### Post date: [14 March 2025 11:24 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/10 "2025-03-14T11:24:22Z")

</div>

Once there are more than 3 possibilities, i usually get confused and would go for a switch case statement, or an object lookup.

// AI generated:

```auto
// Define message configurations in a lookup object
const messageDefinitions = {
    "ERROR_ACK": {
        topicSuffix: "/On-line",
        payloadHTML: '<font color="lime"><i class="fa fa-exclamation-circle fa-2x"></i></font>',
        backgroundColor: "lime",
        actions: [
            { type: "contextSet", key: "LOCK", value: 0 }
        ]
    },
    "HEALTH": {
        topicSuffix: "/Unhealthy",
        payloadHTML: '<font color="red"><i class="fa fa-heartbeat fa-2x"></i></font>',
        backgroundColor: null,
        actions: [
            { type: "contextSet", key: "LOCK", value: 1 },
            { type: "nodeStatusUpdate", status: { fill: "red", shape: "dot", text: "HEALTH ALERT" } }
        ]
    },
    "HEALTH_ACK": {
        topicSuffix: "/On-line",
        payloadHTML: '<font color="lime"><i class="fa fa-heartbeat fa-2x"></i></font>',
        backgroundColor: "lime",
        actions: [
            { type: "contextSet", key: "LOCK", value: 0 }
        ]
    }
};

// Get the message configuration
const config = messageDefinitions[msg.payload];

if (config) {
    // Create the response message
    const msg1 = {
        payload: config.payloadHTML,
        topic: `${device}${config.topicSuffix}`,
        device_ID: device
    };
    
    if (config.backgroundColor) {
        msg1.background = config.backgroundColor;
    }

    // Execute actions defined in the configuration
    config.actions.forEach(action => {
        switch(action.type) {
            case "contextSet":
                context.set(action.key, action.value);
                break;
            case "nodeStatusUpdate":
                node.status(action.status);
                break;
        }
    });

    return msg1;
} else {
    // Handle unknown message payload
    node.warn("Unknown message payload:", msg.payload);
}

```

It becomes more reusable.

---

<div class="post-metadata">

### Author: ![Trying\_to\_learn](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/trying_to_learn/32/28400_2.png) [@Trying\_to\_learn](https://discourse.nodered.org/u/Trying_to_learn)
#### Post date: [14 March 2025 11:29 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/11 "2025-03-14T11:29:08Z")

</div>

Believe it or not, I see words, but the whole idea is foreign to me.

Sorry.

I will try to scope it and study it so I get a handle on what you mean.

Alas (IRL) I am also being flooded with things and ..... structures, procedures and all that sort of stuff.. And the terms are doing my head in.

So that is (probably) not helping me here/now.

---

<div class="post-metadata">

### Author: ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)
#### Post date: [14 March 2025 11:33 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/12 "2025-03-14T11:33:40Z")

</div>

> [@Trying\_to\_learn](#):
>
> Alas this is about 416 lines of JS that are driving me crazy.

A couple of things that might help.

Consider putting some of that code into functions - I know it seems weird to have functions inside a function node 😄 but it is often helpful to break up the code into smaller, logical chunks.

Also, you might want to consider setting up the full VS Code app. If you do, create a testbed folder to work in, initialise it as an npm module using `npm init -y`, then install `eslint` and some of its exensions. And finally add a file called `eslint.config.mjs` perhaps with a config something like this:

```js
// @ts-nocheck
/**
 * https://www.npmjs.com/search?q=eslint-config
 * https://www.npmjs.com/search?q=keywords:eslint
 *
 * npm init @eslint/config@latest -- --config eslint-config-standard
 * https://eslint.org/docs/latest/rules
 *
 * npx @eslint/config-inspector@latest
 * npx eslint --debug somefile.js
 * npx eslint --print-config file.js
 */

import globals from 'globals' // https://www.npmjs.com/package/globals
// @ts-ignore
import pluginImport from 'eslint-plugin-import' // https://www.npmjs.com/package/eslint-plugin-import
import pluginPromise from 'eslint-plugin-promise' // https://www.npmjs.com/package/eslint-plugin-promise
import jsdoc from 'eslint-plugin-jsdoc'// https://github.com/gajus/eslint-plugin-jsdoc
import node from 'eslint-plugin-n' // https://www.npmjs.com/package/eslint-plugin-n, node.js only
import stylistic from '@stylistic/eslint-plugin' // https://eslint.style
import js from '@eslint/js'

/** @type {import('eslint').Linter.Config[]} */
const conf = [
    js.configs.recommended,
    jsdoc.configs['flat/recommended'],
    pluginPromise.configs['flat/recommended'],
    pluginImport.flatConfigs.recommended,
    ...node.configs['flat/recommended-script'],

    {
        plugins: {
            '@stylistic': stylistic,
        },
        rules: {
            'jsdoc/check-alignment': 'off',
            // "jsdoc/check-indentation": ["warn", {"excludeTags":['example', 'description']}],
            'jsdoc/check-indentation': 'off',
            'jsdoc/check-param-names': 'warn',
            'jsdoc/check-tag-names': ['warn', {
                definedTags: ['typicalname', 'element', 'memberOf', 'slot', 'csspart'],
            }],
            'jsdoc/multiline-blocks': ['error', {
                noZeroLineText: false,
            }],
            'jsdoc/no-multi-asterisk': 'off',
            'jsdoc/no-undefined-types': ['error', {
                'definedTypes': ['NodeListOf', 'ProxyHandler'],
            }],
            'jsdoc/tag-lines': 'off',

            '@stylistic/comma-dangle': ['error', {
                'arrays': 'only-multiline',
                'objects': 'always',
                'imports': 'never',
                'exports': 'always-multiline',
                'functions': 'never',
                'importAttributes': 'never',
                'dynamicImports': 'never',
            }],
            '@stylistic/eol-last': ['error', 'always'],
            '@stylistic/indent': ['error', 4, {
                'SwitchCase': 1,
            }],
            '@stylistic/linebreak-style': ['error', 'unix'],
            '@stylistic/lines-between-class-members': 'off',
            '@stylistic/newline-per-chained-call': ['error', {
                'ignoreChainWithDepth': 2,
            }],
            '@stylistic/no-confusing-arrow': 'error',
            '@stylistic/no-extra-semi': 'error',
            '@stylistic/no-mixed-spaces-and-tabs': 'error',
            '@stylistic/no-trailing-spaces': 'error',
            '@stylistic/semi': ['error', 'never'],
            '@stylistic/quotes': ['error', 'single', {
                'avoidEscape': true,
                'allowTemplateLiterals': 'always',
            }],

            'new-cap': 'error',
            'no-else-return': 'error',
            'no-empty': ['error', {
                allowEmptyCatch: true,
            }],
            'no-unused-vars': 'off',
            'no-useless-escape': 'off',
            'no-var': 'warn',
            'prefer-const': 'error',
        },

        settings: {
            jsdoc: {
                mode: 'jsdoc',
            },
            node: {
                version: '18.0.0',
            }
        },

        languageOptions: {
            sourceType: 'commonjs',
            // Will be overridden by the n plugin which detects the correct node.js version from package.json
            ecmaVersion: 'latest',
            // Node.js globals are provided by the n plugin
            // globals: globals.browser,
        },
    },
]

export default conf

```

Then you can paste you code into a file and eslint will check it for you.

Some of the rules listed are my preferences but they are easily adjusted.

---

<div class="post-metadata">

### Author: ![Trying\_to\_learn](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/trying_to_learn/32/28400_2.png) [@Trying\_to\_learn](https://discourse.nodered.org/u/Trying_to_learn)
#### Post date: [14 March 2025 11:39 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/13 "2025-03-14T11:39:20Z")

</div>

I love what you are suggesting, but fear this is still above me.

Excuse the digression here:  
I just got a machine updated to a newer version of NR than I was using.  
V4.

Maybe I've asked, but maybe something has happened since I asked and this has been fixed.  
My MAIN MACHINE (this one) is a NUC and has room to play with stuff.

But the `debug` window - even if set to THIS TAB - keeps wiping itself because of stuff on OTHER TABS.

Has this been addressed with the latest version?

Only if YES, then I could do a lot of it on THIS MACHINE and not flog the poor RasPis with all this testing.

---

<div class="post-metadata">

### Author: ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)
#### Post date: [14 March 2025 11:41 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/14 "2025-03-14T11:41:25Z")

</div>

> [@Trying\_to\_learn](#):
>
> Believe it or not, I see words, but the whole idea is foreign to me.

If in doubt or when confused, I would always fall back to the Mozilla Developer Network (MDN). This has reasonable examples of a lot of of the JavaScript (and HTML and CSS) statements, functions and API's. It also has some pretty good tutorials and starter articles.

This stuff takes time to sink in, so don't let it get to you! 😄

One thing that I will regularly do with my code is that, when I go back and read it after a break, if I'm struggling to work out what it is doing, I know I need to work on refactoring it to make it simpler to read. Often, we write code in a hurry and so it evolves messily, that might sometimes be fine as a one-off, but if we have to come back to it, we may need to tidy and simplify it.

---

<div class="post-metadata">

### Author: ![Sean-McG](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/sean-mcg/32/54677_2.png) [@Sean-McG](https://discourse.nodered.org/u/Sean-McG)
#### Post date: [14 March 2025 12:21 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/15 "2025-03-14T12:21:54Z")

</div>

> [@Trying\_to\_learn](#):
>
> keeps wiping itself because of stuff on OTHER TABS.

You should turn off or even delete unneeded debug nodes, on other tabs.  
Even though you filter to the current tab, these other messages are still filling up the "buffer" and will cause messages to be removed.

---

<div class="post-metadata">

### Author: ![Trying\_to\_learn](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/trying_to_learn/32/28400_2.png) [@Trying\_to\_learn](https://discourse.nodered.org/u/Trying_to_learn)
#### Post date: [14 March 2025 12:27 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/16 "2025-03-14T12:27:33Z")

</div>

Yes, I dug myself into this situation.

This machine has.....  
Well, if I go to `list tabs` and the scroll window....

 ![Screenshot from 2025-03-14 23-26-03](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/b/4/b4fc0aade7887e88f7ef4f2f1d679666d33fb5bc.png)

And they are not (all) small flows.

I am putting a lot of eggs in one basket, I know.

---

<div class="post-metadata">

### Author: ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)
#### Post date: [14 March 2025 12:35 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/17 "2025-03-14T12:35:09Z")

</div>

You might consider having a 2nd Node-RED instance that you use for testing and development. That way, you protect your "live" flows.

---

<div class="post-metadata">

### Author: ![Trying\_to\_learn](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/trying_to_learn/32/28400_2.png) [@Trying\_to\_learn](https://discourse.nodered.org/u/Trying_to_learn)
#### Post date: [14 March 2025 12:37 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/18 "2025-03-14T12:37:01Z")

</div>

I may have to learn how to do that too.

Mind poking me with how to do that?

NR 3.1.5

---

<div class="post-metadata">

### Author: ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)
#### Post date: [14 March 2025 12:41 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/19 "2025-03-14T12:41:58Z")

</div>

Well, I do my dev/test stuff on my desktop and keep my server "clean". Well clean-ish.

The how depends on whether you want to be able to run a _different version_ of node-red for dev/test purposes. Personally, I **DO** want to be able to do that. But if you don't, things are a little easier to set up.

Because my dev/test instance is on my desktop, I don't bother to run it automatically, I'm using Windows 11 and I start it using PM2 with a configuration that auto-restarts when key files change. Just a convenience though, you don't need to do that particularly but when developing custom nodes, you often do lots of small iterative changes so manually restarting NR is a bit of a pain. 🙂

Let me know how/where you'd like to run your dev/test version and I can give some more specific help.

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)
#### Post date: [28 March 2025 12:42 UTC](https://discourse.nodered.org/t/indents-with-if-else-and-other-stuff/95991/20 "2025-03-28T12:42:18Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
