JavaScript x = x || {}

Seeing an OR” operator inside of a JavaScript assignment can be confusing to interpret. That assignment becomes more obvious once we remember two rules about JavaScript Boolean evaluation. If that puzzles you, please read on. Once you see it you will never forget it:

The thing to remember is that JavaScript OR-evaluations, short-circuit when the very first true value is found.

By short-circuiting I mean that the Boolean-inspection comes to an end and the operand on the right is never checked. By being true I mean that the value in the first operand already exists in the current program context as an identifier representing something , or, if not an identifier, the number is at least a valid value (not false or undefined).

When the JavaScript || (or) operator sees the first value as true, it does not check the second value. It short-circuits by assuming the result as true.

When this type of “construct” is used in an assignment, the first value to be true becomes the value assigned.

The other thing to know is that, in JavaScript, a Boolean evaluation is done from left to right.

Based on those two concepts, we can see why 2 is the value assigned to x in the following example:

var x = 2 || 3;  //2

Let me throw in two more examples just to make it clear:

var y = undefined || 5; //5

let z = true || 7; //true

For that matter, when we see in JavaScript something like the following declaration:

var x = x || {};

It means that, if x exists, it is assigned to variable x, which is the same as no change at all since it remains the same. If however, x does not exist, then a new empty object with the name of x is created.

Just for the sake of completion, when it comes to the && (AND) Boolean operator, there is no short-circuit evaluation since both operands must be evaluated. In that case, the last operand to the right is the one assigned to the variable.

Examples:

var x = 3 && 4 && 5;  // 5

var x = x && {}  // {}

The OR operator in the configuration discussed above, is widely used when initiating an object or an array for the purpose of sequentially adding values to the object or array being created.

Example:

 let inventory = {};
 function addMe(myObject, myArray, value) {
      myObject[myArray] = myObject[myArray] || [];
       myObject[myArray].push(value);
 }
 addMe(inventory, ‘colors’, ‘blue’);
 console.log(inventory); // { colors: [ ‘blue’ ] }
 addMe(inventory, ‘colors’, ‘orange’);
 addMe(inventory, ‘clients’, ‘Ada Lovelace’);
 console.log(inventory);
 /*
 { colors: [ ‘blue’ ] }
 { colors: [ ‘blue’, ‘orange’ ], clients: [ ‘Ada Lovelace’ ] }
 */

One more thing:

If you use let instead of “var” in the following example, you will get an error (even if the x variable already exists):

let x = x || {};  // error

This is because let-variables are not hoisted (copied to the top of the execution scope) and therefore the word "x" is totally unknown at the time of declaration. In addition, the visibility of a let variable starts at the point of declaration and downward until the end of the code-block (which totally bypasses any preexisting variable with the same name). In my view, "let" is just another useful way of declaring variables and it have many advantages, but it is not a complete replacement for var.

Cheers,

Tony de Araujo

Advertisements

Learning JavaScript

I’m really happy to announce that my eBook JavaScript in Plain Language – A Self-Study Method: JSON and AngularJS Prep has been updated.

If you’re looking to learn or relearn JavaScript please be assured that I have put a lot of thought into this publication based on the feedback from thousands of students I have coached over the years. Please check it out…

Get your lucky numbers with Angular

This snippet is based on the JavaScript exercise published on my eBook
“Small Projects to Learn JavaScript – Drawing Six ‘Lucky’ Numbers”

AngularJS was not even mentioned on the project but I figured it was time to demonstrate a way to implement AngularJS since it is the most popular implementation wanted right now.

Here it is: JSPLAIN

Have fun!

Tony

JavaScript Objects Functions and Arrays Explained

How many times have you attempted to learn JavaScript, only to put it on the side because it was too complex or you felt overwhelmed by the information overload?

JavaScript Objects Functions and Arrays Explained is easy to understand with plenty of illustrations and links to code files you can physically copy. Easy does not mean simple, it will not insult your intelligence and capacity to learn new concepts. This is a serious book for those wanting to understand how JavaScript works.

This book can be used as a reference if you need a detailed explanation on how a certain method works.
The key to master JavaScript is to become familiar with its library methods.

Get it today and start learning. You don’t need to own a Kindle. You’ll be able to read it on anyone of your computers by downloading the free Kindle app.
–> JavaScript Objects Functions and Arrays Explained

book_object

Fahrenheit to Celsius – JavaScript and AngularJS

You probably know how to convert Fahrenheit to Celsius in JavaScript but how would you display it on a web page?

Google has come up with a modern solution: AngularJS

AngularJS is a way to make your HTML more dynamic and it is easy to implement.

Take a look at my sample here:
http://jsplain.com/javascript/index.php/Thread/45-Fahrenheit-to-Celsius-ng-model/

Have fun testing it!
Tony

On Learning

“People that learn quickly only focus on the information and skills that matter – excuses don’t matter, and they are thought viruses.” – Kevin Horsley

“No time? Time is always there; you just need to schedule it.”