user2034901
user2034901

Reputation:

JavaScript not comparing properly

I have a program written in JS. It compares output of an function with number 4. However, it seems it cannot compare properly.

var myStringNotValidated =  "3T-4T";

var notValidate = myStringNotValidated.substring(3, 4);

if(notValidate === 4)
{
console.log("Value1");
}
else
{
console.log("null");
}
//OUTPUT IS NULL, WHICH IDEALLY SHOULD BE "Value1"

Can any one guide me where am I making mistake?

Upvotes: 0

Views: 213

Answers (6)

Sudipta Basak
Sudipta Basak

Reputation: 178

Try this :

var myStringNotValidated =  "3T-4T";

var notValidate = myStringNotValidated.substring(3, 4);

if(notValidate === "4")
{
console.log("Value1");
}
else
{
console.log("null");
}

Upvotes: 1

Code_Tech
Code_Tech

Reputation: 795

You are trapped in the same mistake which most JS developers do!

There is an difference between === and == in JS. (Difference between == and === in JavaScript). Because of this, when you compare "4" with 4, it compares (String 4) with (Numeric 4), hence returning your else condition.

Solution: Just replace === with ==

var myStringNotValidated =  "3T-4T";
var notValidate = myStringNotValidated.substring(3, 4);
if(notValidate == 4)
{
console.log("Value1");
}
else
{
console.log("null");
}

https://jsfiddle.net/pfrvn485/

Upvotes: 2

user9941177
user9941177

Reputation:

You're comparing the string("4") with the int type(4). Need to be converted to an integer before comparing.

var myStringNotValidated =  "3T-4T";

var notValidate = parseInt(myStringNotValidated.substring(3, 4));

if(notValidate === 4)
{
console.log("Value1");
}
else
{
console.log("null");
}

Upvotes: 1

Sawan Patodia
Sawan Patodia

Reputation: 839

This is because === compares both value and type. In your program, noValidate contains a value of 4 but its type is string and you are comparing it with 4 whose type is number.

You can either use == or typecast noValidate to number.

var myStringNotValidated =  "3T-4T";

var notValidate = Number(myStringNotValidated.substring(3, 4));
console.log(typeof notValidate);
if(notValidate === 4)
{
console.log("Value1");
}
else
{
console.log("null");
}

Upvotes: 1

Joseph Stalin
Joseph Stalin

Reputation: 140

Your if condition is wrong if(notValidate === 4) checks 4 as string. either you can use if(notValidate=='4') or convert it to number & check.

Upvotes: 1

Damian Peralta
Damian Peralta

Reputation: 1866

It depends, if you want to check if notValidate is a string:

var myStringNotValidated =  "3T-4T";

var notValidate = myStringNotValidated.substring(3, 4);

if(notValidate === "4") // Change here
{
console.log("Value1");
}
else
{
console.log("null");
}

if you want to check if notValidate is a number, use parseInt():

var myStringNotValidated =  "3T-4T";

var notValidate = parseInt(myStringNotValidated.substring(3, 4)); // Change here

if(notValidate === 4)
{
console.log("Value1");
}
else
{
console.log("null");
}

Upvotes: 1

Related Questions