ganqqwerty / 123-essential-javascript-interview-questions Goto Github PK
View Code? Open in Web Editor NEWJavaScript interview Questions
License: BSD 3-Clause "New" or "Revised" License
JavaScript interview Questions
License: BSD 3-Clause "New" or "Revised" License
Hello Nishant, Your repo helps me learn a lot about javascript,I found that question 32 and 33 are the same with questions 34 and 35,for telling you the problems and hope to learn more from you.
In "Question 29. Write a function called deepClone which takes an object and creates a object copy of it.", the deepClone function should check for a null
value:
if( typeof object[key] === 'object' && object[key] !== null )
...
What's more, we usually want to also check for hasOwnProperty()
.
If condition statement evaluate using
eval
I'm not sure if this is correct? According to mdn,
if (condition)
condition
An expression that evaluates to true or false.
My understand is function f() {}
here is an function expression instead of function declaration so f
is not a variable. Hence it's undefined
.
Can you provide any reference of "If condition statement evaluate using eval
"?
The function defined in the prototype function displayIncreasedSalary() is trying to call the private function increaseSalary() defined in the constructor function. This doesn't work.
for (var i = 1; i <= 2; i++) {
setTimeout(function() { alert(i) }, 100);
}
The use case for IIFE
Add if found suitable
The code is
function funcA(){
console.log("funcA ", this);
(function innerFuncA1(){
console.log("innerFunc1", this);
(function innerFunA11(){
console.log("innerFunA11", this);
})();
})();
}
console.log(funcA());
The given answer funcA Window {...} innerFunc1 Window {...} innerFunA11 Window {...}
didn't consider the output from the last line, which should be undefined
Now it does not return undefined x 1 but "empty"
Please check and revise the answer.
Question 38 seems to be wrong.
emp1.displayName = function() {
console.log('xyz-Anonymous');
};
employee.displayName();// "xyz-Anonymous"
emp1.displayName(); // "Nishant"
These two should be switched.
employee.displayName();// "Nishant"
emp1.displayName(); // "xyz-Anonymous"
(function() {
var array1 = [];
var array2 = new Array(100);
var array3 = new Array(['1',2,'3',4,5.6]);
console.log(array1);
console.log(array2);
console.log(array3);
console.log(array3.length);
}());
Answer: 1) [] [] [Array[5]] 1
Correct is [] [undefined × 100] [Array[5]] 1
var count = function () {
this.c = 0 ;
var add = function () {
return ++this.c;
};
this.addNum = function (n) {
for(i= 0; i<n ; i++) {
add();
}
return this.c ;
};
}
console.log(new count().addNum(10));
At question 14 (https://github.com/nishant8BITS/123-Essential-JavaScript-Interview-Question#14-what-will-be-the-output-of-below-code), there are 2 lines of 'Boolean + Number -> Addition'
Should one be 'Boolean + Boolean -> Addition'?
employee.displayName(); //Nishant
emp1.displayName();//xyz-Anonymous
There is one more way to set default parameter value:
function sendEmail(configuration, provider = "Gmail") {
console.log(`Provider: ${provider}`);
}
sendEmail("Config");
I'd like to commend you for the compilation of the JavaScript examples. I like the variety you provide and they give some good reminders on common pitfalls. I do, however, implore you to review and update some of your examples. Some are inaccurate or have outright errors.
Question 48 for example assigns an object to a reserved word, location. And then the 'Method 1', ES6 example for this is not only a poor example of ES6, it is also errored. A good example would be:
const merge = (toObj, fromObj) => Object.assign(toObj, fromObj);
Keep up the good work. Just be sure that it is correct. :)
Hi,
I think it is bad example to show Function Declaration in if/else block.
http://stackoverflow.com/questions/10069204/function-declarations-inside-if-else-statements
Thanks!
var y = 1;
if (function f() {}) {
y += typeof f;
}
console.log(y); // 1undefined
I do not agree with this answer as it does not explain what's going on here.
f
is a named function, but it is "created" within the if
statement itself, and the JS engine does NOT create a reference for it at the beginning of the scope.
(function(){
console.log(typeof f, typeof y) // function undefined
function f(){}
var y = 1;
})()
As you can see the function is declared after the printing of the typeof f
and this works because all variables and functions references are compiled to the beginning of the scope.
(function(){
var f = function f(){}, // not really, but "f" acts like a variable because this is only a reference to the named function
y;
console.log(typeof f, typeof y); // function undefined
y = 1;
})()
but in the question, the function was created within the if
statement, and the JS engine therefor does not hoist the reference to the beginning of the scope, but instead the whole thing evaluates into something the if
statement can handle, which is fundamental true/false
scenario and then the was never really created and is discarded by GC.
Another interesting thing would be to print this:
console.log( function f(){}, (function f(){})() ); // ƒ f(){} undefined
and this also shoes that when functions are created inside specific "things" no reference is really created:
console.log( function f(){}, typeof f); // ƒ f(){} "undefined"
Anyway, I think this question should never be asked in an interview because this is far far from real-life scenarios and does not show any skills beside general knowledge of lesser-known specific hoisting-related scenarios.
the method Array.isArray() is available in also in plain Jasvascript not just in JQuery
Array.isArray()
on MDN
In the Array topic, the answer to question2 is wrong.
It should be 2 i.e ([] [undefined × 100] Array[5] 1)
Hey there, description in question 23 needs a bit of adjustment
Let say
new User("xyz")
created a object calledfoo
and returned nowfoo["location"]
would be assigned value asUSA
and person is referencing tofoo["location"]
.
Here, person
is not referencing foo["location"]
, instead it is being assigned the result of Assignment Operator =
which in this case returns string 'USA'. Assignment operator always returns the value of the expression on the right, as described here:
ECMAScript Specification , pt 12.14.4
Otherwise it's totally correct, thanks for great work!
Both compares return false. This is because in JavaScript we pass non primitive data types by reference. So, say:
{id:1} == {id:1} // returns false even though is shallow compare, we are not comparing here two objects values, but 2 references, which are different.
Thank you so much for your list of helpful questions.
Looking at https://github.com/ganqqwerty/123-Essential-JavaScript-Interview-Questions#7-what-would-be-the-output-of-following-code--2, I think the explanation would make more sense like this:
(function () {
console.clear();
function getName1() {
console.log("getName1", this.name);
}
Object.prototype.getName2 = function () {
console.log("Object.prototype.getName2", this.name);
};
Object.prototype.getName3 = () => {
console.log(
"Object.prototype.getName3",
this.name,
"Why does this one not work?"
); //https://stackoverflow.com/a/31755263/470749 because "Arrow functions provide a lexical this. It uses the `this` that is available at the time the function is evaluated." See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
};
Object.prototype.getName4 = () => {
console.log(
"Object.prototype.getName4",
Object.getPrototypeOf(this).name,
"This one does not make sense"
);
};
let personObj = {
name: "Tony",
print: getName1
};
personObj.print();
personObj.getName2();
personObj.getName3();
personObj.getName4();
})();
Thanks again, and best of luck.
write one more console.log, remove one function invoked or replace return of one in function
var y = 1;
if (function f(){}) {
y += typeof f;
}
console.log(y);
I got 1object
instead of 1undefined
, might be related to this issue
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
console.log(trees); // ["redwood", "bay", "cedar", empty, "maple"]; //trees[3] is empty instead of undefined on chrome
Here associativity of the assignment operator is Right to Left so first typeof y will evaluate first which is undefined and assigned to z and then y would be assigned the value of z and then z would be assign value 1.
z should be assign the value of y which is undefined
Question 3. What is the drawback of creating true private in JavaScript?
The "solution" says each copy of Employee
will have its own copy of the increaseSalary
and that such an implementation would be poor for memory. While that is true, it is also true that each instance of Employee
would also have it's own copy of any properties or methods added to this
. So in the case of your example, for the purposes of memory, increaseSalary
is no different from dispalyIncreasedSalary
in terms of memory consumption.
To actually be more memory efficient, one would want to put common properties and methods on the Employee
prototype.
https://stackoverflow.com/questions/8433459/what-s-the-purpose-of-prototype
Question 5 and 24 are the same
In 'Question 44. Write a log function which will add prefix (your message) to every message you log using console.log ?', shouldn't appLog("Some error message")
be enough as a final statement instead of console.log(appLog("Some error message"))
?
In Q31, we have
function Clone(object){
var newObject = {};
for(var key in object){
newObject[key] = object[key];
}
return newObject;
}
var objectLit = {foo : 'Bar'};
var cloneObj = Clone(obj); // Clone is the function which you have to write
console.log(cloneObj === Clone(objectLit)); // this should return false
console.log(cloneObj == Clone(objectLit)); // this should return true
where does the obj
come from in var cloneObj = Clone(obj)
?
should A == B
be the same as A === B
when both A
and B
are objects? why the last two lines have different outputs?
Thanks.
I think the variable ‘location‘ may need to change a value,otherwise the page will redirect.
It is a good idea to include a PDF version of the questions to be generated automatically with Github actions.
I have created a PR for this here:
I debug this question, find it will be more interesting to add the following example:
var salary = "1000$";
(function () {
console.log("Original salary was " + salary);
let salary = "5000$";
console.log("My New Salary " + salary);
})();
this example can emphasis the concept of 'hoist'. Somebody say 'let' or 'const' has no hoisting. But in fact it's not.
Isn't this can be another way of finding the difference between array and object :
function greet(param){
if(param.push!=undefined){
//@ this is array
}else{
//@ other differences OR Object
}
greet([5])
greet({a:5})
Hi, thanks for the questionnaire!
A small correction:
// Create non-enumerable property
Object.defineProperty(person, 'phoneNo',{
value : '8888888888',
enumerable: false
})
Changing non-enumerable property value will return error in strict mode. In non-strict mode it won't through any error but it won't change the value of phoneNo.
Value of phoneNo won't change because 'writable' descriptor is false by default, not because 'enumerable' is false.
If you had:
Object.defineProperty(person, 'phoneNo',{
value : '8888888888',
enumerable: false,
writable: true,
})
you would be able to change property value.
Hi Nishant! I am really learning lots from your repo, but I noticed that questions 30 and 32 in the readme, and the exact same question repeated.
Just letting you know, everything else is amazing!
In answer is lost second undefined
log for console.log(obj.innerMessage());
I suggest leaving only function call.
function User(name) {
this.name = name || "JsGeeks";
}
var person;
var foo = User("xyz") // should be new User("xyz")
I couldn't find much activity in this repository for the last few months. There are quite a few issues and pull requests pending, which didn't receive any attention.
@nishant8BITS What are your thoughts regarding this? I understand that this was also meant to be released as a commercial project, and you are probably unable to spend more time on the repo.
I consider this project to be a very important resource for interviews and have greatly benefited from it. I would be really happy to help out with the maintenance if you would like that.
I believe the definition of a closure as "a function defined inside another function..." is not particularly correct. A closure is a function + lexical environment it's bound to. It doesn't necessary require an outer function.
See also https://stackoverflow.com/questions/50529400/is-the-definition-of-javascript-closures-on-mdn-wrong
emp1
, emp2
, emp3
and displayIncreasedSalary
are all mentioned in the explanation of the example in question 3, but not actually mentioned in the example
For the function expression in Q2
var myFunc1 = new function() {}
var myFunc2 = new function whatever() {} // whatever is not a variable here
I think it would be better to use something like the code below to distinguish the 'function' and the 'Function' object
var myFunc1 = function() {}
var myFunc2 = function whatever() {}
var myFunc3 = new Function ('a', 'b', 'return a+b')
Sorry, I don't understand why using new function(...) {...} rather than new Function()
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.