0

I've found several articles, both here on SO and elsewhere that mention this error message, but none that I can apply to my specific situation. Can anyone help me understand what's going on?

If I write my code like so:

selDocument.group_selected = function ($, anchor) {
    let tmpitems = $(".chkSelectedField:checked");
    if (tmpitems.length > 1) {
        let items = [];
        $(tmpitems).each(function (a, b) {
            items.push($(b).val());
        });
        if (typeof anchor != 'undefined') {
            items = items.filter(el => el != anchor);
        } else {
            anchor = items.shift();
        }
        console.log("57199516 items, anchor", items, anchor);

it works fine, but if I take those blocks and break them into their own function:

selDocument.group_selected = function ($, anchor) {
        let tmpitems = $(".chkSelectedField:checked");
        if (tmpitems.length > 1) {
            let retval = selDocument.create_items_array($, tmpitems, anchor);
            let items = retval.items;
            anchor = retval.anchor;
            console.log("57199516 items, anchor", items, anchor);
...
selDocument.create_items_array = function ($, tmpitems, anchor) {
    let items = [];
    $(tmpitems).each(function (a, b) {
        items.push($(b).val());
    });
    if (typeof anchor != 'undefined') {
        items = items.filter(el => el != anchor);
    } else {
        anchor = items.shift();
    }
    return JSON.parse({ 'items': items, 'anchor': anchor });
};

I get "Cannot access 'anchor' before initialization."

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Bill in Kansas City
  • 360
  • 1
  • 5
  • 21
  • 1
    because the variable is scoped to the block. – epascarello May 13 '22 at 03:59
  • https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – epascarello May 13 '22 at 04:01
  • Because you use anchor as variable not value in `anchor = items.shift();` – masoud May 13 '22 at 04:04
  • You don't have `let anchor` in your first code snippet. You shouldn't have it in your second either. – Bergi May 13 '22 at 04:05
  • Also, that `JSON.parse(…)` call makes no sense. You should just return the object. – Bergi May 13 '22 at 04:06
  • @Bergi You're absolutely right. It was late. Also, why would I have ```let anchor``` if anchor is being passed into the function? (OH! yes, I see it in the second, you're right about that one. Question still stands.) @epascarello anchor is being passed in as a parameter to the function. How would it be scoped to the block? – Bill in Kansas City May 13 '22 at 14:56
  • @masoud I see what you mean. I was unaware of this behavior in js. – Bill in Kansas City May 13 '22 at 15:08

0 Answers0