So in JavaScript, there's a concept called method chaining, it's actually not specific to JavaScript, you'll find that this pattern in a number of languages, but it's something it's very good to be aware of. And it can also help you to write code, it's a little bit more expressive. So on the left side of the page, you've got this object called app. And this app object has three methods in it, start and setup, we don't really care what they do, let's pretend they do something magical and amazing. But the main thing is that we have an object with three methods. And on the right side of the page, I execute those methods by saying app dot init.
App dot start an app dot setup. So that all makes perfect sense seems like a pretty, pretty good, solid way to go. But what if In addition to these, these methods, doing whatever it is they do? What if they were all to return a very specific value? What if they all returned this? Well, we know that in JavaScript, the the this keyword refers to the object to which a method belongs.
So in each one of these cases, I'm returning app. The End method returns app, the start method returns app. And instead of method returns app, so that means on the right side, I could change the way I'm writing my code, I could do something like this, where I say app dot init dot start dot setup. And the reason that works is because each time I execute one of these methods, it's returning app, which allows me to directly execute another method on that object. So when I say app, dot and knit that directly returns app, which allows me to say dot start, and then the start method returns app, which allows me to say dot setup. So another way to look at this would be think about the direct connection between this an app you know, in the init method, I'm returning this, which means I'm returning app, which allows me to directly call the start method.
And then when I call the start method, I'm returning this which allows me to call the setup method. And that allows me to I couldn't even maybe Shane another method on here and created a method called foo, and then a method called bar and a method bags and just I could chain all day. But this pattern, if you look at the code on the right looks quite a bit different than saying app dot init app dot start app dot setup. The code may be a little bit more expressive. And if you're really creative, you can write code that maybe even be easier to manage. So it's not mandatory that you do method chaining.
It's simply a pattern that's good to be aware of, and can be very helpful at time. So let's see if we can get a better understanding of method chaining. If we actually look at some code examples.