0

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.

JTC
  • 119
  • 1
  • 11
  • 3
    Are you sure it's exactly the same string, with one space on each side? – John Montgomery Feb 18 '21 at 01:22
  • Change your if-statement to `if (splitStatus[0]=='HI THERE')` without the spaces around `' HI THERE '` and that will also probably do the trick for you. You really need to _**understand**_ why your current statement isn't working, not just find a workaround, or you are bound for more trouble in the future. – Stephen P Feb 18 '21 at 02:00

3 Answers3

5

"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:

vuongvu
  • 811
  • 6
  • 15
  • You don't always need to use `===` over `==` – Seth B Feb 18 '21 at 01:32
  • 1
    Hey thanks for your answer . Yes i tried all these. But was getting the error. The answer posted by @The Bomb Squad solved my problem – JTC Feb 18 '21 at 01:32
  • @SethB you're right, but imo, it gives me a good practice to always use "===", "==" may lead to bugs later on. – vuongvu Feb 18 '21 at 01:34
  • 2
    @SethB - No, you don't always _need_ to, but it conveys intent and avoids unwanted coercion. It's good practice to use strict equality unless you actively _**want**_ the conversions done with `==` – Stephen P Feb 18 '21 at 01:35
2

Ok, I just woke up.. since u want me to give it as an answer I'll say it here :D
if(splitStatus[0].includes("HI THERE")){/*do your things*/}
The above works because it is unknown how much whitespacing(things like spacebar) exists in the text.. so if it INCLUDES your desired output.. do stuff

The Bomb Squad
  • 4,192
  • 1
  • 9
  • 17
0

= 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 '.

if (splitStatus[0]=='HI THERE'){
//You code
}