Notes from Interview Questions and Concepts

Ten Javascript Theory Questions - The ES6 Quiz

Q1

Is javascript a “pass by value” or a “pass by reference” type of language when it comes to passing function arguments?

Javascript is both. When passing in simple arguments like a string or number, the value is passed into the function. On the other hand, passing in complex types, which in essence boils down to objects, pass in as references. These objects can and will be mutated if changed within the scope of the function.

Q2

Study the following code snippet (see document for full code snippet). What does [ ...users ] do? What is printed to the console?

Q3

Does the code in Q2 conform to the principals of pure functional programming?

No. setCredit modifies the referenced value so side-effects occur.

Q4

How can we prevent setCredit from modifying the original array?

We need to deep clone the array in order to modify it within the function without mutating the original array.

const deepClone = function( obj ){
    return JSON.parse( JSON.stringify( obj ));
};

console.table( setCredit( deepClone( users ), 0, 10 ));

Q5

What is wrong in the following code?

The first console.log will print the sum of the numbers 1-5 (15). The second call will fail because the destructuring pattern is incorrect. [ ...lessNumbers, ] will produce an error because of the comma that indicates more arguments are to follow. The code will work without the comma and yield the answer 6.

Q6

Consider the following function: snip. Determine the output without running the code! Hint: [ 1, 2, 3 ].pop().

arguments is an object so does not have access to pop. The first console.log will print object and 5 but the second call will throw an error.

Q7

Why isn’t 0.1 + 0.2 equal to 0.3?

The precision of the floating point type isn’t entirely accurate, for memory reasons I think, and will not make a nice neat 0.3. It will be a number greater than 0.3 with more digits.

Q8

How can we retrieve a DOM node collection of all div elements on a website? How can we retrieve a DOM node collection of all div elements having the class row-fluid on a website?

const divs = document.querySelectorAll( "div" );
const rowFluidDivs = document.querySelectorAll( "div.row-fluid" );

const divss = document.getElementsByTagName( "div" );
const rowFluidDivss = document.getElementsByClassName( "row-fluid" ); // may not be divs - would need to filter out non-divs

Q9

Swap the contents of two variables without introducing a third variable!

Do not know what type of variable needs swapping.

let one = 1;
let two = 2;
[ one, two ] = [ two, one ];

Q10

Write a function that determines if a string consists of hexadecimal digits only. The digits A-F can either be in lowercase or in uppercase.

const hexStr = function( str ){
    return /^[0-9a-fA-F]+$/.test( str );
};