views:

2734

answers:

37

I was going through Questions every good .Net developer should be able to answer and was highly impressed with the content and approach of this question and so in the same spirit, I am asking this question for JavaScript Developer.

What questions do you think should a good JavaScript programmer be able to respond to?

EDIT : I am marking this question as community wiki as it is not user specific and it aims to serve programming community at large.

Looking forward for some amazing responses.

NOTE : Please answer questions too as suggested in the comments so that people could learn something new too regarding the language.

+26  A: 

What is a closure?

Darko Z
+1. If you've had to deal with closure (beyond it automagically happening for you) then you've gone beyond the basics. Or had to debug memory leaks in IE ;)
Parrots
Terminology questions have a downside. It's entirely possible for someone to be a very good JS developer and understand the behavior but not know the term. Generally it's better to to use a code sample and ask for an explanation of what's happening in the code sample or point out problem points or possible improvements.
Sam
Yes, testing for whether someone knows the vocabulary is potentially misleading. Maybe ask a question for which the correct answer involves creating a closure? Like: "How do you use setTimeout() to call a method on an object?"
Mark Bessey
So, what's the correct answer? As far as I understand, a closure is a pointer to a function that persists after its parent function clears memory.
Plan B
A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression). via http://www.jibbering.com/faq/faq_notes/closures.html
markb
I think it's completely reasonable to expect a javascript developer to know the terminology. That's what makes it possible to work in a team environment.
Breton
Pointless question that tests nothing much. In my experience, there's plenty of people bandying the term around without knowing what it means (a lot of people seem to think it's an anonymous function), and it doesn't really matter. Understanding what code is doing is more important.
Tim Down
What are the chances someone thoroughly understands this concept, but hasn't read enough literature about JS to know the terminology?
Alex JL
If you don't know the terminology then you would accidentally be using closures in which case you wouldn't really understand them as they aren't an obvious feature of the language.
Darko Z
+29  A: 

What is the difference between the == operator and the === operator.

Mathieu Pagé
This is what I ask all the "Javascript Experts" I interview. Nobody has answered it correctly yet.
jeffamaphone
@jeffamaphone: Yet Douglas Crockford would argue that this distinction is critically important.
Jim G.
@jeffamaphone: Are you serious? *Nobody* understood comparing values to values and types? Wow. I'm glad I don't have to give interviews anymore :)
Jonathan Sampson
@Jonathan: I think the problem is not that they don't understand. It's simply that they don't know the difference. Actually the difference is pretty easy to understand, yet some programmer don't even know there is a === operator.
Mathieu Pagé
this is a general programming question for all C derived languages, not specifically for Javascript.
Elzo Valugi
Not really, this is a question for all dynamic OO C derived languages. Static languages don't have a `===`.
Dykam
it's a good question -- i ask this for php developers, too and a lot of people fail.
harald
Nobody that I've interviewed. To be fair, based on the job we're trying to fill, it's not really a good sampling.
jeffamaphone
I dont know ===, could it be explained?
Shawn Mclean
when == is used with two different types as operands, javascript will try to cast the operands to match. so '5' == 5 //true. === on the other hand will return false always, if the types of the operands are different.
Breton
I knew this an I can't write javascript, and can barely read C or its derived programs.
Iuvat
+2  A: 

What is prototype? (not the framework)

Jonathan Sampson
If it's not the framework it shouldn't be capitalized
Triptych
Syntactically, no. But I'm not writing syntax, Triptych. I was referring to it as a thing proper :)
Jonathan Sampson
+21  A: 

What is a prototype?

Jimmy
The prototype object of JavaScript, introduced starting in JavaScript 1.1, is a prebuilt object that simplifies the process of adding custom properties/ methods to all instances of an object. http://www.javascriptkit.com/javatutors/proto.shtml
Ben Aston
+2  A: 

Is it possible to overload functions?

gmcalab
Depends on the definition of overloading. You can easily emulate it but I don't think it actaully counts. (Have a function behave differently based on the contents of 'arguments')
Raynos
The answer is NO.
gmcalab
+2  A: 

For web-based JS: Explain event bubbling.

Erik
Nitpick: that's a DOM thing, not a JavaScript-the-language thing.
Crescent Fresh
+1 Nevertheless JS is bread for frontend developers and they should know things about Event model.
Elzo Valugi
+5  A: 

What are common security exploits available using or against JavaScript execution?

