So you want to be a JavaScript developer, right? We prepared several questions that will estimate your level and experience with the language. And we added what we consider best answers, too.
We tried to make the questions as much generic as possible, relying mostly on basic language properties. Because progressive developers today use it, we also added some non-trivial quiz on ES6. And jQuery, which is not exactly a requirement, though knowledge of it is a plus point, considering how often you run into it.
So, to the question list! - Divided by seniority levels:
Junior Level JavaScript Developers
Standard ES5 questions
Question: You have this object:
var obj = {
"ad-hoc": 15
};
- Why the quotes around ad-hoc?
- How would you obtain the value of ad-hoc property?
Answer:
- Because property name ad-hoc is not a legal JavaScript name. The - character is used for subtraction.
- Easiest would be to use obj["ad-hoc"]
Question: Let’s have a variable param, which was supplied as function argument. How do we test it’s a string?
Answer: Through the expression typeof param == 'string'
Question: How do you create a global variable year with the value of 2017? Show at least 2 ways to do that.
Answer - we give you 3 ways, actually:
- In a global scope, you can do: var year = 2017;
- In any scope, you can do year = 2017;- provided the variable year has not yet been defined in the current scope.
- When in the browser, you can use window.year = 2017; in any scope.
Question: Let’s have this regular expression /^([0-9A-Z]+)$/
- Explain it
- Show us how you would test the variable active against this regular expression
Answer:
- At least one character from the start to the end of the string, allowed to contain decimals and uppercase alphabet only.
- /^([0-9A-Z]+)$/.test(active)
Question: You have this code block
function filler(max) {
var arr = [];
for(j=0; j<max; j+=1) {
var c=j*2;
arr[j] = c;
}
return arr;
}
filler(10);
In which code lines we can access variable c, defined at line 4? Why?
Answer: Variable c is accessible in the scope of function filler, immediately after it’s been defined for the first time via *var c = j2** statement. This is because JavaScript has a function scope.
Task: Create a code that will convert an object obj into an array arr, dropping object keys and appending all object values at the end of the array.
Bonus: do it only for the object’s own (non-inherited from prototype) properties.
Solution:
var arr = [];
for(var key in obj) {
arr.push(obj[key]);
}
Bonus:
var arr = [];
for(var key in obj) {
if(obj.hasOwnProperty(key)) {
arr.push(obj[key]);
}
}
Not too difficult ES6 questions
Question: What is the difference between let and const in a variable creation?
Answer: let declares variables that can be changed later, const assumes they will be static.
Question: let and const are block-scope declarations, in contrast with var. How does that manifest?
Answer:Block-scope declaration means it is accessible in the scope of this block and all nested blocks. Block is anything bounded by {} brackets, i.e. function body, loop body, condition body etc.
Task: Rewrite this block of code to standard ES5 JavaScript:
const caller = id => callback => callback(id)
Solution:
var caller = function(id) {
return function(callback) {
callback(id);
}
};
Task: You have an array
var a= [1, 2, 7];
Append it to the end of array containing [1, 3] using a single expression.
Solution: The expression is [1, 3, ...a]
jQuery Essentials
Question: Say you have a jquery selector containing a Answer: For example: Question: jQuery uses method chaining. What is it? How do you achieve it? Answer: Method chaining in jQuery allows a jQuery object to use different methods in a dot pattern like this: And now to get a bit tougher… Question: If you need to pass an object with data from back-end to front-end JavaScript, what ways can you use and what are their advantages / disadvantages? Answer: We list below three options. The first two solutions are static - they are placed in a template and thus would change only when the server page is re-rendered. Third one is dynamic. Question: You have this statement: + new Date(). What does it do? How does it work? Answer: Question: Look at this code. What’s wrong with it? Answer: JavaScript tries to automatically complete missing semicolons. In this case, it wrongly assumes the return is final and completes as return; completely ignoring the object we intend to return. Returned values must always start on the same line as the return statement. Question: You want to create an array of callbacks that use a progressively incrementing number, starting from 0 to 9. These callbacks are intended to be called later, each with the proper 0..9 increment. Why is the approach below not a good solution? How would you fix it? Answer: Because JavaScript has a function scope, the variable i is accessible through most of the code example. Which means, even in callbacks, it will reference the same variable and will thus equal the last value when i was accessed (10). This behaviour can be fixed by applying one more function to create a closure around the callback definition: Question: You have this code: What will now be the value of a.name? Rewrite this code to make sure that b is a copy of a, not influencing its original value. What if a looked like this: Answers: It will be "Peter"because in JavaScript, objects are always passed by reference. You can use various techniques to create a copy of an object. The most convenient one is to use Object.assign in latest browsers, or copy all properties of the object into a new object manually. Also, jQuery has a similar method extend. In this case the value of name is an object and it will pass by reference. You will need to recursively create copies to fix this. In jQuery.extend, it is possible to use true as the first parameter to indicate you want to create a deep copy. Be forewarned though, if your properties are pointing to others in a circular pattern, it might cause an infinite loop. Question: What kind of inheritance does JavaScript work with? Use example objects Obj1 and Obj2 to demonstrate inheritance: make Obj2 inherit properties from Obj1. Answer: JavaScript uses prototypal inheritance. Every JavaScript object has a link to its prototype, which is also an object. If a property of an object is not found in the object itself, it will try to find it in its prototype. In ECMAScript 5, it is most recommended to use Object.create to define an object prototype. So in our example, when creating Obj2, you would call: Question: What is a pure function? Write an example in JavaScript. What are the advantages/disadvantages of pure functions? Answer: A pure function meets three conditions: An example would be: Advantages: predictability - easy to understand and debug in isolation. Testability - can be replaced by the expected return value when testing. Task: Let’s have a function getPerson() that returns an object with many properties. Illustrate how to obtain the following properties: name, age and sex from what function getPerson has returned, and store them as local constants of the same name. Use the shortest form possible - one line should do. Solution: Question: What does this mean? Can you make it even shorter? Answer: It means you have a function in which you expect an object parameter to be passed in. You use a what is called destructuring assignment to retrieve object property address and image when the function is called, and store them in local variables named addr and img. A shorter form is simple - that is if you don’t mind the local variables being named the same as the properties: Question: You have this code: Answers: ...and the proper usage can be something like: Task: Write a jQuery plugin called sumWidths that will sum the widths of all nodes affected by the selector. It will accept options and have defaults for them as well. Solution: A JavaScript senior should really have a deep experience with the language and be able to choose from a variety of patterns to perform operations most efficiently. There are a couple of questions you should ask JS Seniors. No more a ES5 / ES6 / jQuery divider here, as these are not relevant. We won’t give you the answers - you should come up with the best answer yourself and be able to defend it. Question: Explain the difference between a declarative and imperative paradigm in coding. Which JavaScript frameworks or libraries are typical examples and why? Question: Why is immutability an important concept for functional programming? How do you best implement it in JavaScript (ES5 / ES6)? Question: List all asynchronous programming concepts in today’s JavaScript that you know of. Explain their usage and advantages / disadvantages. Question: What particular library of framework do you use most to develop web apps? Why do you favour this solution? Question: What approaches do you know of to create native mobile apps in JavaScript? How do they integrate with the web app? So we have shown you the questions we usually ask developers to assess their level of knowledge and approach to problems. Our experience shows that it is not really necessary to be as trendy and up-to-date as possible (for example, do you see any React questions?) - there is a lot of time-proven code that will easily tell if you understand the stuff or not. If you find yourself having a really good set of answers to the senior-level questions, and at the same time you’re thinking about changing your job, don’t hesitate to drop us a line - we are always happy to welcome new JavaScript guys and gals on board!
$('<div>').click().hide().show()
This is possible, because any method compatible with this principle returns a reference to the original object.JavaScript Mid-Levels
Standard ES5 trivia
<script>
tag.
Advantages: It is a pretty straightforward method, values can be used without conversion.
Disadvantages: HTML grows in size + you need to keep the proper JavaScript syntax in the object definition, including encoding.
Advantages: data can be adjacent to an element of interest. Different elements can contain different data. Data do not pollute global JS scope. You can use shorthand method data() in jQuery.
Disadvantages: you need to encode/decode data properly, for example putting it into JSON format. Extremely large data would make the page HTML code less readable.
Advantages: Data are always up-to-date. Page HTML is not affected in size. You do not need to alter the templates.
Disadvantages: A communication delay would result in a necessary waiting period. You need to add server-support for the AJAX call. You need to encode/decode the values (there are tools to do that quickly).
What: It returns the timestamp of the current time.
How: the + operator triggers the valueOf() method of a new Date instance. So, this is the same as calling: (new Date()).valueOf()
// brackets around the “new” added for better readability, though not really necessary
return
{
state: 1,
text: "notes"
};
var callbacks = [];
for(var i = 0; i < 10; i += 1) {
callbacks.push(function(argument){
return argument * i;
});
}
var callbacks = [];
for(var i = 0; i < 10; i += 1) {
(function(increment) {
callbacks.push(function(argument){
return argument * increment;
});
})(i);
}
// testing
console.log(callbacks[1][2]); // will return 4
console.log(callbacks[4][2]); // will return 8
var a = { name: “Alan” };
var b = a;
b.name = "Peter";
var a = { name: { first: "Alan", second: "Maxwell"} };
- would it be possible to use the solution from 2)?
var b = Object.assign({}, a); // Object.assign way
var b = jQuery.extend({}, a); // jQuery extend way
var b = {}; // manual way
for(var attrName in a) { b[attrName] = a[attrName]; }
Obj1 = {
name: "Alex"
};
var Obj2 = Object.create(Obj1);
console.log(Obj2.name); // will be Alex
var add = function(a, b) {
return a+b;
};
Disadvantages: cannot be used just anywhere (i.e. I/O functions are impure by default). Requires some learning time to use in practice effectively.More complex ES6 Questions
Bonus: store the object property **sex* in constant gender** with a small modification of the previous one-liner. const {name, age, sex} = getPerson();
// Bonus:
const {name, age, sex: gender} = getPerson();
({ address: adder, image: img }) => { …
({ address, image }) => { …
const delayedMessage = (message, delay) => {
return new Promise( (resolve, reject) => {
setTimeout(() => resolve(message), delay)
})
};
delayedMessage("hello", 2000).then((message) => console.log(message));
const delayedMessage = (message, delay) => {
return new Promise( (resolve, reject) => {
if(message == "error") {
reject(message);
} else {
setTimeout(() => resolve(message), delay)
}
})
};
delayedMessage("hello", 2000)
.then((message) => console.log(message))
.catch((error) => console.log("error happened: " + error));
One particularly handy jQuery task
var result = jQuery(selector).sumWidths({ /* … options … */ });
jQuery.fn.sumWidths = function( options ) {
var default_options = {
/* defaults */
};
var opts = jQuery.extend({}, default_options, options);
// code below can access options via opts object
var sum = 0;
this.each(function(){
sum += this.width();
});
return sum;
};
And some Senior Level stuff...
Final Note