0

I need some help in this conditional code. In order to store the required data to the variable paw, I have three conditions.

  1. If nameu is not blank or empty and empidu is blank or empty, it should store the Title : nameu only.
  2. Else if nameu is blank or empty and empidu is not blank or empty, it should store the EmpID : empidu only.
  3. Else store both.

I have written the code myself, but it is not working. Here is the code :

var paw = "";
    if(nameu !== " ") {
       paw = JSON.stringify({
        Title: nameu
      });
    }
    else if(nameu === "" & empidu !== " ") {
       paw = JSON.stringify({
        EmpID: empidu
      });
    }
    else {
     paw = JSON.stringify({
      Title: nameu,
      EmpID: empidu,
    });
  }

Note : nameu (String) and empidu (number) are user input values

I think I am either writing wrong statements or logic. Please help me.

2 Answers 2

1

You should use logical AND operator (&&) to evaluate multiple expressions instead of bitwise AND (&)

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

Comments

0
  1. you can use this code
    let paw = {};
    if (nameu.trim() !== ''){
       paw.Title=nameu;
    }
    if (empidu.trim() !== ''){
       paw.EmpID = empidu;
    }
    paw = JSON.stringify(paw);

2 Comments

Thank you for your answer. But adding && worked for me. Here is the code : var paw = ""; if(nameu !== " " && empidu === "") { paw = JSON.stringify({ Title: nameu }); } else if(nameu === "" && empidu !== " ") { paw = JSON.stringify({ EmpID: empidu }); } else { paw = JSON.stringify({ Title: nameu, EmpID: empidu, }); }
It's really good but you can improve your code and maintainable happy coding!

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.