+2  A: 

Nasty ones:

  • How to make your function (or property) private ?

Use local variables and methods inside the constructor.

  • What is the use of [[Prototype]] of an object?

The [[Prototype]] of an object can be accessed via Object.getPrototypeOf(object) (ECMAScript 5+, JavaScript 1.9+) or object.__proto__ (JavaScript-only). The [[Prototype]] is the prototype property of the object's class or constructor function. It can be used to find out what properties and methods the object inherits from its superclass.

Kartoch
`__proto__` is non-standard (https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/Proto).
KennyTM
There's no concept of **private members** in Javascript. It is a concept from class-based object oriented languages, which Javascript is not. You can merely simulate that by the use of closures and local variables.
Bruno Reis
@Bruno: it's why this question is dangerous and ambiguous: it depends of the point of view of the developer ("simulate" VS language support)...
Kartoch
+33  A: 

What's the difference between:

function foo() {
   var i = 3;
   ...
}

and:

function foo() {
   i = 3;
   ...
}
jeffamaphone
Excellent question, but I would also elaborate a bit and ask what is the result of that difference.
I would actually like to know what the answer is :)
Plan B
What is the difference??
JP
The first *declares* a variable `i` in the *local* function scope, then set it to 3. The second searches for an `i` in all accessible scopes (including the global scope) and set it to 3.
KennyTM
@KennyTM So, in the second function, if no variable `i` exists in any scope, its created in the local scope?
Plan B
@Plan: Yes. Moreover, variables created with `i=3;` can be `delete`-ed while those with `var i=3;` cannot.
KennyTM
Someone at Microsoft actually introduced a bug in the ASP.NET javascript libraries related to this that wasn't fixed until .NET Framework 3.5 SP1. See http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=260892 and http://www.codeproject.com/KB/aspnet/pendingcallbacks.aspx for the juicy details.
Chris Shouts
@Plan B: No, if *i* is not found in any enclosing scope, it is created in the _global_ scope.
Ian Clelland
@Ian Clelland: Interesting, thanks for the clarification.
Plan B
@Plan B, @Ian Clelland: Pretty much. If no property called `i` is found on any object on the scope chain, a property called `i` is created on the global object, which is why it can be deleted while variables created with var cannot.
Tim Down
A: 

What is the fastest method to send function output to an HTML page?

@Daniel, in what way is your question relevant? Austin asked the fastest, he didn't mention the best. If you want you can ask your own "what is the best method to send blah blah blah" question.
Bruno Reis
A: 

What JavaScript Libraries / Frameworks have you used?

At this point all experts should be familiar with one of jQuery, script.aculo.us, or similar libraries.

jeffamaphone
if the job requires this, it sure is good to know these frameworks -- however: i wouldn't call someone a good javascript programmer, just because he has worked with this frameworks. the opposite is sometimes true, because some of the even famouse frameworks introduce bad practice ...
harald
It's very common for developers to have zero choice in frameworks they've used in production apps. Good developers that have been unable to use them in production will still have done research and hopefully played with them, but it's not great to discount a developer that never used any libraries in a project when it may be out of their control.
Sam
Good developers are familiar with, or have used frameworks. Bad developers might have used frameworks. Therefore, a developer who hasn't used a framework is bad.
Breton
@Breton: Uh-huh. Why is it necessary for a good developer to be familiar with the big JavaScript libraries?
Tim Down
The same reason it's necessary for a good taxi driver to know the major routes of their city, the hotels, etc. Same reason you'd expect a good furniture maker to know about the various powertools that are available. The same reason it's necessary for a great musician to be familiar with a wide range of genres, or for a painter to know how to use a stencil. That is, not because they expect to use them all the time, but that you expect an expert in a particular field to actually know about, and have some familiarity with the tools and techniques that exist in that field.
Breton
@Breton: I think you do have a point, so long as your idea of familiarity includes the idea of assessing the major libraries and deciding not to use them.
Tim Down
under appropriate circumstances yes. But not deciding to not use a framework for no reason at all, or because that's what "real men" do.
Breton
@breton: interesting point of view, really ... i don't agree though, because using a framework does not tell you anything about the skills a developer has on the programming language itself. for example: i interviewed php developers, they knew a lot of stuff about symfony and zend framework but failed with essential features of the language itself -- on the other hand i had people with very good knowledge of the language itself, but less knowledge of frameworks -- so: who would you think would be the better choice?
harald
If you're an expert in JavaScript, you should have, by now, worked with at least one, or at least independently assessed one and be able to talk about the pros and cons of using it vs not using it vs using a different one. Developers, whatever their area of expertise, who don't pursue technology outside of what is required of them at work, are not the ones I want to hire.
jeffamaphone
@Breton, would you require those taxi drivers to know to drive a 20 meter limousine ? because that is what you are comparing ...
Gaby
I think you broke the analogy.
Breton
+1  A: 

