Hemanth's Scribes

javascript

JavaScript ReferenceError: Invalid left-hand side in assignment

Author Photo

Hemanth HM

So lately was trying some silly syntax with JavaScript, logically it seems to work, but throw away your dry logic!

Most of us who have been pawing at some raw JS knows undefined || "hi" would result in "hi", on the same lines, I tried:

> obj = {}
Object

> obj["prop"] || obj["prop"] = "newprop"
   
ReferenceError: Invalid left-hand side in assignment
    type: "invalid_lhs_in_assignment"
 
> obj["prop"] = obj["prop"] || "newprop"

> obj.prop
"newprop"

// Works this way ^_^

One of my friend @Altreus said “Lack of ||= saddens me” and @jasonmulligan’s solution helped!

Finally:

  • ||= is much needed.
  • obj['prop'] ||= "fun" would be nice!
  • There is already a proposal in ES5 for this now!

Happy hacking, hope we shall have more fun with more JS :)

EDIT 0 suggested by charliesome:

obj["prop"] || (obj["prop"] = "newprop");
#javascript