There are times when even the most straightforward code seems puzzling. I recently stumbled upon a piece of JavaScript that has left me scratching my head. Despite adding a debugger to step through it, I'm still struggling to grasp its inner workings.
var obj = {};
var myID = 999;
var productID = 1;
var myModelID = 100;
var myCatID = 200;
var addMe = 1;
if (typeof obj[myCatID] == 'undefined') {
obj[myCatID] = {};
}
var locationObj = {
state: 'roch',
city: '3',
street: '2nd',
houseNum: '101'
};
var qty = 1;
obj[myCatID][myModelID]={
'location': locationObj,
'quantity': qty,
'prodID': productID,
'id': myID
};
I find myself in doubt about what's happening here — `obj[myCatID][myModelID]`. It appears to involve two properties accessed using bracket notation for `obj`, followed by an object assignment. But, my understanding remains foggy.
The outcome, as shown by my alert and debugger: !https://i.sstatic.net/Sn2K5.jpg
!https://i.sstatic.net/VBRHh.jpg
If I were to inject an additional bracket value to transform `obj[myCatID][myModelID]` into `obj[myCatID][myModelID][addMe]`, why am I confronted with a debug error stating "uncaught TypeError: Cannot set property '1' of undefined" upon execution? I fail to discern how this differs from `myModelID` and its declaration. Your assistance in overcoming this hurdle is greatly appreciated.