Does the order of <script> tags matter?

Anurag
I don't understand the question. Are you asking whether it matters in which order the bodies appear, or is there something special about different tags that I'm not aware of. If it is as simple as which order the bodies (which define javascript behavior) appear in, then the order affects the loading time. If <scripts> appear before html text, they can slow down the loading of the html. Is that what you meant?
PanCrit
@Pan, I meant if there are multiple `<script>` tags, then the order in which they appear matters. If there are two `<script>` tags and the one appearing second has a dependency on the first one, then things may break.
Anurag
+18  A: 

What is the difference between

function foo() { ... }

and

foo = function() { ... }

?

(The former defines a function with name foo, the latter defines an anonymous function and assign it into the variable foo.)

(Took the liberty of adding content)

This function will throw error when called (inner is not defined)

function outer() {
    inner();

    //bunch'o'code

    var inner = function() {
        alert('inner');
    }
}

This will not:

function outer() {
    inner();

    //bunch'o'code

    function inner() {
        alert('inner');
    }
}
KennyTM
Is there any functional difference? That is, is there any difference in the way that blocks foo1 and foo2 can and can't be used?
BlueRaja - Danny Pflughoeft
@BlueRaja: There is an important difference. You can call the function as defined in the first case even before it is defined. It is parsed and assigned to `foo` before any code is run in that scope. You can't do it in the second case.
Chetan Sastry
For bonus points, what happens if you say `bar = function foo() { ... }` ?
Ian Clelland
@Ian: bar is visible but undefined, foo isn't visible at all.
Jimmy
@BlueRaja: when "var bar = function foo() { ... }" is declared, one difference is: inside of the function, foo is defined. Also, in non-IE browsers, bar.name == 'foo'. (IE doesn't define a name attribute on functions)
Jimmy
As always, I'll provide a link to kangax's (http://stackoverflow.com/users/130652/kangax) excellent article on this subject: http://perfectionkills.com/named-function-expressions-demystified/
Tim Down
+1 Of all the answers, this one seems good/non-trivial
Aiden Bell
+3  A: 

In what ways is JavaScript object oriented, and in what ways is it not?

Sam
+1 this is pretty complex, maybe too complex
Elzo Valugi
Yes, it's complicated. It depends on if you're looking for a JS developer that is just doing validation and simple DOM manipulation or if you're truly building a full app in JS.
Sam
Define "Object Oriented" first, dumbo.
Breton
@Brenton: End of interview, dumbo. :-)
Sam
so you'd base an interview question on such a poorly defined concept, and dismiss the interviewee for asking for a definition? Honestly, you people take "Object Oriented" for granted, and never stop to notice that it means something completely different in every language.
Breton
@Brenton, that's exactly the point of the question. Most people don't think about JavaScript as object oriented, so when asked in what way is JS OO and what way isn't it, they have to think about what OO means, what are all the different aspects of an OO language, and which ones do or do not apply to JS.
Sam
I know a lot about JavaScript and don't know whether I could answer the question, mostly because I don't really care. I know how the language works in some detail and how to code in it and discussing how it does or does not conform to a nebulous abstract concept doesn't interest me much, as I don't think it will help me improve. What kind of answer would you hope to get?
Tim Down
@Sam, I wouldn't be interested in the job anyway. A boss who's interested in the answer to such a silly question is a gigantic red flag for trouble. And by the way, my name isn't brenton.
Breton
@Brenton, that's good, an interview is a two-way communication and both the employer has to decide if they like the applicant and the applicant decides if they like the employer. Funny thing is, we has a job application from a Brenton just a few weeks ago. Not you, his last name started with a K.
Sam
Rather than focus on the name-calling, I thought it might be valuable to attempt to answer the question. If you follow Crockford's JS:TGP, javascript has encapsulation, inheritance (via prototypes), polymorphism. If you use the language the way it is normally presented, you lose the encapsulation, but still have the rest.
PanCrit
+6  A: 

Based on the frequently asked questions on Stackoverflow:

1 . What does the following code do? Why? (Assume you have firebug or some other debugging tool that declares console )

var i;
for(i=0; i<10; i++) {
    setTimeout(function(){console.log(i);}, 1000);
}

2 . What is wrong (or can go wrong) with this code?

var arr = [1,2,3,4],
    sqrArr = [],
    i;
//calculate squares of the numbers in array
for(i in arr) {
    sqrArr.push(arr[i] * arr[i]);
}

3 . Which code runs faster and why?

var i;
for(i=0; i<100; i++) {
    jQuery("#myDiv").append("<span>" + i + "</span>");
}

var i, markup = "";
for (i=0; i<100; i++) {
    markup += "<span>" + i + "</span>";
}
jQuery("#myDiv").append(markup);


var i, markup = "";
for (i=0; i<100; i++) {
    markup += "<span>" + i + "</span>";
}
jQuery("#myDiv").append("<div>" + markup + "</div>"); //assuming the extra div is okay.

[Edit]: Posting the answers.

1: It will log 11 ten times. The closure passed to setTimeout holds a live reference to the variable i of the outer scope. It will log the value of i when it is actually run, not when the closure is created. In this case, hopefully the loop completes itself before any of the console.log is called (1000msec ought to be enough!).

2: for..in is really meant to enumerate (non built-in) properties of an object. Used on an array, it seems to work because Arrays support enumeration on their indices too. However, if you add any property to Array.prototype (such as popular libraries like Prototype and Dojo do), they will be included in the enumeration as well. It is a bad idea to base your code on the assumption that someone else doesn't mess with Array.prototype.

Ex.

//Someplace else in your page
Array.prototype.blah = function() {alert(this.length);}

var a = [1,2,3], i;
for (i in a){ 
    console.log(i);
}

//output
1
2
3
blah

3: The first snippet is the slowest because it is doing both a document.getElementById and an append inside the loop. That's just plain wrong.

The second snippet is better because it is doing the DOM manipulation once. But it seems jQuery does a lot of work for each parent level element in the markup, appending each of them to a documentFragment and then to DOM finally.

The third snippet which only has 1 parent element in the markup is the fastest.

Chetan Sastry
#1 will cause an error if not using firebug or something similar that defines `console.log` ;)
Daniel Vandersluis
Of course.. It is implied :) I first wrote `alert()` but in case someone is trying out the code, it becomes incredibly annoying having to dismiss 10 alerts one by one.
Chetan Sastry
#2: Are you just looking for the problem with possible extra members on Array.prototype? Or is the fact that i is not a local variable a deliberate issue as well?
Ian Clelland
@Ian: Extra members in Array.prototype. Corrected the error in question.
Chetan Sastry
#3: Which one runs faster between 2 and 3? Is there any reason a div tag would speed up the appending?
Vanwaril
#2: I thought `for(i in arr)` would give `1,2,3,4` for `i` and therefore `arr[4]*arr[4]` would be invalid. If not, can you explain?
DisgruntledGoat
#3: My random thinking: The third one would run quickest because it's essentially only inserting one element into the DOM tree - the div. The spans are not technically "inserted" since they are already children of the div and it's all done in one block. Is that right?
DisgruntledGoat
A: 

