Learn how JavaScript handles primitive values and references (objects and arrays).

Play around by running JS statements, and seeing how the data are structured in the memory.

---

Try these (type or copy into the input box, and press Enter).

  • Set x to the number 5 (a primitive value).
x = 5 
  • Double x by multiplying its current value.
x = x*2 
  • Double x again using compound assignment.
x *= 2 
  • Create an array y of three numbers (an object stored by reference).
y = [1, 2, 3] 
  • Copy the primitive value of x into z (no aliasing for primitives).
z = x 
  • Copy the reference of array y into u (now u and y alias the same array).
u = y 
  • Mutate the first element of y to demonstrate mutations are visible through all aliases.
y[0] = 7 
  • Read the first element via the alias to show shared state.
console.log(u[0]) 
  • Create two separate but identical-looking objects and compare them by reference (not equal).
x = {name: "Johnny", age: 21}
y = {name: "Johnny", age: 21}
console.log(x==y) 
  • Point x to the same object as y and compare again (equal by reference).
x = y
console.log(x==y) 
  • Create two distinct user objects and put their references into an array z.
x = {name: "Johnny", age: 21}
y = {name: "Jimmy", age: 61}
z = [x, y] 
  • Remove the standalone variables; the objects remain reachable via z.
delete x
delete y 
  • Attempt property access with incorrect syntax, then access the first object's age correctly.
console.log(z[0.age])
console.log(z[0].age) 
  • Create a nested user object with an address.
user = {name: "Jim", address: {city: "London", street: "Downing Street"}} 
  • Set the name via the property.
user.name = "Joey" 
  • Add a roles array and push a new role to show in-place mutation.
user.roles = ["admin"]
user.roles.push("operator") 
  • Log the number of roles.
console.log(user.roles.length) 
  • Replace a role by index to mutate an element in-place.
user.roles[1] = "moderator" 
  • Try the difference between referencing a method and calling it, then pop the last role correctly.
user.roles.pop
user.roles.pop() 


Published 18 hours ago
StatusIn development
CategoryTool
PlatformsHTML5
Authorpontosan3