1

Saw some JS notation today that I've never seen before, bear with me if it is something common that everyone knows.

var cookiepath = cookiepath || '';

Now, is this just saying, if a variable named cookiepath already exists, set it to cookiepath or if it doesn't, set it to ''?

roflwaffle
  • 29,590
  • 21
  • 71
  • 94
  • possible duplicate of [Javascript || operator](http://stackoverflow.com/questions/1378619/javascript-operator) – Guffa Nov 15 '10 at 15:14

4 Answers4

2

You are correct.

The || operator evaluates to the first of its operands that is "truthy".
If the first operand is "truthy", the second one is not evaluated at all.
(If neither operand is truthy, it evaluates to the second one)

Truthy means anything but undefined, null, false, 0, NaN, or "", .

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

The cookiepath variable is being declared, an initialized.

The var statement doesn't make any harm if an identifier was already declared in the current lexical scope.

If cookiepath wasn't declared yet, the var statement, before run-time, will initialize the variable to undefined.

After that, in run-time, the assignment is made, if it's value is falsy (other than null, undefined, an empty string, 0, NaN, or false) it's set to an empty string.

Keep in mind that you have access to the cookiepath variable in the local scope.

Consider the following example:

var cookiepath = 'outer';
(function () {
    var cookiepath = cookiepath || "";
    alert(cookiepath); // alerts an empty string, not "outer"
})();

In the above example, we have a global cookiepath variable, on the global scope, but when the function is executed, a local cookiepath variable will be declared on the scope of the function, and this shadows the value of the outer scope, and this behavior is noticeable even before the var statement in the function, e.g.:

var foo = 'foo';
(function () {
    alert(foo); // undefined, not 'foo' from the outer scope
    var foo; // undefined
})();
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
0

as @SLaks says it evaluates to first true so this code will result in wrong execution:

var cookiepath = false;
var cookiepath = cookiepath || "";
# cookiepath === ""
mpapis
  • 52,729
  • 14
  • 121
  • 158
0

It's a way to provide a default value.

Here, cookiepath will get the value '' assigned only if it's value is null, false, undefined, 0, empty string, or NaN. Otherwise, it will stay the same.

Hugo Migneron
  • 4,867
  • 1
  • 32
  • 52