Who is Douglas Crockford?

Upper Stage
Knowing the answer makes a person any better at JavaScript?
Blixt
@Blixt, knowing his work makes a person better at Javascript.
Bruno Reis
Knowing the person indicates that the applicant reads about Javascript, which itself probably correlates to being a better programmer.
Triptych
When I read this question, I imagined asking a prospective hire these questions - perhaps in an interview. If a candidate cannot answer a question like "Who is DC?", he or she may not be reading current literature and may not be polishing the tools of his or her craft. imho
Upper Stage
Personally, I consider myself to be proficient with JavaScript. Despite this, I can't tell you much about Douglas Crockford. I've read many of his articles on the internet, but I haven't realized it was he who wrote them until later, because they were just part of all the hundreds of articles I've read on the internet over the years. I can definitely see the possibility of a very good JavaScript programmer barely knowing who Douglas Crockford is at all. Also, how do you answer the question in a way that indicates you know what he writes? Does "He's a well known JS guru" tell you anything?
Blixt
-1 because I think this is a terrible question. Long ago I used to ask interview questions like "What's your favorite book about programming?" (which btw is a *much* better interview question than "Who is such-and-such?") but I stopped doing it because it turns out what a person reads is not strongly correlated with getting things done. Even if reading a particular blog makes you a better programmer, it is not what makes most good programmers good (so you will get lots of false negatives) and it cannot make bad programmers good (so you will get a lot of false positives).
Jason Orendorff
Of course, you're entitled to your opinion. I find questions like this tell me whether a candidate is reading articles, reading blogs, participating in SO, staying current, etc. I don't care whether a candidate knows the names of DC's children; rather have you heard of him at all. I liken this to resumes where Java is misspelled (JAVA); you're not reading enough if don't know how to spell Java. And I think if you are studying JS, you might remember a author or two.
Upper Stage
**You** : Who is Douglas Crockford?**Interviewee** : That's my uncle. Works on his farm in mid-west.**You** : No, not your uncle. I mean the Douglas Crockford that's famous for popularizing Javascript.**Interviewee** : Oh that Douglas Crockford. Yeah, he's done some terrific stuff with Javascript. Great guy.
Anurag
It's just not important, and will tell you nothing about whether someone can code. -1.
Tim Down
To all the downvoters: The fact is, great Javascript programmers will at least be aware of Douglas Crockford. The OP didn't say it's a make-or-break question, but, well, I've worked with good JS programmers and not-so-good JS programmers, and I bet this question would have been a good filter. It's worth asking, but perhaps not deciding on.
Triptych
Knowing about Douglas Crockford might be correlated with JS ability. But there are many better, more direct questions you can ask. Once you've done asked some of those and you have a good idea of what a candidate can do, this question won't affect your hire/no-hire decision either way, right? So it is useless.
Jason Orendorff
Absolutely horrible question. I've been working as JavaScript developer/architect and performance optimizer for 10 years now, and I wouldn't be able to answer that because, first of all, I have a horrible memory for names, second - because when I read articles on the Internet, I really could care less who wrote them, only how good they are. More than that, if somebody would've asked me this question on the interview and insist on getting the answer, I wouldn't want to work for/with this person. -1
Ilya Volodin
+1  A: 

