Introduction
JavaScript is a language of the Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.
Before moving further let us look at the previous articles of the series:
- Voice of a Developer: JavaScript Data Types - Part One
- Voice of a Developer: JavaScript Objects - Part Two
- Voice of a Developer: JavaScript Engines - Part Three
- Voice of a Developer: JavaScript Common Mistakes - Part Four
- Voice of a Developer: Editors - Part Five
- Voice of a Developer: VSCode - Part Six
- Voice of a Developer: Debugging Capabilities of VSCode - Part Seven
- Voice of a Developer: JavaScript OOP - Part Eight
- Voice of a Developer: JavaScript Useful Reserved Keywords - Part Nine
- Voice of a Developer: JavaScript Functions - Part Ten
- Voice of a Developer: JavaScript Functions Invocations - Part Eleven
- Voice of a Developer: JavaScript Anonymous Functions - Part Twelve
- Voice of a Developer: JavaScript Pure And Impure Function - Part Thirteen
- Voice of a Developer: JavaScript Closures - Part Fourteen
- Voice of a Developer: JavaScript Currying - Part Fifteen
Chaining

- $("#h1").text("Change text").css("color", "red");
- Another example of chaining
- while working with strings: var s = "hello";
- s.substring(0, 4).replace('h', 'H'); //Hell
Chaining methods
Ques: What is returned if there is no return statement in the method?
Ques: How is chaining implemented?
Ans: When a method returns this; the entire object is returned & it is passed to next method and it is called chaining. Example,
- var games = function() {
- this.name = '';
- }
- games.prototype.getName = function() {
- this.name = 'Age of Empire';
- return this;
- }
- games.prototype.setName = function(n) {
- this.name = n;
- }
- //now execute it
- var g = new games();
- g.getName().setName('Angry Birds');
- console.log(g.name);
Advantages
- Code is more maintainable, simple, lean
- It is easy to read chaining code
Simplify code after chaining
- var vehicles = "Bike|Car|Jeep|Bicycle";
- vehicles = vehicles.split("|");
- vehicles = vehicles.sort();
- vehicles = vehicles.join(",");
- console.log(vehicles);
Output
Bicycle, Bike, Car, Jeep
Approach 2
- var vehicles = "Bike|Car|Jeep|Bicycle";
- vehicles = vehicles.split('|').sort().join(',');
- console.log(vehicles);
Output
Bicycle, Bike, Car, Jeep
Rajib Das GuptaPosted Jun 7, 2016, 5:48 AM
Nice one.
Vignesh ManiPosted May 9, 2016, 6:14 PM
Good one
Kuppurasu NagarajPosted May 9, 2016, 11:59 AM
Nice Sharing..
Debasis SahaPosted May 9, 2016, 8:39 AM
Good One..