JavaScript Interview Questions

15 minutes read

If you approach us with the intention to sell yourself as a JavaScript developer, here are some questions you might be facing. We are prepared for all seniority levels, ES5 / ES6 / jQuery - related questions.

JS interview questions article image

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
    };
  1. Why the quotes around ad-hoc?
  2. How would you obtain the value of ad-hoc property?

Answer: 

  1. Because property name ad-hoc is not a legal JavaScript name. The - character is used for subtraction.
  2. 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:

  1. In a global scope, you can do: var year = 2017;
  2. In any scope, you can do year = 2017;- provided the variable year has not yet been defined in the current scope.
  3. When in the browser, you can use window.year = 2017; in any scope.

Question: Let’s have this regular expression /^([0-9A-Z]+)$/

  1. Explain it
  2. Show us how you would test the variable active against this regular expression

Answer:

  1. At least one character from the start to the end of the string, allowed to contain decimals and uppercase alphabet only.
  2. /^([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

element in variable $div. Show as many ways as you can to remove this element from the view.

Answer: For example:

  • $div.hide()- hides it, alternatively $div.fadeOut() / $div.slideUp() using visual effects,
  • $div.remove() or $div.detach() - removes it from the DOM,
  • $div.css('display' 'none') - uses CSS to hide it.

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: $('<div>').click().hide().show() This is possible, because any method compatible with this principle returns a reference to the original object.

JavaScript Mid-Levels

And now to get a bit tougher…

Standard ES5 trivia

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.

  1. Defining a global variable in the page template, using a separate <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.
  2. Using element attributes such as data-object="...value..." to store this object.
    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.
  3. Passing data in dynamically via AJAX request.
    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).

Question:  You have this statement: + new Date(). What does it do? How does it work?

Answer: 
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

Question:  Look at this code. What’s wrong with it?

    return 
    {
        state: 1,
        text: "notes"
    };

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?

    var callbacks = [];
    for(var i = 0; i < 10; i += 1) {
    callbacks.push(function(argument){
        return argument * i;
    }); 
    }

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:

    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

Question:  You have this code:

    var a = { name: “Alan” };
    var b = a;
    b.name = "Peter";
  1. What will now be the value of a.name?

  2. Rewrite this code to make sure that b is a copy of a, not influencing its original value.

  3. What if a looked like this:

        var a = { name: { first: "Alan", second: "Maxwell"} };
    
    - would it be possible to use the solution from 2)?

    Answers: 

  4. It will be "Peter"because in JavaScript, objects are always passed by reference.

  5. 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.

        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]; }
  6. 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:

    Obj1 = {
        name: "Alex"
    };
    var Obj2 = Object.create(Obj1);
    console.log(Obj2.name);     // will be Alex

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:

  1. given the same input, it always returns the same output,
  2. has no side effects, meaning it does not mutate values outside of the function,
  3. relies on no external resource in order to work properly.

An example would be:

    var add = function(a, b) {
        return a+b;
    };

Advantages: predictability - easy to understand and debug in isolation. Testability - can be replaced by the expected return value when testing.
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

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.
Bonus: store the object property **sex* in constant gender** with a small modification of the previous one-liner.

Solution:

    const {name, age, sex} = getPerson();
    // Bonus:
    const {name, age, sex: gender} = getPerson();

Question: What does this mean? Can you make it even shorter?

    ({ address: adder, image: img }) => { …

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:

    ({ address, image }) => { …

Question:  You have this code:

    const delayedMessage = (message, delay) => {
        return new Promise( (resolve, reject) => {
            setTimeout(() => resolve(message), delay)
        })
    };
  1. What does this function actually return and what does it mean?
  2. Write a code that executes delayedMessage with the message "hello" and a delay of 2 sec. Handle the returned value properly to make sure that it displays the string passed into console after the delay.
  3. Change the delayedMessage definition to contain a condition that will immediately fail the promise if the message is "error". Take care of the error properly.

Answers: 

  1. The function returns a promise, which is an object. The idea is that the promise represents the possible completion (or failure) of an asynchronous operation, and its resulting value. It implements then() and catch() methods that allow to register the completion (and failure) handlers.
  2. Using the code below:
        delayedMessage("hello", 2000).then((message) => console.log(message));
  3. The new delayedMessage definition will be:
        const delayedMessage = (message, delay) => {
            return new Promise( (resolve, reject) => {
                if(message ==  "error") {
                    reject(message);
            } else {
                setTimeout(() => resolve(message), delay)
                }
            })
        };

    ...and the proper usage can be something like:

        delayedMessage("hello", 2000)
        .then((message) => console.log(message))
        .catch((error) => console.log("error happened: " + error));

    One particularly handy jQuery task

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.

    var result = jQuery(selector).sumWidths({ /* … options … */ });

Solution: 

    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...

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?

Final Note

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!

Send us
a message

Contact form is disabled because Kurzor no longer operates.

Thanks for understanding!