Search code examples
javascriptfor-in-loop

What does " var x = "theBomb" in megalomaniac; " do?


I'm working through JavaScript koans from GitHub and got stopped by this one:

it("should have the bomb", function () {

  var hasBomb = "theBomb" in megalomaniac;

  expect(hasBomb).toBe(FILL_ME_IN);
});

I've never seen the construction

var x = "y" in object;   

before and I'm not sure what it is doing. The koan expects hasBomb to be true.


Solution

  • The statement is comprised of two parts:

    1. "theBomb" in megalomaniac; checks whether a property named theBomb exists in the Object megalomaniac (or in its prototype chain). See in Operator.
    2. var hasBomb = "theBomb" in megalomaniac; assigns the value of that check (either true or false) to the variable hasBomb.

    Example:

    var megalomaniac = {theBomb: 'boom'};
    
    var hasBomb = "theBomb" in megalomaniac;
    
    console.log(hasBomb); // true