I have a JavaScript array called splitstatus which takes data from a variable called "status". splitStatus[0] and splitStatus[1] contains text inside it .
I doubled checked it by using console.log
let splitStatus=status.split('\n')
for(let i=0;i<splitStatus.length;i++){
console.log(splitStatus[0]); // shows output HI THERE
console.log(splitStatus[1]); // shows output HELLO WORLD
}
The code above is working as i expected, as splitStatus[0] has ‘HI THERE’ stored inside and splitStatus[1] has ‘HELLO WORLD’ inside.
ISSUE: "if condition" doesn’t work with the "==" operator as shown below
if (splitStatus[0]==' HI THERE '){
//my code
}
when i put just "=" it works, but i want to put "==". Can someone tell me what im doing wrong. Thanks a lot for reading.
=
is an assignment opeator. When you write=
, that means you are assigning' HI THERE '
to splitStatus[0]. And assigning a variable will always true.You are doing wrong while compare in if condition.
Remove space from begin and end of string. It campare the string with spaces, which are not in your output string.
Use
'HI THERE' instead of ' HI THERE '
.You can use
.includes
it will ignore the white spaces… Your reason the==
operand is not working is the two strings are not equal as you have white space in your conditional string" HI THERE "
."HI THERE" is not equal to " HI THERE ".
btw you should use "===" than "==" to compare variables and shouldn’t use "=" as it’s an assignment operator, assignment operator will always return
true
so it worked in your case.Learn more: