Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why assign this variable to itself in this var declaration?

I was reading Ben Cherry's "JavaScript Module Pattern: In-Depth", and he had some example code that I didn't quite understand. Under the Cross-File Private State heading, there is some example code that has the following:

var _private = my._private = my._private || {}

This doesn't seem to be different from writing something like this:

var _private = my._private || {}

What's happening here and how are these two declarations different?

like image 741
JoeM05 Avatar asked Nov 29 '11 19:11

JoeM05


People also ask

Why is self needed instead of this in JavaScript?

In the JavaScript, “self” is a pattern to maintaining a reference to the original “this” keyword and also we can say that this is a technique to handle the events. Right now, “self” should not be used because modern browsers provide a “self” as global variable (window. self).

What does it mean to assign a variable?

To "assign" a variable means to symbolically associate a specific piece of information with a name. Any operations that are applied to this "name" (or variable) must hold true for any possible values. The assignment operator is the equals sign which SHOULD NEVER be used for equality, which is the double equals sign.

What is the purpose of using VAR in JavaScript?

The var keyword is used to declare variables in JavaScript. Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows. Storing a value in a variable is called variable initialization.

How do we assign an existing variable to a new variable?

We simply use the = to give the variable a new value.


1 Answers

var _private = my._private = my._private || {}

This line means use my._private if it exists, otherwise create a new object and set it to my._private.

More than one assignment expression can be used in a statement. The assignment operator uses (consumes) whatever is to the right of it and produces that value as its output to the left of the variable being assigned. So, in this case, with parentheses for clarity, the above is equivalent to var _private = (my._private = (my._private || {}))

This case is a type of lazy initialization. A less terse version would be:

if (!my._private) {
    my._private = {};
}
var _private = my._private;

In this case, it seems that the lazy initialization is more used for anywhere initialization than laziness. In other words, all functions can include this line to safely create or use my._private without blowing away the existing var.

like image 59
Nicole Avatar answered Oct 19 '22 09:10

Nicole