Explain the concept of cross-domain scripting and why it's significant.

Plan B
It is not purely Javascript, but more a browser and web-security related question.
Bruno Reis
+6  A: 

Not in any particular order..

  1. The difference between jQuery and JavaScript (seems flaky nowadays with some people...)
  2. How to use prototypal inheritance. Even if one knows what a prototype is, they may not know how to actually use it in any useful way.
  3. Debugging tools. They should know of Firebug, using breakpoints, even better if they know of other tools like WebKit nightlies' more unique features (DOM event listeners, etc.)
  4. How to write cross-browser compatible code without browser sniffing (using feature detection)
  5. How to write code that uses progressive enhancement techniques

Some other Good-to-knows:

  1. Application/code architecture. Surprisingly many JS coders don't actually know that much about writing good, readable, maintainable code.
  2. New HTML5 APIs like localStorage, Web Database, Canvas
  3. Tools like JSLint, YUI Compressor, Closure Compiler
Jani Hartikainen
Your comment on the first #1 scares me...
Renesis
+3  A: 

What is the purpose of

//<![CDATA[

//]]> 

http://en.wikipedia.org/wiki/CDATA

markb
I assume the intent here is to have a client render something differently depending on whether JavaScript is enabled or disabled. Isn't there a better way to do this?
Mark Bessey
This is an X(HT)?ML thing... not really applicable to the JS language.
J-P
IIRC it's the hideous code you have to add to every script block in order to validate your XHTML (and maybe HTML too). Pointless if you ask me.
DisgruntledGoat
@DisgruntledGoat: Especially since IE doesn't handle XHTML anyway. You don't need it for HTML.
Tim Down
+2  A: 

Based on some misconceptions encountered on Stack Overflow:

What does delete do? When should variables be set to null?

Christoph
The delete operator deletes a property of an object, or an element at a specified index in an array. https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator
Ben Aston
+19  A: 
  1. What is going on here?
  2. Why would you do this?

    (function() {           
        // Do Stuff        
    })();
    
