DEV Community

Cover image for 9 Common JavaScript Interview Questions You Might Not Know The Answer For.
Gus Pear 🍐
Gus Pear 🍐

Posted on • Updated on

9 Common JavaScript Interview Questions You Might Not Know The Answer For.

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
Enter fullscreen mode Exit fullscreen mode

Explanation

  • The condition statement if(function f() {}) returns function f() {} which is truthy, so the code executes inside the if statement.
  • typeof f returns undefined because the function f(){} was never declared outside the if statement, so it doesn't "exist" outside the if brackets if (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
Enter fullscreen mode Exit fullscreen mode

Write an example of closure

function createFunction(msg) {
    return function(name) {
        return msg + name;
    }
}

let myFunc = createFunction("Hey ");
console.log(myFunc("Dude")); // Hey Dude
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

*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' }
Enter fullscreen mode Exit fullscreen mode

delete operator on Object

const Person = {
    name: 'Gus',
    age: 32,
}

const person1 = Object.create(Person);
delete person1.age

console.log(person1.age); // 32
Enter fullscreen mode Exit fullscreen mode
  • person1 is created with its prototype set to the Person object.
  • When the instance person1 has it's age property deleted, we can still access the age 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
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Oldest comments (28)

Collapse
 
ervin_szilagyi profile image
Ervin Szilagyi

I will leave this here 🫣:

> function isInt(num) {
...   return num % 1 === 0;
... }
undefined
> isInt(1.00000000000000001)
true
> isInt(1.0000000000000001)
true
> isInt(1.000000000000001)
false
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gustavupp profile image
Gus Pear 🍐

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:
Image description

Thanks again for raising the issue.

Have a great week

Gus

Collapse
 
ervin_szilagyi profile image
Ervin Szilagyi • Edited

Yes, this is why the builtin Number.isInteger fails with the same values:

>Number.isInteger(1.00000000000000001)
true
>Number.isInteger(1.0000000000000001)
true
>Number.isInteger(1.000000000000001)
false
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
gustavupp profile image
Gus Pear 🍐

That's right Ervin

Collapse
 
tracygjg profile image
Tracy Gilmore • Edited

Hi Gus,
I think you have a few typos in the section covering "delete operator on Object"

The prototype object Person and the instance person1 would have a property of age but not Age so delete person1.age would have the intended result but console.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.

Collapse
 
gustavupp profile image
Gus Pear 🍐

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.

Collapse
 
carlosds profile image
Karel De Smet

The simplest and most correct way to check if a number is an integer is Number.isInteger()

Collapse
 
gustavupp profile image
Gus Pear 🍐

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!

Collapse
 
carlosds profile image
Karel De Smet

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.

Collapse
 
gustavupp profile image
Gus Pear 🍐

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.

Collapse
 
moopet profile image
Ben Sinclair

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

Collapse
 
gustavupp profile image
Gus Pear 🍐

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.

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

Collapse
 
gustavupp profile image
Gus Pear 🍐

What? Sh... That is awesome!
Thanks for including this post on your post @fruntend!

Collapse
 
dpagey profile image
Pagey

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

Collapse
 
gustavupp profile image
Gus Pear 🍐

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

Collapse
 
dpagey profile image
Pagey

"definitely"...sure

Collapse
 
milandry profile image
Michael Landry

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

Collapse
 
gustavupp profile image
Gus Pear 🍐

Hey Michael, how is it going?

I think both are relevant.

Thanks for your comment.

enjoy the rest of your week!

Collapse
 
parthprajapati profile image
Parth

Nice one :) Earlier looked for some similar and easy to understood tut, but couldn't find it. Thanks

Collapse
 
gustavupp profile image
Gus Pear 🍐

Thans Parth, I am glad you liked it!

Have a great rest of your week

Collapse
 
gabrielprogramerx profile image
Gabrielprogramerx

I love JavaScript

Collapse
 
gustavupp profile image
Gus Pear 🍐

Me too! haha

Collapse
 
ravavyr profile image
Ravavyr

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.

Collapse
 
gustavupp profile image
Gus Pear 🍐

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)

Collapse
 
ysmnikhil profile image
Nikhil Malik

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 ;)

Collapse
 
raguram90 profile image
RamR

thanks. very useful article. got better understanding of closures now.

Collapse
 
gustavupp profile image
Gus Pear 🍐

I am glad it was helpful RaguRam!

Thanks for your comment!

Enjoy your sunday