Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Longest word solution explanation
    This is a solution to the longest word challenge by aselbie. It looks pretty darn nifty but I can't wrap my head around it. Can someone please explain? How is it possible to invoke a method (using the period) without any object places in front of it? Why did he return the object at the beginning? Aren't you supposed to return the object after you've done stuff to it?
    thetrystero asked this question on 5/15/14 | javascript, longest, word
    Answers
  • +
  • 3
  • -
  • Hi, the sen right there is the object. He put the methods on a new line just to make it look beautiful and easy to read. As long as there is no semicolon that separates the new line, it is still considered one line of code. Basically, what he did is actually this: To display code include the following tags:
    // just returning the value of match of sen with a regexp, which becomes an array, 
    // sort that array from the longest to the shortest, and then pull out the value of the beginning of that array
    
    return sen.match(/[\w]+/g).sort(function(a, b){return b.length - a.length}).shift();
    
  • +
  • 0
  • -
  • This is called method chaining, basically instead of writing everything out you do it all together. http://schier.co/post/method-chaining-in-javascript
  • +
  • 0
  • -
  • Strings have methods. He returned the result of those methods, he could have saved the result of those methods in a variable, and then returned the variable if he wanted.
    Login to write an answer