ChaosPandion
I'd like to also know this too, I had to do this in some google map event.
Shawn Mclean
It's to provide scope for local variables, right?
hmp
That code creates an anonymous function and executes it. You would use it to avoid naming conflicts in a javascript library etc (check out jQuery for a good example of applying this technique)
Chris T
An extension of local variables: I often use this to create private variables for a constructor and its prototype methods.
Shtééf
I'd like to know, what's the deal with the extra parentheses? i.e. as opposed to plainly `function() { /* do stuff */ }`
DisgruntledGoat
@DisgruntledGoat - Without the parentheses your are defining a function. With the parentheses you are defining an anonymous function.
ChaosPandion
@ChaosPandion: not true. Without the parentheses you have a syntax error, since a function expression may not be used on its own as a statement. As part of an assignment, a function expression does not require the parentheses: the following are functionally identical: `var f = function() {...}();` and `var f = (function() {...})();`. Both create an anonymous function.
Tim Down
@Tim - Caught in my own web of lies!
ChaosPandion
@Tim Down, @ChaosPandion: I think the original assertion is correct: if the `function(){...}` is not wrapped in parentheses, the parser thinks it's a statement, and so won't accept the `()` at the end. Preceding it with the first half of an assignment or wrapping it in parentheses both make the parser interpret it as an expression rather than a statement. I think.
intuited
intuited: Isn't that what I said?
Tim Down
+1  A: 
  • What does it mean to give an anonymous function a name?

  • How to accomplish that?

  • In which situation could this be interesting?

  • In a situation that would require such capability, which language construct you could use to avoid naming an anonymous function?

Bruno Reis
I like this question, but I think it's not entirely clear. Obviously a function with a name is by definition not anonymous. However, it turns out that people use the term "anonymous function" when what they really mean something else, like "locally-scoped function object".
Mark Bessey
Actually you can give an anonymous function a name, and it is still anonymous (?). Like this: `var f = function func() { ... }`. `function func() { ... }` in this context is a function expression, a lambda function, an anonymous function. It happens that inside the scope of this anonymous function, it is represented by the identifier `func`.
Bruno Reis
For a complete, real example, take a look at this answer I gave to another question: http://stackoverflow.com/questions/1750168/use-recursion-instead-of-eval/1750295#1750295
Bruno Reis
A: 

I must admit that syntactical details, is not as important to me as a good and thorough understanding of the core concepts behind programming, even for script users. Questions like how to write a function, sort an array, etc. in language A, B or P is something every good developer should be able to find out, not necessarily know by hand. The thing is, if you are good at developing in language A then you are most likely able to easily adapt to language B or any other.

The thing interesting to know, is then not the language specific syntactical things, but the concepts that are used in programming in general. However since this question bases specifically on JavaScript I'd say it would be important to find out how the developer would solve a given solution. Give them a task to solve something like a calendar function, and look how they solve it. Are they adding extra functionality, are they making it very basic and core functionality only. Is it cross-browser compatible? etc.

TommyA
+14  A: 

How does the this keyword work?

answer: this is late bound to some object before the invoked function is executed. Which object it is bound to depends on how the function was invoked. There are 5 different ways to invoke a function, each binds this to a different sort of thing.

This can lead to a pitfall where if you have a constructor, written with the expectation that this will be bound to some new object, and you accidentally call it without the new keyword, this will instead get bound to the global object, and the constructor will pollute the global namespace.

Luca Matteis
What are these 5 different ways? and what does each case do?
Raynos
+1  A: 

What will happen when Javascript is disabled in client browser? ( graceful degradation principle )

Elzo Valugi
A: 

Nobody mentioned so far Ajax techniques like Comet or JsonP, or JSON itself...

Elzo Valugi
+4  A: 

What is the difference between undefined and null? When is a variable one or the other and why might you need to know the difference?

