JavaScript Interview Questions that made me think — Do I really know JavaScript? — Part 5
Challenging JavaScript Interview Questions: Testing My JavaScript Knowledge
“JavaScript: Where ‘null’ is an object, ‘[] + {}’ is not ‘NaN’, and writing code feels like exploring a land of surprises.”
When I first saw these questions, I was like 😢, but when I understood the concept behind each one of them, everything started making sense.
With that said let’s see some interesting questions based on Javascript:
1. What will be logged in console?
.
.
.
Output: true false
Explanation: The arguments
object is a special object available in function scopes, and both {}
and arguments
are constructed using the Object
constructor. Therefore, this comparison evaluates to true
.
2. What will be logged in console?
.
.
.
Output: 1, 101, 0, 0
Explanation: There are few things which needs to be understood in this question before going to explanation:
1. pop
: this method removes element from last index, and returns the removed
element.
const arr = [1,2,3,4,5];
console.log(arr.pop()); // logs 5
2. we can increase the length of an array by simple assigning values to index.
const arr = [];
console.log(arr.length); // 0
arr[4] = 1;
console.log(arr.length); // 5
arr[400] = 1;
console.log(arr.length); // 401
3. we can set values agains string keys other than numerical indices
const arr = [];
arr["JS"] = 1; // no effect on length
console.log(arr.length); // logs 0
console.log(arr["JS"]); // logs 1
4. apply
: this method is used to call a function whose context is defined by the first argument passed, and it accepts a second argument an array of parameters which is optional.
const obj = {
lang: 'JS'
}
function show() {
console.log(this.lang);
}
show(); // logs undefined
show.apply(obj); // logs 'JS'
5. arguments
: special array like object exist in every function, that is declared using function keyword.
Let’s understand the arguments
object in detail:
- When a function is invoked in JavaScript, it creates an internal
arguments
object that holds all the arguments passed to the function. Thisarguments
object behaves similarly to an array in that it has numerical indices and alength
property, but it is not a proper array (it's array-like). arguments
object is an array-like object available within the scope of a function that contains the values of the arguments passed to that function.- While the
arguments
object has some array-like properties, it is not a true array, and it doesn't have access to the array methods likepop
,push
, etc., that are available on arrays created from theArray.prototype
. - However, by using the
apply
orcall
method, you can borrow methods from theArray.prototype
and use them on thearguments
object or any other object.
We can convert arguments
into array, to have all methods by this way:
const argsArray = Array.prototype.slice.call(arguments);
// The slice method is called on the Array.prototype object and is provided with the arguments object as its this context. This allows the slice method to operate on the arguments object as if it were an array.
Now let’s get back to our question:
3. What will be logged in console?
.
.
.
Output: 10 1
Explaination: Let’s re-factor the code:
var a = 1;
function toTheMoon() {
var a; // var has function scope, hence it's declaration will be hoisted
if(!a) {
a = 10;
}
console.log(a); // 10 precendence will be given to local scoped variable.
}
toTheMoon();
console.log(a); // 1 refers to the `a` defined at the top.
4. How long will this data will be available?
.
.
.
sessionStorage.setItem("JS", 99991)
will be available for as long as the current browser session is active. Once the session ends (e.g., the user closes the tab or browser), the data will be cleared. As a matter of fact it will survive the refresh.
5. What will be logged in console?
.
.
.
Output: true true
Explanation: Both admin
and guest
object shares same prototype
chain defined by User.prototype.attributes
When we are calling admin.attributes.isAdmin
, JS engine will try to find the attributes
key is admin
object, when it doesn’t get any key with this name, it will look for the key in prototype
chain.
And guess what, we have a key
named attributes
in prototype
chain of admin
object. And hence JS engine will update the attributes
key in prototype
Object of User
.
Due to this reason, when guest
object will try to access this property it will also get true.
To fix this, we should use attribute
key separatley for each object. we should only use prototypes
to share common functionality:
const User = function() {
this.attributes = {
isAdmin: false
};
};
const admin = new User();
const guest = new User();
admin.attributes.isAdmin = true;
console.log(admin.attributes.isAdmin); // true
console.log(guest.attributes.isAdmin); // false
And if we to the prototype
way, we have to use defineProperty
and use getter and setter to enfore the restriction:
function User() {}
Object.defineProperty(User.prototype, "isAdmin", {
get: function() {
return this._attributes.isAdmin;
},
set: function(value) {
console.error("Cannot directly modify isAdmin property on prototype.");
}
});
User.prototype._attributes = {
isAdmin: false
};
const admin = new User();
const guest = new User();
admin.isAdmin = true; // This will trigger the error message and not actually modify the property
console.log(admin.isAdmin); // false
console.log(guest.isAdmin); // false
6. What will be printed in the console?
.
.
.
Output: 4 16 64
Explanation: **
operator returns the result of raising the first operand to the power of the second operand. It is equivalent to Math.pow()
, except it also accepts BigInts as operands.
7. What will be logged in the console?
.
.
.
Output: a1:- 1 a2:- 2
Explanation: In JavaScript, you can create a function using the Function
constructor. The Function
constructor takes a variable number of string arguments, where each string represents a parameter name, followed by the function body as the last argument. Here's the general syntax:
const functionName = new Function(arg1, arg2, ..., functionBody);
Here’s an example of how you can use the Function
constructor to create a simple function:
const add = new Function('a', 'b', 'return a + b;');
console.log(add(2, 3)); // Output: 5
So, in this line,
(new Function('a=2'))();
in the function body we are doing a=2
, this a will be added to the global scope, and hence we get 2
as a result of
console.log('a2:-', a);
8. What will be printed in the console?
.
.
.
Output: false true
Explanation: If you explicitly return a primitive value from a constructor function using the return
statement, that return value will be ignored, and the instance (object) will be returned by default.
In case you have any doubt or want to understand any concept related to web development, book as session with me on topmate. https://topmate.io/frontendmaster
Here are other part of this series: