-2

When I use '=' in my if statement I get undefined, but when I use '===' I get my expected result. Can someone explain what's happening there?

function once(callback) {
  let counter = 0;
  let result;
  function sum(x) {
    if (counter === 0) {
      result = callback(x);
      counter++;
    }
    return result;
  }
  return sum;
}
const addByTwoOnce = once(function(num) {
  return num + 2;
});

// UNCOMMENT THESE TO TEST YOUR WORK!
console.log(addByTwoOnce(5));  //should log 7
console.log(addByTwoOnce(10));  //should log 7
console.log(addByTwoOnce(9001));  //should log 7
kay
  • 1
  • 3
  • Well, `=` and `===` mean two significantly different things. – Pointy Jul 13 '21 at 15:47
  • Does this answer your question? [Which equals operator (== vs ===) should be used in JavaScript comparisons?](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons) – Alexis Garcia Jul 13 '21 at 15:49
  • [In javascript == vs =?](https://stackoverflow.com/q/11871616) – VLAZ Jul 13 '21 at 16:10

6 Answers6

2

'=' means you are assigning value to the variable.

if(count = 0)

means count value becomes 0.

'==' or '===' means checking the value.

if(count == 0)

checks count is 0 or not.

if(count === 0) // Strict equality comparison which means checks types also

checks count is 0 and checks both types are also equal or not.

kadina
  • 5,042
  • 4
  • 42
  • 83
1

= is Assignment operator

=== is a strict equality comparison operator

So if you are using = to your condition, it does assign the value to variable.

if (counter = 0) { // counter value is 0
      result = callback(x);
      counter++;
}

This could throw an error in strict mode

expected a condition but found an assignment

underscore
  • 6,495
  • 6
  • 39
  • 78
1

= is used to set values, and === is used to strictly compare values.

This article has a good explanation of the differences between == and ===: https://bytearcher.com/articles/equality-comparison-operator-javascript/

One = is only used to assign values, e.g. var x = 2;

AbsentBird
  • 321
  • 1
  • 8
0

Single '=' means you are assigning a RHS value to LHS

Double or 3 '===' means you are comparing LHS and RHS

Please explore more about assignment and comparison operators

0
  1. = is used to assign values to any variable.
  2. == is to check if the 2 values are equal or not
  3. and === will check the values and their data types also.

FOR EX:-

float A = 1 and int B= 1

if (A==B) //TRUE

BUT IF(A===B) //FALSE ,because a and b have different datatypes

Harshal
  • 199
  • 3
  • 8
0

= is use for assignment while ==&=== is use for comparing two sides

BONUS: == is used to compare the condition if LHS==RHS while === not only compares LHS&RHS But also check both LHS AND RHS Should have same data type 'int:int','string:string','float:float' then only comparison between LHS& RHS is Done

TeraCotta
  • 55
  • 10