== operator not working inside If statement (JavaScript)

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.

21 thoughts on “== operator not working inside If statement (JavaScript)”

  1. = 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
  2. 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 ".

    let status = ' HI THERE \nHELLO WORLD'
    let splitStatus = status.split('\n')
    if (splitStatus[0].includes('HI THERE')) {
      console.log(`using includes without the spaces in the string: true`)
    if(splitStatus[0] === " HI THERE "){
      console.log(`using strict equals: true as there are spaces in the string`)
    if(splitStatus[0] === "HI THERE"){
      console.log(`without the spaces in the strict comparitive conditional: false`)

Leave a Comment