Vous êtes sur la page 1sur 15

One.

com has received a lot of responses to our job posting for a Dubai - Javascript
Developer. Since we have limited ressources we cannot interview everyone who has
applied for the job. This questionnaire is part of a pre-screening for a job interview.

Getting a reliable view of your skills is of utmost importance, hence you will be immediately
disqualified for the job, if we later discover that the online test does not match your own
knowledge. Therefore you have to complete the test on your own.

Javascript (40 questions)

How would you randomly pick an element from an array


named ​myNumbers​?
○ myRandomElement = myNumbers[Math.floor(Math.random() *
myNumbers.length)];
○ myRandomElement = myNumbers[Math.ceil(Math.random() *
myNumbers.length)];
○ myRandomElement = myNumbers[Math.random(myNumbers.length)];
○ myRandomElement = Math.random(myNumbers.length);

Which of the following is not a Javascript operator?


○ new
○ this
○ delete
○ typeof

A cookie is set using the below Javascript statement. When


will it expire?

document.cookie = "foo=bar;secure";

○ When the browser is closed.


○ When the user navigates away from the page that set the cookie.
○ Never.
○ In 2036.

What is Firebug?
○ A Javascript ajax/event/UI framework.
○ An add-on for Mozilla Firefox.
○ The plugin framework of Mozilla Firefox.
○ The Mozilla project's bug database.
Which of the following is not a popular Javascript
framework?
○ Ajaxian
○ Prototype
○ MooTools
○ Dojo

Which of the below can be used to perform an asynchronous


request to the web server?
○ XmlHTTPQuery
○ XMLHttpRequest
○ document.querySelectorAll
○ $.ajax
○ An iframe with an oncontentloaded callback.

What's computed by this code?

(function(n){return (n && n*arguments.callee(n-1)) || 1;})(10);

○ 10!
○ Nothing, it's an infinite loop.
○ 10 to the power of 10
○ 10!/10
○ The 10th Fibonacci number.

How do you remove a property ​prop​ from an object ​obj​?


○ obj['prop'] = null;
○ obj.prop = undefined;
○ delete obj.prop;
○ remove(obj['prop']);

Assuming ​a​ refers to a function, how would you execute ​a


after a delay of one second?
○ setInterval("a()", 1000000);
○ setTimeout(a, 1000);
○ window.sleep(1);a();
○ a.defer(100);
○ eval("a()", 10000);
○ delay({callback: a, milliseconds: 1000});
○ You cannot do that in Javascript.

What is JSON?
○ A safe subset of Javascript.
○ A lightweight data interchange format.
○ All of the above.
○ None of the above.

The below script has some troubles getting the numbers


right. What could be wrong?

var fruitSaladRecipe = "2 apples, papaya, coconut, 5 oranges, apple,


banana",
ingredients = fruitSaladRecipe.split(/,\s+/),
ingredientHash = {},
num = 0; // Total number of fruits
for (var i=0 ; i<ingredients.length ; i++) {
var ingredient = ingredients[i],
fruitType = ingredient.match(/(\w+)$/)[1].replace(/s$/, ""),
numPieces;
if (/^\d+/.test(ingredient)) {
var num = ingredient.match(/^(\d+)/)[1];
numPieces = parseInt(num, 10);
}else{
numPieces = 1;
}
if (/^(?:banana)$/.test(fruitType)) {
// Speaking of bananas, let's add some more! Those things are
delicious!
numPieces *= 2;
}
num += numPieces;
if (fruitType in ingredientHash) {
numPieces += ingredientHash[fruitType];
}
ingredientHash[fruitType] = numPieces;
}
var message = num + " fruit(s) in total:";
for (var ingredient in ingredientHash) {
if (ingredientHash.hasOwnProperty(ingredient)) {
message += " " + ingredientHash[ingredient] + " " + ingredient +
"(s)";
}
}
alert(message);

○ The total will be incremented twice for fruit types that have already been
encountered in the list.
○ The lack of block scope in Javascript causes the second ​var num
assignment to overwrite the first one.
○ The numbers are interpreted as binary because the p ​ arseInt​ function is
called with a wrong 'radix' parameter.
○ A for-in loop can only be used with arrays. The behavior is undefined
when used with objects.
○ An error in one of the regular expressions causes apples and oranges to
be considered the same fruit type.

