1

Hope guys are doing well.

I'm a newb and still learning javascript.

My if condition isn't working, I created a simple if-else loop (if any condition is met it should print following conditions statement). I tried googling but couldn't found my answer.

The condition should work as, if the user doesn't enter first name it shouldn't print anything, when I'm trying to enter first name, the first name field is replaced with null and when the if condition is true it still prints else condition statement.

Below is my JS code.

if (this.firstName === null) {
    console.log('Please enter first name' + typeof(this.firstName));
} else {
    console.log('Contact Created is First name & Last name.');
}

I tried with =,==and===

2 Answers 2

2

Sorry, I couldn't understand your question, but I think you want something like this

console.log(this.firstName, typeof this.firstName)
if (!this.firstName) {
    console.log('Please enter first name' + typeof(this.firstName));
} else {
    console.log('Contact Created is First name & Last name.');
}

It'll show please enter first name if you don't specify the name. Because empty input has the value of '' and when it gets converted to Boolean it's false

4
  • It is still printing the else statement mate. Jan 27, 2022 at 11:03
  • updated the code, added additional console.log, now you should know what is the actual value and you can debug the issue
    – ytiq
    Jan 27, 2022 at 11:26
  • Thank you mate for your time. Jan 27, 2022 at 11:36
  • Np, glad I could help
    – ytiq
    Jan 28, 2022 at 0:38
2

This then necessarily means that the value that is being returned is not the null literal instead that could be undefined or something else. You may print the firstname on console and determine what you are getting. If you are getting null is it a literal null or a string null?

This syntax help you

if (this.firstName === undefined || this.firstName == null || this.firstName.length <= 0)
4
  • It is still printing the else statement bhai. Jan 27, 2022 at 11:04
  • What is console output for this.firstName?? Jan 27, 2022 at 11:04
  • Please enter first name basically it's a hardcoded message. Jan 27, 2022 at 11:06
  • i mean what is the output for consloe.log(this.firstName)? And can you also let us know your code for this object and its initialization? Jan 27, 2022 at 11:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .