Possible Duplicate:
What questions should a JavaScript programmer be able to answer? [1]
I was going through Questions every good .Net developer should be able to answer [2] 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.
What's the difference between:
function foo() {
var i = 3;
...
}
and:
function foo() {
i = 3;
...
}
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
i
exists in any scope, its created in the local scope? - Plan B
i=3;
can be delete
-ed while those with var i=3;
cannot. - KennyTM
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
What is the difference between == and === ?
===
. - Dykam
What is a closure?
What is a prototype?
Why would you do this?
(function() {
// Do Stuff
})();
function() { /* do stuff */ }
- DisgruntledGoat
var f = function() {...}();
and var f = (function() {...})();
. Both create an anonymous function. - Tim Down
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
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');
}
}
foo
before any code is run in that scope. You can't do it in the second case. - Chetan Sastry
bar = function foo() { ... }
? - Ian Clelland
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.
this
to a specific meaning regardless of context? Closures and binding are good topics for interview questions. - Elf Sternberg
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 10 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.
console.log
;) - Daniel Vandersluis
alert()
but in case someone is trying out the code, it becomes incredibly annoying having to dismiss 10 alerts one by one. - Chetan Sastry
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
Not in any particular order..
Some other Good-to-knows:
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?
undefined
in the first place. - Tim Down
undefined
as a comparison value. - NickC
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
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
undefined
the following object: {foo: undefined, bar: undefined}
? - Rene Saarsoo
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. - NickC
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
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.
What are common security exploits available using or against JavaScript execution?
For web-based JS: Explain event bubbling.
In what ways is JavaScript object oriented, and in what ways is it not?
What is prototype? (not the framework)
Is it possible to overload functions?
Based on some misconceptions encountered on Stack Overflow:
What does delete
do? When should variables be set to null
?
what is hoisting and what are its implications?
http://bustingseams.blogspot.com/2009/08/another-javascript-pitfall-hoisting.html
Nasty ones:
Use local variables and methods inside the constructor.
[[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.
__proto__
is non-standard (developer.mozilla.org/en/Core_JavaScript_1.5_Reference/…). - KennyTM
Explain the concept of cross-domain scripting and why it's significant.
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?
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
What will happen when Javascript is disabled in client browser? ( graceful degradation principle )
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
What is the fastest method to send function output to an HTML page?
Does the order of <script>
tags matter?
<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
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.
Nobody mentioned so far Ajax techniques like Comet or JsonP, or JSON itself...
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.
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)
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
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.
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.
How does prototypal inheritance work in JavaScript?
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.
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/
length
property, Array.prototype, and [] literals. - Breton
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. - NickC
Who is Douglas Crockford?