Renesis
... and why it is better not to use `undefined` in the first place.
Tim Down
What do you mean to "not use"? If you are talking about assignment, you're right, but it's often useful (or even necessary) to use `undefined` as a comparison value.
Renesis
Using `undefined` is always unnecessary and carries risk. While `null` is a reserved word and the value of `null` cannot be changed by JavaScript code, `undefined` is a property of the global object whose value may be changed accidentally. For example: `if (undefined = someVar) {...}` will silently change the value of `undefined` and break all other comparisons with `undefined` in your program (unless `someVar` is in fact undefined). It's safer to use a `typeof` check: `if (typeof someVar == "undefined") {...}`.
Tim Down
On the other hand: `alert` is a property of the global object, whose value may be changed accidentally - should we therefore conclude, that we shouldn't use `alert` in our programs?
Rene Saarsoo
Plus, how would you create without using `undefined` the following object: `{foo: undefined, bar: undefined}` ?
Rene Saarsoo
@Rene Saarsoo, foo and bar will be `undefined` if you don't assign them at all, so as far as I know your code is no different than `{}`. In my case, I've sometimes needed to use `undefined` in a ternary operator in a method call to avoid two separate lines calling the same method with different numbers of parameters.
Renesis
@Renesis: there is a difference: for `var a = {foo: undefined}`, "foo" would show up in a `for...in` loop over that object, and `foo in a` would return true, neither of which would be the case for `var a = {}`
Tim Down
A: 

In what way can the following code be simplified to a single statement, that is not possible in Java, and preserves the exact operational logic (getB() will always be called once but getC() will not) (Hint, it does not involve a ternary operator.)

var a;
var b = getB();
if (b) {
    a = b;
} else {
    a = getC();
}

[Edit] Answer:

var a = getB() || getC();

In JS the || operator does not create a boolean but passes assignment on to the next part of the statement if the current part ! evaluates to true.

Renesis
+1  A: 

It seems odd that the OP was about javascript, yet nearly all suggestions are about ECMAScript and almost none about javascript itself (i.e. the interaction between ECMAScript implementations and DOMs).

If a concise question is required that tests an individual's understanding of ECMAScript, the following post by Richard Cornford on the comp.lang.javascript news group might help:

http://groups.google.com.au/group/comp.lang.javascript/msg/28559592272d4e54?hl=en >

The most revealing part of the test is not necessarily whether the answer is correct or not, but what the answer reveals about a person's understanding of the language.

-- Rob

RobG
Brilliant thread I'd not seen before since it predates my time on clj. And nice to see some of the regulars in slightly more humble mode. Thanks.
Tim Down
+1  A: 

This is a fun one:

Why does new Boolean(false) || true return false?

(Because Boolean is an Object, and in the logical expression Object is converted to true, as defined by ToBoolean in the ECMA 262 spec)

Andreas Jansson
Strictly speaking `new Boolean(false) || true` does not evaulate to `false`, and in fact `!!(new Boolean(false) || true)` evaluates to `true`, for the same reason you mentioned.
Tim Down
A: 

How would you create an associative array in javascript?

trick question, javascript doesn't have associative arrays, but a lot of inexperienced programmers coming from PHP get misled into thinking it does.

http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/