What is the return value of ​setInterval​?


○ An object that make is possible to queue up messages/objects for the
next invocation of the function passed to ​setInterval​.
○ An ID that can be used with c​ learInterval​ to stop the interval.
○ An opaque object that can be used with c​ learTimeout​ to stop the
interval.
○ Whatever is returned from the first invocation of the function passed to
setInterval​.

Why doesn't the below code open an alert box with the text
"foo"?

function wrapInObject(value) {
return
{
value: value
};
}
alert(wrapInObject("foo").value);

○ Javascript's automatic semicolon insertion causes an undefined value to


be returned from ​wrapInObject​.
○ A variable cannot be used as a key in an object.
○ wrapInObject​ returns an object literal with a single "foo" key, not "value".
○ A function is only allowed to return a primitive value.

Why doesn't the below code open an alert box with the text
"foobar"?

var a = "foo",
b = a;
b += "bar";
alert(a);

○ When ​bar​ has been appended to ​b​, ​b​ and ​a​ don't refer to the same
value because strings are immutable in Javascript.
○ Because Javascript enforces referential integrity for primitive values.
○ Because there is a circular reference between the two String objects.
○ The += operator only works with numbers.

What does the function ​f​ do?

function f(a) {
return function(b) {
return a + b;
};
}

○ Given an integer ​a​ it returns an anonymous function that returns the sum
​ ​ and the supplied argument ​b​.
of a
○ Given a string a ​ ​ it returns an anonymous function that returns the
concatenation of a ​ ​ and the supplied argument b
​ ​.
○ All of the above.
○ None of the above.

Why doesn't this work as intended?


function makeNumberSequenceGenerator(nextValue) {
return function() {
return nextValue++;
};
}
alert(makeNumberSequenceGenerator(10).nextValue().nextValue());

○ nextValue​ cannot be referenced from the inner function.


○ nextValue​ cannot be incremented from the inner function, it is read-only.
○ nextValue​ is a property on the returned object, not a method.
○ The return value of the ​makeNumberSequenceGenerator​ function
doesn't have a ​nextValue​property/method.

Complete the return statement in the function below:

function isFalseBooleanValue(bool) {
// return...
}

○ return bool = false;


○ return bool == false;
○ return bool === false;
○ return bool ==== false;

What's accomplished by using this construct:

(function() {
for (var i=0 ; i<10 ; i++) {
alert(i);
}
})();

instead of just:

for (var i=0 ; i<10 ; i++) {


alert(i);
}

○ The global object isn't polluted by the variable ​i​.


○ The execution of the for loop will be delayed until the entire script has
run.
○ The loop will run in a security sandbox that cannot access the DOM.
○ Nothing, the two pieces of code are equivalent.

The below code is added to an existing website (in an


external Javascript file), causing some unexpected effects.
What's the problem?

window.onload = function() {
document.write("Hello, world!");
};

○ Wrong capitalization of ​onLoad​.


○ document.write​ overwrites the existing contents of the document if it is
run after ​window.onload​ has fired.
○ The w ​ indow​ object doesn't support an o ​ nload​ event, it should be set on
​ ocument​object.
the d
○ The o ​ nload​ handler must be set in the HTML, like this for instance:
<body onload="document.write('Hello world!');">

The below code doesn't work as expected. What could be


wrong?

for (var i=0 ; i<10 ; i++) {


var button = document.createElement("button");
button.onclick = function() {
alert("You clicked button number "+i);
};

document.body.appendChild(button).appendChild(document.createTextNod
e("Button "+i));
}

○ The variable ​i​ cannot be used in the onclick handler because it's defined
in an outer scope.
○ The variable i​ ​ will be shared among the event handlers because
Javascript doesn't have block scope.
○ Button tags are only allowed within a < ​ form>​.
○ Chaining a​ ppendChild​ calls is only supported in Internet Explorer.
The below code doesn't work as expected. What could be
wrong? (Assuming that elements with a class of 'button'
receive a suitable styling)

for (var i=0 ; i<10 ; i++) {


document.body.innerHTML += "<div class='button'
id='button"+i+"'></div>";
document.getElementById("button"+i).onclick = function() {
alert("You clicked button number "+this.id.replace(/^button/, ""));
};
}

