3 ms·
Because the candidate couldn't write a JavaScript function that allows chaining method calls on its result... along the lines of myFunction().setAttr('a').setAn
by bzalasky 11y ago
Because the candidate couldn't write a JavaScript function that allows chaining method calls on its result... along the lines of myFunction().setAttr('a').setAnotherAttr('b').toString(). In my experience, candidates either tackle this in 5-10 minutes, get close and finish with some hints in 20-30 minutes, or have no clue.
If it goes well (first scenario), I like to spend the rest of the interview pairing on a task like writing a parse method for a Backbone model that needs to transform a response for a charting library or something like that with Underscore/Lodash.
One time, a candidate started checking emails on his phone during an on-site interview. That candidate wasn't hired.
- jhildings 11y agoOut of curiosity, what is the things you need to do to make that possible?
- tienthanh8490 11y agoYou just need to "return this;" for the methods whose result need to be chained. Example: var a = function(x){ this.x = x+1; return this; } var b = function(){ this.x *= 2; return this.x; } a(3).b(); //result = 8
- bzalasky 11y agoSomething along the lines of this: function myFunction() { var a, b, func; func = function () { return { attrA: function (attr) { a = attr; return this; }, attrB: function (attr) { b = attr; return this; }, toString: function () { console.log([a, b].join(' ')); return this; } } } return func(); } This allows us to call myFunction multiple times, set attributes (imagine it were createPerson instead, with a name, age, etc...) and not run into problems with state being shared. I like this question because it covers closures, this, objects and functions. It also doesn't qualify as a brain teaser, IMO.
- fragmede 11y ago> It also doesn't qualify as a brain teaser, IMO. That's debatable. It requires a piece of unusual thinking ('return this'), and a bit of magic (knowing about the 'this' magic variable), but once you've seen it, the answer's obvious, and it's pretty easy to replicate everywhere.
- bzalasky 11y agoUnderstanding 'this' is foundational when it comes to understanding JavaScript, IMO. So, I don't think it's that unusual. Out of curiosity, what's another question that demonstrates a solid understanding of JavaScript as a language?
- fragmede 11y agoYeah, but returning 'this' to let you chain things like that? Definitely a trick. Not as obscure as Duff's device, but a trick, nonetheless.