1

Currently I'm learning angular JS, but I think that this question is related to javascript. First I did my code (as the tutorial was saying to do), then, when I got into the next level, I saw something different.

The tutorial was saying:

"Make a function that sets the this.current var, but when there is no value passed, set it to 0".

And I, with all my "noobly" did that, and it worked:

app.controller('GalleryController', function(){
    this.current = 0;
    this.setCurrent = function(newGallery){
        if(newGallery === null){
            this.current = 0;
            return;
        }
        this.current = newGallery;
    };
});

And that is what I saw before:

app.controller('GalleryController', function(){
    this.current = 0;
    this.setCurrent = function(newGallery){
        this.current = newGallery || 0;
    };
});

What I'm asking, how it works and why it works. Since it is just an OR operator

Thanks.

  • The code `this.current = newGallery || 0;` is a shorthand way of saying `this.current` should be `newGallery` unless it returns false, in that case, use `0` – user372495 Feb 19 '16 at 22:24
  • `value || value` is an expression, it evaluates to the first value if it is truethy, else it evaluates to the second. – Kevin B Feb 19 '16 at 22:24
  • You need to learn what "`truthy`"` and "`falsey`" mean in JavaScript. – PM 77-1 Feb 19 '16 at 22:24
  • Thanks! I got how it works now, it is very useful, here's a link explaining that: http://www.sitepoint.com/javascript-truthy-falsy/ – Mateus Mercer Feb 19 '16 at 22:29

0 Answers0