JavaScript Getting Started With ES2015 Defining Variables With let and const Defining a Variable with let

How does this condition work?

Hi, Please help me understand how the person.role value is used as a condition? An added test on the previous line shows that this is a string.

        function personDescription(person) {
            var description = person.first_name;
            alert(typeof(person.role) === "string");   // true
            if(person.role) {                                        // a condition using a string???
                description = description + " is a ";
                description = description + person.role;

1 Answer

Nick Hericks
.a{fill-rule:evenodd;}techdegree seal-36
Nick Hericks
Full Stack JavaScript Techdegree Graduate 20,690 Points

If I understand this correctly, I believe the example is using an object property as a condition. So if the 'person' object has a property named 'role', then the condition is true. If there is no 'role' property for the 'person' object, then the condition would evaluate to false.

The reason typeof is telling you it's a string is because the value of that object property is a string. Test this by changing the value of person.role from a string to a number (Ex. person.role = 23) and you'll see that typeof will tell you it is now a number.