1

My code is below:

  module.exports = {
    cleanCode: function(){
      return 'clean code helper'
    },

    nestedChildren: function(arr, parentId) {
    var out = []
    for (var i in arr) {
      if (arr[i].parent_id == parentId) {
        var children = nestedChildren(arr, arr[i].id)

        if (children.length) {
          arr[i].subCate = children
        }
        out.push(arr[i])
      }
    }
    return out
  }
}

Getting following error {"message":"nestedChildren is not defined"}

3
  • Move the function definition outside the module.exports object? Commented Jul 6, 2021 at 11:40
  • How may i use after this ? Commented Jul 6, 2021 at 11:42
  • function nestedChildren(arr, parentId) { var out = [] for (var i in arr) { if (arr[i].parent_id == parentId) { var children = nestedChildren(arr, arr[i].id) if (children.length) { arr[i].subCate = children } out.push(arr[i]) } } return out } Also use this but getting same error Commented Jul 6, 2021 at 11:46

1 Answer 1

3

As @jonrsharpe suggested, move the function outside of the export:

let nestedChildren = function(arr, parentId) {
    var out = [];
    for (var i in arr) {
        if (arr[i].parent_id == parentId) {
            var children = nestedChildren(arr, arr[i].id);

            if (children.length) {
                arr[i].subCate = children;
            }
            out.push(arr[i]);
        }
    }
    return out;
};

module.exports = {
    nestedChildren,
    cleanCode: function(){
        return 'clean code helper';
    }
};

Properties of an JavaScript Object cannot reference themselves or any other property of the same object. Thus, a recursive function within an object is not possible.

To work around this problem, you can move the function to the upper scope (outside of the object) where it's accessible from within the object.

So what I did was defining the function outside of the object as standalone function and then I referenced it in your export.

module.exports = {
    nestedChildren,
    ...
};

is just a shorthand for

module.exports = {
    nestedChildren: nestedChildren,
    ...
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you its working ,Please explain as well
@webdeveloper Hope it's clearer now. Let me know if you have any more questions
@webdeveloper No problem! Glad I could help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.