Whether you like them or not, tricky questions are still asked by interviewers in the wild.
The reason is, these questions can tell a lot about your core understanding of the language, and therefore if you are a fit for the job.
Common concepts addressed in these questions include:
- Hoisting
- Closure
- Scope
- Value vs Reference type
- Prototype inheritance
Today we will kill two birds with one stone.
Prepare to ace your next interview and brush up on the core concepts, at once.
Why typeof f
is undefined?
var y = 1;
if (function f() {}) {
y += typeof f;
}
console.log(y); // 1undefined
Explanation
- The condition statement
if(function f() {})
returnsfunction f() {}
which is truthy, so the code executes inside the if statement. -
typeof f
returnsundefined
because the functionf(){}
was never declared outside theif
statement, so it doesn't "exist" outside theif
bracketsif (f(){}) { It doesn't exist here }
This is how we would "fix" this code snippet:
var y = 1;
function f() {}; //declare function outside if brackets
if (f) { //f exists so we enter the if block
y += typeof f; //here typeof f is function
}
console.log(y); // 1function
Write an example of closure
function createFunction(msg) {
return function(name) {
return msg + name;
}
}
let myFunc = createFunction("Hey ");
console.log(myFunc("Dude")); // Hey Dude
Explanation
- The first function (createFunction) returns an anonymous function
- The anonymous function returns the parameter
msg
from the outer function(createFunction()) +name
from itself.
When we declare the variable javascript let myFunc = createFunction("Hey ")
the variable myFunc
holds a reference to the anonymous function returned by the outer
What is interesting is that when you call javascript myFunc("Dude")
(passing just the 'name' parameter) it still "remembers" the value of msg
that was passed in when createFunction()
was executed.
The ability to access variables from the outer 'scope' where the function was created is one of the definitions of closure.
Learn more about closures here
Write a multiply() function that can be called like multiply(2)(5)(10) and returns 100
This is similar to the example above, the difference being that we are retuning an additional function and invoking all of them straight away(no using variables for holding references)
function multiply(x) {
return function(y){
return function(z) {
return x*y*z;
};
}
}
multiply(2)(5)(10) //100
By invoking multiply like
javascript multiply(2)(5)(10)
We are invoking the returned functions one after the other.
We could use intermediate variables to make it clearer. Let's have a look:
let func1 = multiply(2); // x is 2
console.log(func1) // function(y) { return function(z) { return x*y*z } }
let func2 = func1(5); // y is 5
console.log(func1) // function(z) { return x*y*z }
func2(10); // z is 10
// finally has all 3 values and returns their product.
Learn more aboute Nested Functionshere
delete
operator on a local variable
What would be the output of the following code?
let output = (function(x) {
delete x;
return x;
})(0);
*The delete operator is meant to be used to delete properties of objects, and not on value types(number in this case).
This would work:
let obj = { name: 'Gus', age: 32 }
delete obj.age;
console.log(obj) // { name: 'Gus' }
delete
operator on Object
const Person = {
name: 'Gus',
age: 32,
}
const person1 = Object.create(Person);
delete person1.age
console.log(person1.age); // 32
-
person1
is created with its prototype set to thePerson
object. - When the instance
person1
has it'sage
property deleted, we can still access theage
property of the prototype object(Person) - That is why it seems like it didn't work.
This is a big topic, you can learn more here
delete
operator on Array
What would be the result of logging arr.length ?
let arr = ["a", "b", "c", "d"];
delete arr[2];
arr.length // 4
- When used on arrays, the delete operator sets the delete element to 'empty' but does not remove it from the array, not changing the length of the array.
What will be the value of both console.log's?
var favouriteAnime = "Dragon Ball";
(function() {
console.log(favouriteAnime);
var favouriteAnime = "Naruto";
console.log(favouriteAnime);
})();
// undefined
// Naruto
Here is how the compiler interpreted this code:
var favouriteAnime; // declared and initialized with undefined
(function() {
console.log(favouriteAnime);
var favouriteAnime = "Naruto";
console.log(favouriteAnime);
})();
favouriteAnime = "Dragon Ball";
// undefined
// Naruto
A few things to keep in mind when declaring JavaScript functions and variables.
- Variable assignment(myVar = 5) takes precedence over function declaration(function func(){})
- Function declarations(function func(){}) take precedence over variable declarations(var myVar;) *let or const
- Function declarations(function func(){}) are hoisted over variable declarations(var myVar;) but not over variable assignments(myVar = 5;).
As a best practice, you should always declare your functions before invoking them.
Learn more about hoisting here
How would you check if a number is an integer?
The easiest way to check if a numner is a decimal ir integer is by using the built-in Number.isInteger()
console.log(Number.isInteger(4)); // true
console.log(Number.isInteger(12.2)); // false
console.log(Number.isInteger(0.3)); // false
Another way is to see if there is a remainder left when you divide by 1.
function isInt(num) {
return num % 1 === 0;
}
console.log(isInt(4)); // true
console.log(isInt(12.2)); // false
console.log(isInt(0.3)); // false
Note: There is a limit to JavaScript precision when handling floating points. If you check Number.isInteger(1.0000000000000001)
will return true
. You can learn more here
Conclusion
Remember to hit f12 and try out the examples for yourself.
This tiny action will help you remember what you learned for much longer.
This is a recap of what we have seen today:
- Why typeof
f
is undefined? - Write an example of closure
- Write a multiply() function that can be called like multiply(2)(5)(10) and returns 100
- Delete operator on a local variable
- Delete operator on Object
- Delete operator on Array
- What will be the value of both console.log's?
- How would you check if a number is an integer?
Thanks for reading!
If you like this article:
*Leave a comment below(You can just say hi!)
*Follow me on Twitter @theguspear.
Catch you later my dude,
Gus.
Top comments (28)
I will leave this here 🫣:
Hi Ervin!
Thanks for taking the time to comment.
I did a quick research and turns out JavaScript has a precision limit when it comes to numbers.
Here's what the MDN's explanation:
Thanks again for raising the issue.
Have a great week
Gus
Yes, this is why the builtin
Number.isInteger
fails with the same values:That's right Ervin
See, I'm bad with terminology and my javascript is self-taught, so with 16 years experience i can pretty much build anything on the internet [given enough time and resources], but i can't answer silly questions about closures and type that have zero effect on real world day to day projects.
Ask me how I'd write code to meet a request and how I'd provide a deliverable.
Ask me how I check for code performance or responsiveness [how many of you have code that fires on load but breaks when a browser window is resized? do you even know? do you even resize while testing?]
Give me a business problem and ask me what i'd write to solve it.
Give me data and tell me what you want to show on the interface and include some additional behind the scenes logic that needs to be performed on the data to meet the interface requirements.
Ask me what i do if there's a bug in the code. Present me with a bug and let me debug it, track down and solve the problem.
Ask me real world questions, not book questions.
If i want to know which type is undefined...I run the code.
I wouldn't write a multiple function because i can put that one line inside another function as needed
If i want to write a certain piece of logic....I write that piece of logic without first debating whether one term outweighs another term.
If i want to know what code performs better, i write both options and run them side by side to see since in the real world code performance also depends on the data its processing and what devices you're running it on.
That "delete" stuff though...man that's gonna ruin anyone's life, cuz you don't use it often and when you do it just doesn't work like you'd expect and I wish the people developing javascript would fix odd behaviors like that instead of shoving more and more Type nonsense into the language just because it seems devs can't be expected to write code with a few extra if statements to handle unexpected types?
Code interviews kill me. Good article though.
I loved your comment Ravavyr!
I understand how you feel about coding interviews, cuz I feel the same way.
Unfortunately, we have to play by their rules if we want a better job.
Thanks for sharing your thoughts on this topic.
Enjoy the rest of your week Ravavyr.
Off-topic: Your writing is good as. Funny, witty, and has a ton of personality (I'll get there)
Ravavyr, I agree with you.
From your comment, I can see, you have lots of amazing things in mind and which could become a series series of blogs.
If yes, I will be eagerly waiting for that ;)
Hi Gus,
I think you have a few typos in the section covering "delete operator on Object"
The prototype object
Person
and the instanceperson1
would have a property ofage
but notAge
sodelete person1.age
would have the intended result butconsole.log(person1.Age)
would be undefined.Also, in the description there is a reference to
'emp1'
but that is not referenced in the example. It also states "has it's 'name' property deleted" when it does not, it is the age property that is deleted.I suggest replacing the text for:
When the instance 'person1' has its 'age' property deleted, we can still access the 'age' property of the prototype object(Person)
.Best regards.
Hey Gilmore!! How are you doing?
Thanks again for stopping by, catching my mistakes, and improving the post.
The typos have been corrected.
Have a wonderful week.
Most of these seem to be, "this code is deliberately broken, how could you make it work?" type questions, and they're a bit contrived. The solution to all of them is, "write clean, self-documenting code that doesn't try to be too clever".
Hey Ben, how are you?
I agree 100% with what you said.
The phrase: "write clean, self-documenting code that doesn't try to be too clever", solves 99% of the problems.
Thanks for your comment.
Have a great week.
The simplest and most correct way to check if a number is an integer is
Number.isInteger()
Hi Karel! How are you doing?
You are right.
I'll add
Number.isInteger()
to the examples.Thanks for stopping by and improving the post.
Hope to see you around again.
Have a great week!
"Common interview questions" 🤔
Good article but these questions probably shouldn't come up in interviews. There are much more relevant questions for the day-to-day job.
Hi Pagey! Thanks for taking the time to comment.
They are definitely relevant for the day-to-day but have also come up in interviews in the past.
Enjoy the rest of your week
"definitely"...sure
thanks. very useful article. got better understanding of closures now.
I am glad it was helpful RaguRam!
Thanks for your comment!
Enjoy your sunday
After reading this post, I get the sense that people who ask these questions are less interested in closures and more interested in higher order functions
Hey Michael, how is it going?
I think both are relevant.
Thanks for your comment.
enjoy the rest of your week!
Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍
What? Sh... That is awesome!
Thanks for including this post on your post @fruntend!
Asking for an explanation and example of closure or hoisting are questions I would consider asking during an interview. But the other ones, not really.
Hey Karel,
I agree.
Questions about closure and hoisting directly reflects the core understanding of the language, which is as you know of great importance.
The other questions about delete operator and having a function being evalueated inside an
if
statement are just tricky questions that are good to know and understand.Thanks again for your comment.