Breton
It would be more productive to just point out that JS objects are like PHP associative arrays, that the [] array access can still be used, and that the real Array is reserved for sequential/numeric arrays.
Renesis
Except that two out of those three things aren't really true.
Breton
I'm not sure I see how, unless you are being pedantic about it, which is really pointless unless you are trying to keep understanding JS out of reach of "inexperience programmers". PHP associative arrays store data by key. So do JS objects. [] array access can be used for keys on objects in JS. And Array is reserved for sequential/numeric arrays.
Renesis
"PHP associative arrays store data by key. So do JS objects" true, but that is where the similarities end. PHP associative arrays do not have a prototype chain, or built in methods, and are otherwise not at all "like PHP associative arrays". "Array" is not "reserved" for sequential/numeric arrays. That is a meaningless statement. You can have sequential and numeric property names on any sort of object, so that's certainly not what makes Array special. The only things that differentiate a js array from a normal object is the magic `length` property, Array.prototype, and [] literals.
Breton
Beginners are not served by being given incorrect or misleading information.
Breton
I don't see why you are refusing to try to understand the sentence "Array is reserved for sequential/numeric arrays" since that is basically pulled from the link *you* put up. I'm not saying it may only be used that way, I'm saying it *should* be used that way. As for what serves beginners, a beginner does not need to understand all the ins and outs of the complexities of PHP objects. Those things come with time. You need to give them somewhere to start, and a comparison with PHP associative arrays can actually be quite helpful - even by pointing out the differences, as you have.
Renesis
@Renesis I had another look at my link I could not find anything like what you're talking about. The closest thing I could find is "JavaScript arrays (which are meant to be numeric)", but that's vastly different than arrays being "Reserved", which has the connotations that numeric properties are the only thing that can be used with arrays, or that you can only use numeric properties on arrays. This is simply and obviously not true, and in fact is part of what leads to the confusion. If for example, trying to assign a non numeric property to an array threw an error, we wouldn't be arguing.
Breton
Sorry that all the words I chose had all the wrong connotations to you. I certainly know that numeric properties are not the only thing you can set on an Array, so that's simply not what I meant. As the article points out, even String can have keyed properties, since all JS classes extend Object.
Renesis
I'm sorry that you are disturbed by my awareness that words have meanings, and that which words you choose to put into a sentence effects its meaning.
Breton
@Renesis: You really need your wording to be precise in this kind of debate.
Tim Down
The point is, words can have different connotations to different people. Clearly that's the case here. My thought was that with the context given it would be comprehensible.
Renesis
@Renesis the context of talking to a beginner that doesn't know anything about javascript? Words can have different connotations to different people, but I feel that "reserved", especially in a programming context, has a very specific and predictable meaning. Such as in the phrase "Javascript reserved words" means that you cannot use those words for any purpose other than what they were intended. Now if you were teaching javascript to a beginner, and you say on the one hand "these are reserved words", and then "Array is reserved for numbers" what conclusions do you think they'll draw?
Breton
Well you have a good point, teaching is always tricky because of the reasons you bring up, and I don't at all consider myself an expert teacher. However, my reasoning in this case is that I feel it might be better to let a beginner consider Array "reserved" than to get into the deeper reasons why keys still *technically* work. Speaking of reserved words, there are certain "reserved" words (`label` being one) that will still work in some browsers and throw mysterious errors in others. Maybe it's not technically considered "reserved", but we had this bug and it was hard to track down.
Renesis
I would say all objects in JS are associate arrays. The "trick" mentioned was a little confusing however, because I'm not familiar with associative arrays in PHP. I notice the article recommends that non-numeric keys should only be assigned to an Object, that it's wrong to assign them to an Array because it might confuse someone who uses for...in. I respectfully disagree in that I think using for...in to iterate the elements of an Array is what aught to be discouraged.
machine elf
+2  A: 

what is hoisting and what are its implications?

http://bustingseams.blogspot.com/2009/08/another-javascript-pitfall-hoisting.html

Breton
I'm not sure about this one. Here it really is possible and quite likely that someone may know that you can call a function earlier in the code than its declaration without knowing that it is called hoisting (which itself is a term that isn't used to describe the phenomenon in the ECMAScript spec).
Tim Down
@Tim Down I'm not fussed about the terminology on this one, but this is a key and very confusing part of how javascript code gets interpreted, which even experts get hung up on. It affects how you organize your source files, and which order they can be loaded in, and it effects the behavior of individual functions in subtle and confusing ways.
Breton
+1  A: 

There are 5 different ways of invoking a function. What are they, and how do they affect how this is bound?

new Func() //creates a new object that inherits from Func.prototype, and binds it to `this`

func() // binds `this` to the global object

myobject.func() // method invokation, binds `this` to myobject

func.call(anotherobject) //call invokation binds `this` to the first argument given to call

func.apply(anotherobject) // binds `this` in the same way as call invokation.
Breton
A: 

They should have a clear understanding of the unique way "this" works in JavaScript.

That was the trickiest thing for me when learning the language, and the thing that caused me the hardest to track down bugs.

Andrew Johnson
A: 
  1. Creating custom Javascript objects, associative arrays.
  2. What happens when you declare two variables with same name?
  3. When method has name which is a variable name, what will be the resulting scenario? Any errors?
pramodc84
A: 

This is not an interview question but taken from a test I've been giving to my students:

Are the objects created by PopUp1() and PopUp2() constructor functions identical (both by the interface they provide and how such objects are stored in memory)

function PopUp1(sText){
  this.text = sText;
  this.show = function () {
                  alert(this.text);
               };
}
function PopUp2(sText){
  this.text = sText;
}
PopUp2.prototype.show = function () {
                          alert(this.text);
                         };

And the explanation is - the two objects provide the same interface (both have a method show()). However, in the first example each object created by new PopUp1() has its own implementation of the show function (even though it is identical in each object), but the PopUp2 objects actually don't have their own implementation of show() function, it is inherited from the prototype.
To answer this question, the student must have at least some understanding of how prototypal inheritance works.

naivists
A: 

How does prototypal inheritance work in JavaScript?

AlexanderN