-2

Given the following block of JavaScript:

var n = { a: 1, b: "1.0", c: false, d: true };
var a = "b";

Can someone help me explain the following expressions:

n.a 
n[ a ]
n.a == n.b 
n.a === n.b 
n.b == n.d 
n.a =n= n.d  
n.c ? "a" : "b" 
n.e   
n.e 
n.e != null 
SouthernBoy
  • 223
  • 2
  • 5
  • All you need are [JavaScript Literal Objects](http://www.dyn-web.com/tutorials/object-literal/) and [=== vs ==](http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons) – frogatto Jun 11 '15 at 19:14

1 Answers1

0

The code creates two variables, an object (n) and a string (a). The object's properties can be accessed with the . or [] operator. You should read a description of how Javascript objects work, such as this one.

n.a                  // Accesses the 'a' property of n, which currently holds 1
n[ 'a' ]             // Also accesses the 'a' property. Same as above.
n[ a ]               // Since a holds the string 'b', the accesses the
                     // 'b' property of n
n.a == n.b           // Compares n's 'a' property to n's 'b' property
n.a === n.b          // Same, but does a strict comparison so type
                     // and value are compared
n.b == n.d           // Another comparison with different properties
n.a =n= n.d          // Sets n to true. Will cause the lines after this
                     // not to function as expected since n is no longer
                     // an object. See Barmar's comments below.
n.c ? "a" : "b"      // Shorthand for if (n.c) return "a" else return "b" 
n.e                  // Accesses 'e' attribute of n (Currently not set)
n.e != null          // Compares (unset) e attribute to null
bytesized
  • 1,502
  • 13
  • 22
  • You should update your answer based on the changes he made to the question. `o` is gone. – Barmar Jun 11 '15 at 19:02
  • 1
    `n.a =n= n.d` is equivalent to `n.a = (n = n.d)` – Barmar Jun 11 '15 at 19:03
  • @Barmar So `n = n.d` sets `n` equal to `true`. That makes sense, but now `n` is not an object so `n.a = true` is attempting to assign `true` to a property of a variable that is no longer an object. – bytesized Jun 11 '15 at 19:09
  • Apparently assigning to a property of a boolean causes no error, but it doesn't do anything. `true.a = true` – Barmar Jun 11 '15 at 19:12