JavaScript question
What is the difference between var and let?
While this seems easy enough, you will not believe how many candidates I had to turn down just because they could not answer this question. The difference is in the level of scope. var
is function-scoped, but let
(and const
) are block-scoped.
What is the difference between == and ===?
If your answer is “==
compares by value and ===
also compares by type", it is not correct. The way JS engine understands it, ==
allows type coercion and ===
disallows. Type coercion is the automatic type conversion by the interpreter. This is the source of most confusion in JS (like [] == ![]
being true).
What does ‘this’ keyword mean?
You might be tempted to answer that this points to the instance of the class inside its body, but this is also not right. First off, classes in JS are syntactic sugar and do not introduce any new features. this
keyword is available in any function and points to the object that contains this function.
What is a constructor function?
Constructor functions in JS are also not class-related functions and are tied closely to this
keyword. A constructor function is called with new
keyword and returns whatever the value of this
is. Note that in constructor functions this
does not point to the outer object, but instead used as a placeholder object.
NaN === NaN?
False. This is an endless source of debate and one of the most confusing parts about JS. In a nutshell, NaN
stands for Not a Number, and just because one value is not a number and another one is not a number does not imply they are equal. The downside is you cannot really check if a variable is NaN
using myVariable === NaN
. You can use the Number.isNaN
function or myVariable !== myVariable
to check for it.
What are the primitive data types in JS?
A primitive data type in JS is data that is not an object and that has no methods. Here is the list of primitive data types in JS:
- Boolean
- Null
- Undefined
- Number
- BigInt
- String
- Symbol
What is “strict” mode?
In JS, you enable strict mode by putting "use strict";
at the beginning of the file. Strict mode enables more rigorous error-checking in your code and makes debugging easier. For example, this snippet will work in regular JS, but not strict.