○ Existing event handlers below ​document.body​ are lost when ​innerHTML


is overwritten.
○ document.getElementById​ cannot be used immediately after i​ nnerHTML
has been altered, s​ etTimeout​ must be used.
○ this.id​ cannot be used from within the event handler, causing a runtime
error when the click event is handled.
○ document.getElementById​ only works in Internet Explorer, the
document.all​ collection must be used.

How can this function be improved?

function removeLeadingAndTrailingWhitespaceFromString(str) {
return str.replace(/(^\s+)|(\s+$)/ig, "");
}

○ The ​g​ flag can be omitted from the regular expression.


○ The *​ ​ quantifier should be used instead of ​+​ to avoid unnecessary
replacements.
○ There's no need to use capturing parentheses in the regular expression
because the values aren't used.
○ All of the above.

What seems to be the problem with the below code?

function StateMachine(initialState) {
this.state = initialState || 'foo';
return {
transition: function() {
this.state = {foo:'bar', bar:'quux', quux:'foo'}[this.state];
return this;
}
};
}
var sm = new StateMachine();
alert(sm.transition().transition().state);

○ The ​transition()​ calls cannot be chained. Use


sm.transition();sm.transition();​ and then inspect ​sm.state​.
○ The initial t​ his.state​ assignment doesn't set the property on the object
that's returned from the constructor.
○ The n​ ew​ operator cannot be used when the constructor returns a
different object.
○ All of the above.

Why doesn't the below code work as expected? (Assuming


Javascript 1.6 support)

var isOdd = function(n) {return n&1;},


isDivisibleByThree = function(n) {return !(n%3);},
addOne = function(n) {return n+1;};
alert([1,2,3,4,5,6,7].map(addOne).filter(isOdd &&
isDivisibleByThree).length);

○ The ​isOdd​ test never gets called.


○ The ​isOdd​ test is wrong.
○ The i​ sDivisibleByThree​ test never gets called.
○ The i​ sDivisibleByThree​ test is wrong.

Why doesn't the below code alert "foobar" as expected?

function StringBuffer(initialStr) {
this.append(initialStr);
}
StringBuffer.prototype = {
items: [],
append: function(str) {
this.items[this.items.length] = str instanceof StringBuffer ?
str.toString() : str;
return this;
},
toString: function() {
return this.items.join("");
}
};
alert(new StringBuffer("foo").append(new StringBuffer("bar")).toString());

○ The ​items​ array is shared among all instances of ​StringBuffer​.


○ initialStr​ is appended to all instances of ​StringBuffer​ whenever the
toString​ method is called.
○ The a ​ ppend​ method returns the wrong object.
○ toString​ doesn't call the t​ oString​ method on each object in i​ tems​.

Rename f , a , and b to something more suitable:

function f(a, b) {
return function() {
return a.apply(b, arguments);
};
}

○ f:bindFunctionToScope, a:fn, b:scope


○ f:delayExecution, a:fn, b:milliseconds
○ f:applyFunctionToArray, a:array, b:fn
○ f:map, a:array, b:fn

Why doesn't the below function work as expected?

var isUndefinedOrNull = function(obj) {


return /^(?:undefined|null)$/.test(typeof obj);
};

○ undefined​ is a reserved word, not a type.


○ Regular expressions work on strings, not types.
○ It will return true for the empty string.
○ All of the above.
○ None of the above. Something else is wrong.
Why doesn't the following function work?

function printZeroToNinetyNine() {
for (var i = 0; i < 100; i += 1) {
setTimeout(function () {
console.log(i);
}, 0);
}
}

○ There is an off-by-one error.


○ The delay of zero in setTimeout means the inner function is never
called.
○ The variable `i` is not scoped to the inner function.
○ The function name is too long.
○ It is not possible to write a function in a for-loop.

What is the output of the following function?

function delayedPrint() {
for (var i = 0; i < 100; i += 1) {
(function (value) {
setTimeout(function () {
console.log(i);
}, 1000 * value);
}(i));
}
}

○ The numbers 0 to 99 with a delay of 1000ms between each line.


