I come from Ruby world and entering the JavaScript world. One feature of Ruby language is the case
statements to evaluate a target value:
my_val = case my_var
when "var1" then "value1"
when "var2" then "value2"
else "value3"
end
# my_val evaluated to a specific value
puts my_val
Can I do something as succinct in JavaScript as above? This is the closest I get:
let myVal = null;
switch (myVar) {
case "var1":
myVal = "value1";
break;
case "var2":
myVal = "value2";
break;
default:
myVal = "value3";
}
// my_val evaluated to a specific value
console.log(myVal);
You could use an object with a ternary to set a default value like so:
const obj = {
"var1":"value1",
"var2":"value2",
"defaultVal": "value3" // default value
},
getVal = sVar => sVar in obj ? obj[sVar] : obj["defaultVal"];
// Use case 1:
console.log(getVal("var1")); // get "var1" from the object
// Use case 2:
console.log(getVal("foo")); // get "foo" from the object, doesn't exsist, so we get the default value
The above creates an object, where each key in the object points to a value (ie what myVar
should turn into). If myVar
is not in the object, it will default to defaultVal
, if it is in the object it will retrieve the associated value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With