DEV Community

JavaScript OR Assignment Operator

Adam Roynon on February 09, 2020

In JavaScript, there may be times when you want to assign one variable to a non-null value. The JavaScript OR assignment operator can be used to qu...
Collapse
 
rubenswieringa profile image
Ruben Swieringa

You’re talking about the regular OR-operator; the OR assignment-operator doesn’t exist in Javascript (unfortunately)

let a, b;
a = null || "something"; // OR-operator only returns
b ||= "something"; // OR assignment-operator assigns if variable is falsy
Collapse
 
acroynon profile image
Adam Roynon

I consider the standard or operator the one used in if statement, for boolean logic. Then the or assignment operator being used to assign values to variables (assign this value, if its falsey assign this value instead). I could be completely wrong in my phrasing, but I think it makes a nice distinction between the two use cases

Collapse
 
rubenswieringa profile image
Ruben Swieringa

You can consider a melon a nail when you hit it with a hammer, but it’s not going to make sense to anybody.

I’m afraid the long and short of it is just that the OR-assignment operator (||=) is not the OR-operator (||), sorry man.

Thread Thread
 
acroynon profile image
Adam Roynon

Okay, thanks for the clarification

Collapse
 
stefanovualto profile image
stefanovualto

You should replace "null" / "null or undefined" by "falsy".

And also have a look at the "??" operator.

Keep writing it is a good way to improve!

Collapse
 
acroynon profile image
Adam Roynon

Yeah, you're correct, it is a "falsely" value that is evaluated, I didn't want to make this post too complicated, but great to mention this for the curious readers. Thanks

I am not sure what you mean by "??" operator, I have written a post on the ternary operator and I plan to write a post about the optional chaining operator ('?.') in the future.

Collapse
 
stefanovualto profile image
stefanovualto

Here is the related documentation:

developer.mozilla.org/en-US/docs/W...

Thread Thread
 
acroynon profile image
Adam Roynon

Thanks, it seems like a more strict version of the OR assignment operator. Perhaps I shall create a post comparing the two

Thread Thread
 
stefanovualto profile image
stefanovualto

I think that you should point out the differences between falsy values (cf. developer.mozilla.org/en-US/docs/G...) and null/undefined checks (with ??). I think that will add value to your post.

Thread Thread
 
acroynon profile image
Adam Roynon

I think I shall leave this post as it is for now and cover the falsy values and the coalescing operator in separate posts, thank you for the feedback and ideas

Collapse
 
acroynon profile image
Adam Roynon

Great stuff, do you think my explanation in this post is good?

 
acroynon profile image
Adam Roynon

Okay thank you