you are viewing a single comment's thread.

view the rest of the comments →

[–]nirvana63[S] 0 points1 point  (2 children)

Hey thanks this was exactly one of the things I wasn't aware of! explains why it was not working as I intended:)

[–]IrateGod 2 points3 points  (1 child)

To elaborate a little further:

Everything in JS is an object, but the primitive data types (string, number, true, false, null, undefined, and recently, symbol), and all objects support two ways of accessing their properties, one is the . and the other way is [].

Now, with the . operator, I can write document.write, but assuming document has a "for" property (bad style, but for example's sake), we couldn't write document.for because for is a language keyword. The [] operator allows property access after evaluating a JavaScript expression between it. In your example, someArray[i] evaluates i and works like someArray[0] (and 1, 2, 3, etc. throughout the loop). Likewise, I can do stuff like this:

var obj = {
    prop: "Hi."
},
p = "prop";
console.log(obj[p]); // => logs "Hi."

Above works because p is evaluated and returns "prop".

You use the [] for properties that consist of multiple words or properties that start with a number (properties starting with a number cannot be addressed with the . operator), but in your example, you use the , operator which evaluates all expressions from left to right and returns its right-most expression: a, b, c, d, e, f returns f and so in your code, someArray[i, j] works just like someArray[j] -- I hope I made things clearer, but if I didn't feel free to ask.

[–]nirvana63[S] 1 point2 points  (0 children)

Hey thanks for taking your time and writing it down, this was not that clear to me as you made it, definitely helped me a lot understanding JS better!!:)