26. Pas.sing Arguments, Why ==?


#1

https://www.codecademy.com/en/courses/objects-ii/4/5?curriculum_id=506324b3a7dffd00020bf661#

In the following exercise, we have a public method called askTeller within the class Person. Why are we using the notation == to set the parameter equal to 1234? Wouldn't we typically use ===?


`

Replace this line with your code.

function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;

this.askTeller = function(pass) {
if (pass == 1234) return bankBalance;
else return "Wrong password.";
};
}

var john = new Person('John','Smith',30);
/* the variable myBalance should access askTeller()
with a password as an argument */
var myBalance = john.askTeller(1234);


#2

The === operator checks for identity, meaning both value and type are identical.

== operator checks for equality, which means the value is the same (once cast) but the type is different.

"42" == 42   => true
"42" === 42  => false

From a practical point of view, it is best to use === and be sure your code is generating the correct type.


#3

Alright, so in this case, === would make sense because we are expected to enter the number 1234.

That clears things up. Thanks!


#4

If the number is returned from a prompt() it will be string data.

"1234" == 1234

That may be why the loose type is used.


#5

The === doesn't exactly check for identity. == will essentially convert "12" == 12 to 12 == 12 before comparing (called coercion). === does not do coercion and will compare right away. People tend to believe that === does more work than == by checking types, but it actually does less work by not coercing values.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.