0

I want to print an errormessage using javascript in certain cases. The string is german and the start depends on a variable called blfType which can be "field", "line" or "block" and the string then would be "This field already has this prerequisite" if blfType is field. I tried to do that similiar as I would do it in python:

alert("Das Feld"*(blfType == 'field') + "Die Zeile"*(blfType == 'line') + "Der Block"*(blfType == 'block')+" besitzt diese Vorraussetzung bereits");

But this would just print "NaN besitzt diese Vorraussetzung bereits". Is there any other way how I can do this in just one line or do I have to do create another Variable that takes the start of the sentence.


In this case I would do this in python like that:

const gerblfType = "Feld" if blfType === "field" else "Zeile" if blfType === "line" else "Block"

But this is also not working. Is there a smooth way in Javascript to not do it like that:

gerblfType = "Feld";
if(blfType == "line") gerblfType = "Zeile";
if(blfType == "block") gerblfType = "Block";
4
  • 1
    I think you have to do it like you just suggested, Javascript is just lame Commented Jul 30, 2021 at 17:22
  • 1
    const foo = { line: "Zeile", block: "Block" }; const gerblfType = foo[gerblfType] || "Feld"; Commented Jul 30, 2021 at 17:26
  • @epascarello that is also nice to know, thank you Commented Jul 30, 2021 at 17:31
  • Also with ternary gerblfType === "line" ? "Zeile" : gerblfType === "block" ? "Block" : "Feld" Commented Jul 30, 2021 at 17:37

2 Answers 2

1

Typical ways people would do it.

The if way

const foo = "two";

let bar = "default";
if(foo === "one") bar = "1";
else if(foo === "two") bar = "2";

console.log(bar);

With nested Ternary

const foo = "two";

const bar = foo === "one" ? "1" : foo === "two" ? "2" : "default";
console.log(bar);

With an object

const LOOK_UP = {
  one: "1",
  two: "2",
  default: "default"
};


const foo = "two";

const bar = LOOK_UP[foo] || LOOK_UP.default;
console.log(bar);

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

Comments

0

Use switch instead of ifs.

let gerblfType;
switch (blfType) {
  case 'line': gerblfType = 'Die Zeile'; break;
  case 'block': gerblfType = 'Der Block'; break;
  default: gerblfType = 'Das Feld'; break;
}

alert(`${gerblfType} besitzt diese Vorraussetzung bereits`);

1 Comment

Yeah i know, switch case is usually better than ifs, but the goal was to keep the lines in this function as few as possible. Usually i am using switch case over if

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.