○ The numbers 0 to 99 with a 1000ms delay before the first one but no
delay between numbers.
○ The number 100 printed 100 times with a 1000ms delay before the first
one but no delay between numbers.
○ The number 100 printed 100 times with a delay of 1000ms between
each line.
○ The numbers 0 to 99 with an increasing delay between each line,
starting from 0ms and ending with 1000ms.
What is the output of the following piece of code?

function createObject(name, value) {


var returnObject = {};

returnObject[name] = value;
returnObject['addTo' + name] = function () {
return value += 1;
};

return returnObject;
}

var obj = createObject('Property', 100);


console.log(obj.Property);
console.log(obj.addToProperty());
console.log(obj.Property);

○ 100, 101, 100


○ 100, 100, 100
○ undefined, undefined, undefined
○ 100, 101, 101
○ 100, 101, 102

Which of the following regular expressions can be used to


find all occurrences of two-letter words in a string?
○ /[A-Za-z]{2}/g
○ /\b\w{2}\b/g
○ /(?:[a-z][A-Z]|[A-Z][a-z])/g
○ /\b[a-zA-Z]{2}\b/g
○ /\s(.*)\s/g

Why doesn't the following regular expression work?

function hasANumber(value) {
return /^.*[0-9]*.*$/.test(value);
}
○ It will not match strings that contain a decimal like 'abc 12.34'.
○ The * modifier after [0-9] means it will match for strings with no numbers.
○ \d should be used instead of [0-9].
○ The g flag is not set so it will not return true if there are multiple
numbers.
○ It will not match strings with numbers at the beginning or end like '123'.

What does it mean when a function or feature is referred to


as "asynchronous"?
○ It is highly efficient and very fast.
○ It is difficult to use.
○ It will not work on IE8 or older browsers.
○ It requires multiprocessor support.
○ It will not block the current execution.

How can one ensure that a series of asynchronous calls are


invoked in the correct order?
○ Use `setInterval()` and invoke each call after a sufficient delay.
○ Set each function as an element in an array and iterate over this array.
○ Each asynchronous call should accept a callback to execute the next
call in the series when it completes.
○ Use `Math.random()` and hope for the best.
○ It is not possible.

Below is a function for executing asynchronous tasks in


parallel. Why doesn't it work as expected?

function doInParallel(tasks, cb) {


var numTasks = tasks.length;

tasks.forEach(function (task) {
task();
numTasks -= 1;
if (numTasks === 0) {
cb();
}
});
}
doInParallel([...], function () {
// Execute only when tasks are complete
});

○ The callback function will be executed as soon as the last task is


invoked but before any of the tasks complete.
○ The doInParallel function should return `this`.
○ `cb()` should be called after the `forEach`; there is no reason to track the
number of tasks.
○ All of the above.
○ It does work.

What does the `new` operator do when used in conjunction


with a function call?
○ Uses classical inheritance to instantiate an object of that class.
○ Creates a new Object instance assigned to `this` that will be the return
value by default.
○ Performs garbage collection on unused variables in the current scope
and runs the function.
○ Ensures that the return object's prototype contains the correct
properties.
○ Instantiate an object which can be extended with additional methods.

Given the below piece of code, what should `obj.value` be


set to in order for the if-condition to be true?

var obj = {};

obj.value = ???;

if (obj.value === obj.value.value.value) {


}

○ this
○ obj.value
○ function () {return true;}
○ obj
○ window
Given the below code, which of the following is true:

var a = '',
b = '',
c = {value1: a, value2: b},
d = {value2: b, value1: a};

○ a === b && c === d


○ a === b && JSON.stringify(c) === JSON.stringify(d)
○ c === c.value1 && d === d.value2
○ c.value1 === d.value2 && c.value2 === d.value1
○ a === c === d === b

Which of the following can set the background color of a


DOM element to red?

var element = document.getElementById('my-element');

○ element.style.backgroundColor = '#f00';
○ element.bg.color.red = true;
○ element.setBackgroundColor('#ff0000');
○ element.style({ background-color: red; })
○ element.style.background-color = red;

Which of the following is an acceptable way to add a click


event handler to a DOM element?

var element = document.getElementById('my-element');

○ element.click = function () {};


○ element.on('click', function () {});
○ element.addEventListener('click', function () {});
○ element.onclick(function () {});
○ (function onElementClick() {}(element));