0

Is it possible to have a variable be defined as two different things without using an array?

So for example:

var myVar = "asd" || "fgh" // or maybe it's "asd" && "fgh"?
var message = "asdtest"
var otherMessage = "fghtest"
if (message === myVar + "test") {
   console.log("success!")
}
else if (otherMessage === myVar + "test") {
   console.log("success!")
}
2
  • 2
    Nope, that's why there's conditions and assignment, though. Commented Nov 6, 2017 at 2:15
  • @PHPglue true . Commented Nov 6, 2017 at 2:16

5 Answers 5

2

No, a variable can only hold a single thing at a time. If you want multiple things, you should use an array.

var myVar = "asd" || "fgh"

This line of code will evaluate "asd" to see if it is 'truthy', and it is. Therefore, myVar is set to "asd". If instead it were 'falsy', for example if you did var myVar = null || "fgh", then it would set myVar to the second part, thus making it equal "fgh".

Sign up to request clarification or add additional context in comments.

Comments

2

This is just one definition. The variable will be assigned to the value of the expression on the right side. In principle, this is the same thing as

var x = 1 + 2;

How || works is that it is logical OR: It returns the first "truthy" value (such as a non-empty String, all values are truthy unless they are false, 0, "", null, undefined, or NaN). This is useful if you want to give defaults to "missing" values for example:

var size = specifiedSize || 100;

In your case, it is simply asd.

Comments

1

A variable can only hold a single value. However, your variable can be referencing an array or an object, which can hold more than one value.

Comments

1

You may use objects or arrays to store all possible values:

var myVarObj = {
  p1: "asd"
  p2: "fgh"
};

var myVarArr = ["asd", "fgh"];

for (var property in myVarObj) {
    if (message === myVarObj[property] + "test") {
        console.log("success!");
    }
}

for (var value in myVarArr) {
    if (message === value + "test") {
        console.log("success!");
    }
}

Comments

1

You can use a function expression

var myVar = bool => bool ? "asd" : "fgh";

console.log(myVar(1)); // `"asd"`
console.log(myVar(0)); // `"fgh"`

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.