Ten JavaScript Theory Questions
These are popular conceptual questions asked in JavaScript interviews.
We'll cover the following...
There are countless questions your interviewers may ask when it comes to how JavaScript works. The idea behind asking these questions is to assess whether you have recent experience in writing JavaScript code.
Some more clueless interviewers tend to ask you for lexical knowledge and edge cases that you could simply look up online. I, personally, think that this signals a lack of competence from the end of my interviewers, and I tend to start getting concerned whether I am in the right place.
Usually, you are not allowed to use Google to find the answer, and you have to answer on the spot.
Question 1
Is JavaScript a “pass by value” or a “pass by reference” type of language when it comes to passing function arguments?
Answer: JavaScript passes function arguments by value. In case we pass an array or an object, the passed value is a reference. This means you can change the contents of the array or the object through that reference.
Read this article on value and reference types for more details.
Question 2
Study the following code snippet:
let user1 = { name: 'FrontendTroll', email: 'ihatepopups@hatemail.com' };let user2 = { name: 'ElectroModulator', email: 't2@coolmail.com' };let users = [ user1, user2 ];let swapUsers = function( users ) {let temp = users[0];users[0] = users[1];users[1] = temp;return users;}let setCredit = function( users, index, credit ) {users[ index ].credit = credit;return users;}console.table( swapUsers( [...users] ));console.table( setCredit( [...users], 0, 10 ) );console.table( users );
What does [...users]
do? What is printed to the console?
Answer: [...users]
makes a shallow copy of the users
array. This means we assemble a brand new array from scratch. The elements of the new array are the same as the elements of the original array.
However, each element is an object in each array. These objects are reference types, which means that their content is reachable from both arrays. For instance, modifying [...users][0].name
results in a modification in users[0].name
.
Let’s see the printed results one by one.
In the first console table, we expect the two elements to be swapped. This change left the users
array intact, because none of its elements were modified.
console.table( swapUsers( [...users] ) );
This is printed on the screen:
(index) | name | |
---|---|---|
0 | “ElectroModulator” | "t2@coolmail.com" |
1 | “FrontendTroll” | "ihatepopups@hatemail.com" |