How does it work?

I can’t figure out how the a[prop] = a[prop] || works ??

var a = {
    b: ["1", "2", "3"],
    c: ["4", "5", "6"]
};

function f(prop, j) {
    if (j === 1) {
        a[prop] = a[prop] || [ ]; //what is the logic behind this line of code? how does it work??
    }
    return a;
}
console.log(f("b", 1));
console.log(f("d", 1));

Have you tried to do some changes in this function?

What happened when you change your

 a[prop] = a[prop] || [ ];

for:

 a[prop] = [ ] || [ ];

What is the output? Make some changes in this function and watch the results. If you can’t understand for yourself what is the result and what this do , let me know and I will help you.

It is a way to say that if a[prop] is undefined, make it an empty array. If it is defined, leave it as it is.

There is some interesting reading about this technique in the answers to this SO question:

1 Like

i understand what it does but i don’t understand how it works

If you don’t declare a ‘d’ on your array which means is undefined make an empty array. If is defined they leave the array the way you declare before.

Ah ok. Basically with the lazy evaluation when JS is going to check for the result of a[props] || [ ], the first element is undefined (so it will count as false). The result depends than on the second element, whose value is the one that will be given to the left side of the assignment.
If a[prop] is not undefined, it counts as true for the lazy evaluation and so there is no need to check for the second element.

1 Like

Thanks for the resource