0

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 ''?

2
  • possible duplicate of Javascript || operator Commented Nov 15, 2010 at 15:14
  • This question is similar to: Javascript || operator. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Oct 8, 2024 at 18:25

4 Answers 4

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
})();
Sign up to request clarification or add additional context in comments.

Comments

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 "", .

Comments

0

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

var cookiepath = false;
var cookiepath = cookiepath || "";
# cookiepath === ""

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.