Search code examples
javascriptconditional-statementscomparison-operators

Difference between (age==18) and (age===18) in JavaScript?


I was doing this program and not getting output but if I entered age 18 after typecasting the age in the second block of code I got the output why is it so?

And if I use only two "==" sign then also I got the output but in case of "===" I didn't get the output.

  • age == 18 Got the output
  • Number(age)===18 Got the output
  • age === 18 Didn't got the output

Both the codes are given below.

With "==="

var age=prompt("Enter your age");
if(age<18){
  alert("Sorry, You are too young to drive this car Powering off");
}else if(age>18){
  alert("Powering On Enjoy the ride!");
}else if(age===18){
  alert("Congratulation on your first riding Enjoy the ride!");
}

With typecasting "Number(age)===18"

var age = prompt("What is your age?");
if (Number(age) < 18) {
  alert("Sorry, you are too young to drive this car. Powering off");
} else if (Number(age) > 18) {
  alert("Powering On. Enjoy the ride!");
} else if (Number(age) === 18) {
  alert("Congratulations on your first year of driving. Enjoy the ride!");
}

Solution

  • prompt always returns a value in string format.

    Suppose a string and number have same value (say 18 and '18'). Here the value is same, only the type differs. Comparing a string value with a number will return true if only value is compared and false if type is also compared.

    == compares two value without comparing the types. == is called as Abstract Equality Comparison which compares value only, not type. == will perform a type conversion when comparing two things.

    console.log(18 == '18'); // Expect true

    === compares two value by comparing the types. === is called as Strict Equality Comparison this will compare both value and type

    console.log(18 === '18'); // Expect false

    In case of Number(age) === 18, the string age is converted to numeric age and hence this both the value is od type number. Hence this will return true

    Read More on == and ===

    const age = prompt("Enter your age");
    console.log(`Type of Age = ${typeof age}`);
    const numbericAge = +age; // String to number conversion, Same as Number(age)
    console.log(`Type of Numeric Age = ${typeof numbericAge}`);
    if (numbericAge < 18) {
      alert("Sorry, You are too young to drive this car Powering off");
    } else if (numbericAge > 18) {
      alert("Powering On Enjoy the ride!");
    } else if (numbericAge === 18) {
      alert("Congratulation on your first riding Enjoy the ride!");
    }