JavaScript Mock Interview | Online Interview Questions and Answers
Vložit
- čas přidán 6. 09. 2024
- Online Technical Mock Interview of one of my viewers. Where I ask JavaScript Fundamental Questions and give their answers.
If you like to be mock interviewed, email me at
* info@interviewnest.com
Please be my patreons on patreaon
* / techsith
Follow me for technology updates
* / techsith
* / techsith1
Help me translate this video.
*
Note: use translate.goog... to translate this video to your language. Let me know once you do that so i can give you credit. Thank you in advance.
He's totally ready to get a good JS job :) he thinks fast, knows his stuff, and follow good practices. Maybe he just needs to get out of that "I only do ES6" mentality, as real world programming might require him to be able to deal with ES5 just as well (for legacy browser support, legacy code, or whatever).
This mock interviews are great, not only for the interviewee, but for everyone trying to check his level and better prepare for actual job interviews. Thanks for taking the time to do this! :)
This guy is definitely a senior dev
Great point! Interesting he is mostly questioning about OOP in JS.
@@rogerh2694 1 year of experience. Probably he's still a junior, but he definetely knows what's up
Hi bro , I got offer letter from CTS yesterday, joining date as Oct 8 2018. I start to watch ur video tutorial last two days before interview. Really it helpful... Same questions I got in interview, thank you bro
Exactly same happened with me .
@@khyatichoprakc kitna year experience the bhai
@@AnshulJain-sj1lu I have 5+ years of experience and i got selected in one of the Big 4. These videos are superb.
Awesome !!! Please continue this series . Worth watching and learning. Keep up the good job Sir. Waiting for more such videos and others like React and React Native. :-)
3:10 he was so close, only needed to use Object.values instead of Object.entries. Still nice to see he could quickly think of another approach with a simple function, even if he didn't know the native method for doing that
Yeah I was thinking the same way, would it be enough?
Nice to have a backup, but it was wrong. That loop was creating an array of the keys, not the values.
@@RKkuba using: for ( let i in obj) { xArr.push (obj[i]) } would have worked as well.
Simplest and cleanest solution at 27:00 is this:
const a = [1,2,5,7,9];
const b = [2,5,7,12,100];
const c = a.concat(b);
let x = c.sort(function(a,b){return a-b});
console.log(x)
What an awesome format! Please proceed with this, interesting, thanks a lot!
Noticed people asking about the sorting one. I think this will work. It only checks the smallest array then just smacks together the rest of the larger array since its pre-sorted for minimal checks.
let arr = [2,5,7,12,100,101,103,432,566,765,865,987,999];
let arrb = [1,2,5,7,9];
let j = 0;
let i = 0;
if(arr.length > arrb.length){
[arr,arrb] = [arrb,arr];
}
let ans = [];
while(j
I'd say my general knowledge of javascript is much lower than you guys but I managed to figure out the one starting at 15:48 by just bashing my head against the keyboard until I finally figured it out.
Here's a correct way to write it or at least how I wrote it so that newB.getX() and newB.getY() works:
// constructors
const a = function(x) {
this.x = x;
};
const b = function(x, y){
this.y = y;
a.call(this,x);
};
// building my own prototypes
b.prototype.getX = function(){
return this.x
}
b.prototype.getY = function(){
return this.y
}
//this line creates a "new b" so that any prototypes you make for a.prototype won't work on it (at // least they didn't work on a.prototype.getX = function() {
// return this.x
//} ) newB.getX() throws an error here
const newB = new b('x', 'y');
>newB.getX()
newB.getY()
Thank you for this video. I have been using all of your videos as study guides for my technical frontend developer interview and I aced it!
great. I feel good knowing that. :)
At 14:00 i would do it this way:
if(!Array.prototype.print){
Array.prototype.print = function() {
console.log(this.join(','));
}
}
Nuce solution. Thanks buddy.
why is this if(!Array.prototype.print) needed, also why won't my solution work without it on repl ide?
@@Snugglelol Х.З. so just it will be
correct answer - ... [a, b] = this;
console.log(`${a},${b}`);...
Thats what i was thinking
Question with contact and sorting array. Is very simple question. I can just say that person being interviewed isn't familiar with sorting algorithms. If he knew a MergeSort the answer is simple. Just make a function like this
const sortedMerge = function(a, b){
let i = 0;
let j = 0;
let result = [];
while (i < a.length && j < b.length) {
if(a[i] < b[j] || a[i] === b[j]){
result.push(a[i]);
i++;
}
else if(b[j] < a[i]){
result.push(b[j]);
j++;
}
};
while (i < a.length) {
result.push(a[i]);
i++
};
while (j < b.length) {
result.push(b[j]);
j++
}
return result;
};
for asc sort() array you need ```a.concat(b).sort( (a,b) => a - b )```
You have taken a great step to teach the beginners. Absolutely amazing.
33:45 simple solution is const c = [...a,...b].sort((a,b)=>a-b); using spread operators and sorting the array
yes thats correct but he didnt want him to use sorting in this situation
WOW, awesome series.
Here is one thing I want to point out. The print method on array prototype will not work because of arrow function implementation where "this" simply refers to windows object, not the value in which method is called. We have to use normal function syntax in that case I guess.
I'm in love with your channel contents.
Yes do not use arrow function in that example it doesn't bind with the object.
so I came up(with the help of reddit) a solution for the global method at 10:20
//Correct solution
Array.prototype.print = function() {
console.log(this.join(', '));
}
const arr = [1,2,3,4];
arr.print(); // 1, 2, 3, 4
however my original code was this one below
//Incorrect solution
Array.prototype.print = function() {
console.log(this.join(', '))
}
[1,2,3,4].print() // TypeError: Cannot read property 'print' of undefined
I still don't know 100% why it returns an error but it has something to do with that [].print isn't picking up the prototype chain, which is why assigning it to a constant in the correct solution solved it. Any thoughts/correction appreciated and keep up the awesome work :)
I would have failed this interview dratically.
This is great. I am mid level js programmer and let be honest I learnt cool new things from this interview.
for the inner.call(this), it is actually the right answer!
Seeing this video makes me feel like I have to go over all the javascript videos again ps I always watch every ad on your videos. Great as usual
Thanks for watching the ads . Feel free to ask any questions if you ever need my help. Keep learning!
I have been programming as a hobby for around 4 years, mostly games, but no finished projects. I recently decided to get serious and make it a career. I have been extremely intimidated because I have no formal training. If this guy is a 9/10, I am putting in applications tomorrow. Thank you for these videos.
Also, I think I will put in an email to get in the hotseat here if you still do these mock interviews.
Feel free to send me a reqest for a mock interview on techlover2000@gmail
14:35 to get the index and the value of the array you need to use this.entries() otherwise will throw error. should be: let [i,elem] of this.entries()
Answer for the question in the video at 17:09 const a= function(x){
this.x=x;
this.getX=function(){
return this.x;
}
}
const b=function(x, y){
a.call(this,x);
this.y=y;
this.getY=function(){
return this.y;
}
}
b.prototype=a.prototype;
b.prototype.constructor=b.prototype.constructor;
const newB = new b('x', 'y');
console.log(newB.getX());
console.log(newB.getY());
I think that the answer with the print() method on the prototype is wrong, because using arrow function there will cause the this keyword point to the window obejct not the actual array bc its lexicaly scoped. He should use plain function like Array.prototype.print = function(){this.map(e => console.log(e)} instead.
That is a correct. Thanks for sharing :)
Array.prototype.print = function() { return this.join(',') }
Also he should have used if(i === this.lenght-1). It never makes it to this.length!
If it's not important to console.log, this question screams:
Array.prototype.print = Array.prototype.toString
I have also noticed that arrow functions don't go so well with prototype functions. Thanks for bringing this to the limelight. 🙏🏿
For the first, it withh give an array of the prop ([a,b])
It is hsould be arr.push(obj[i])
Should have been Object.values(x)
@@77y7 There are multiple ways... that's one of them.
my solutions
//first question:
let x = {
a: 1,
b: 2
};
let arr1=[];
Object.keys(x).map((x1,id) => (
arr1[id] = x1
));
console.log(arr1);
// 2nd question
let x = "hi"
//let y = "id"
let y=""
for (let i = x.length - 1; i >= 0; i--) {
y= y+ x.charAt(i)
}
console.log(y)
good solution syyam :)
It is important to note that in the question with the print function, It's important to solve this question with a regular function statement because an arrow function doesn't keep the this and points to the window object, so it won't work.
This is helpful as it more clearly identifies my weaknesses. Two thumbs up. This seems like a no brainer winner for your channel.
It was a good experiment. To give in-sight into how to answer and what to answer.
Instead of using inner.call in the last question which shows error use inner.bind(this)()
For the merge of two array...
const arr22=[2,3,5,9,6];
const arr33=[7,8,4,66,45,28,75,34,21,69,54,34];
const arr44=[];
arr22.map((val,ind)=>{
arr44.push(val,arr33[ind]);
});
arr44.push(arr33.slice(arr22.length));
console.log(arr44.flat());
The answer for the first question seems like correct one, but for some reason from the same code as on video I'm getting array of key pairs instead of values.
let x = {
a: 1,
b: 2
};
const arr = [];
for (let i in x) {
arr.push(i);
// console.log(i);
}
console.log(arr);
// returns: ["a","b"]
One of solutions is to use Object.values:
var obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // returns ['bar', 42]
Other Solution is to use "i" in "x" object as an index.
let x = {
a: 1,
b: 2
};
const arr = [];
for (let i in x) {
arr.push(x[i]);
// console.log(i);
}
console.log(arr); // returns [1,2]
Thanks for sharing your solutions. :)
@@Techsithtube thank you Sir, for making such awesome videos
14:00 won't work, because you are defining the Array.protype.print with an arrow function, so "this" is reffering to the global object.
Thanks for this comment bro...!!!! It helped me :)
I was about to comment on that. Just change to basic function and console.log(this). That's all.
One more thing, arrow functions inside object are a bad idea.
Awesome video! He really knows his stuff!
He sure does, exceeded my expectations.
You guys sure the solution at 14:50 works? I think it needs three modifications: 1) if (i === this.length - 1) 2) for (const [i, elem] of this.entries()) and 3) the function needs not to be an arrow expression, since the binding to this refers to the arrow function and not the object instance.
I really enjoyed this. The one thing I would do different is the [1,2].print(); // 1,2 problem. I would extend the Array object using a class rather than changing the Array.prototype object. By creating a new class that extends the Array object, you can also add additional methods for working with your array, and you still have access to all of the Array methods. For example:
const xArr = [1,2,3,4,5]
class Modify extends Array {
print() {
console.log(this.toString());
}
}
const arr = new Modify(...xArr);
If you were to add additional methods, you would just add a constructor function, like so:
class Modify extends Array {
constructor(...args) {
super(...args);
this.last = this[this.length-1];
}
print() {
console.log(this.toString());
}
}
After watching this i am feeling like i don't even know beginner level javascript. Have to practice more.
liked the coding competition between interviewer and the interviewee!
Just a small workaround for deep cloning. Works for only objects not for arrays.
function clone(ob){
let newObj={},value;
for(let key in ob){
value=ob[key]
newObj[key]=(typeof value === 'object') ? clone(value):value;
}
return newObj;
}
short and sweet. thanks for sharing
Wish I can like this video 1000 times :) I kept coming back to watch this!
Thanks for a nice comment;)
love these. I had a technical phone screening and i bombed so hard. Now I have better idea what to expect thanks.
Keep up the good work and good luck with the interviews.
every question is unic n creative way of explaination. we never ever seen this kind of heavy stuff in javascript
at 12:00 we need to use classical function expression, can't use fat arrow functions and we need to declare a variable so this keyword will be bind to it:
Array.prototype.print = function(){
console.log(this.toString())
}
let arr = [1, 2, 3]
arr.print()
sorting two arrays in an optimal way what i could think of is :-
const a = [1, 2, 5, 7, 9];
const b = [2, 5, 7, 12, 100, 105, 123];
let sortedArr = [];
let x = 0;
let y = 0;
for (let i = 0; i < a.length * 2; i++) {
if (a[x] < b[y]) {
sortedArr.push(a[x]);
x++;
} else {
sortedArr.push(b[y]);
y++;
}
}
console.log(sortedArr.concat(b.slice(a.length - 1)));
Good solution. :)
let x = {
a:1,
b:2
}
let values = function(obj){
let result = Object.values(obj)
return result
}
console.log(values(x))
2nd last question that you have ask him that merge two arrays and sort them as well, so can we use the spread operator [...a, ...b]; after that we can sort it.
I watched your Videos night before my interview. And boom .... i joined Big 4 Company 💯 This is actually realistic and beneficial. I checked the comments, many people have got offer from good MNCs like me. Gratitude & Grateful to you Sir .
Fantastic! Kyati, congratulations on your new Job. Keep on learning! I am glad the videos helped! :)
At 21:55 the getter inside b will not work because method notation doesn't work inside functions, only inside objects.
Hello Sir,
A humble request if you can provide the most optimum and efficient answers for each question with some explanation.
That would be great.
Awesome Work!!! Worth every second watching. Awaiting more mockups like this. Thanks for sharing.
At 23:47 for cloning an object with a new value for c, use ES6 spread operator (…). const clone = {...obj, a: {b: {c: 2}}};
Yep , that is how you do it.
We can clone object with below approach
const objToClone = {
a:{
b:{
c:1
}
}
}
const anotherObjectwithoutReference = {...objToClone}
anotherObjectwithoutReference.a = 9;
console.log(JSON.stringify(objToClone))
An alternative to question 1:
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.values(object1));
// expected output: Array ["somestring", 42, false]
Good One.
In real life, this guy is not going to get the job. People are crazy now. I solved a very complex program which will take at least a few hours for a more junior Enigneer. Including retrieving API, parsing, sorting, paginating. Complex graphic requirement, loading states, field validations within less than 40 mins. I finished way before 40 mins, clean up the code, did more requirements from the interviewers. And still she is not happy about it. I am just speechless. You need to be a god to ask no questions. A few interviewers just gone missing after giving you the questions. I think youtuber needs to do some videos on how a real coding interview is like:
1. They roll their eyes when talking to you or looked like you killed their mother (most of the time). I meet one who is friendly
2. They are not at all happy doing the interviews
3. They stay very silence as if gone and not answering your questions unless you asked twice
4. When you solved the problem, they didn't say it is good. They just add more questions asking you to solve until you ran out of time and say Opps, out of time
5. They remove weird thing in the code: such as a single return word randomly somewhere and made you spent time to look for this tiny set up bug
6. If you did really well, finished up the problems way before time, they get very angry and start calling you, "Guess you are the Senior Software Engineer'. The next thing you heard back is they dont want to move forward???!!!
7. And if you can't solve the problem that's when they lightened up and smiled
I think many Engineers at work are extremely paranoid they will get replaced. So, that's why they act like this. Some bigger companies provide feedback, so candidates who felt mis-treated should speak up.
At 34:57, can we use spread operator ?
const a = [1,2,3,4,9,8];
const b = [3,2,3,7,9,8];
const c = [...a, ...b];
c.sort();
yes you can use the spread operator here.
function print(arr){return console.log(arr.toString())}
that's not modifying the prototype, which is what the interviewer guy was asking for
i think for the question of regrouping the two arrays we could simply do let x = [...a,...b].sort()
That is a clean answer Mr Miiz
3:51 will give ["a", "b"]. I guess we need to use for(i in x){xArr.push(x[i]); } to get the values.
yes that is correct
Object.keys(x).forEach((element)=>xArr.push(x[element]));
@@ultimatehuzefa var xRay = Object.values(x)
Just as a heads up: The code from question 10:04 will not run because it's using an arrow function. The "this" is bound to the window object, not the input of the array method. It needs to be a ES5 function, not ES6.
Thanks a lot mate. I was confused in this. But once I learned that if we are using this in an arrow function, in that case, this binds to the object ( suppose I am talking about the case of nested functions ), What will you say about this?
correct.. I also thought the same.. because of the arrow function 'this' will be referred as 'Window' object. it should be function (){} representation.. another thing is as the print() is called before it is defined.. it will throw 'not a function' error because print is a function expression .In order to make it work the function call should be after it is defined.
At 14 minutes, you do not want to use an arrow function. It would take the current context and pass it into the function, in other words, it binds this, so this would represent the outer context rather than the array.
Yep , that is a good solution. thanks for sharing
For merging array and sort , I'd do this simpler way using spread operator
const result = [...a,...b].sort((a,b)=>a-b);
the last question wasn't asked right
the code will give "1" as he said
but this code will give undefined
const obj = {
x:1,
getX(){
const inner = function(){
console.log(this.x)
}
inner();
}
}
obj.getX();
so there are four solutions you can do
1- the code you have posted
2- assign this to new variable before inner funtcion
3- use inner.call(this)
4-use inner.bind(this)
greatings :) :)
Great initiative for JS learners and who are seeking JS jobs. Keep it up. All the best.
Please try to capture clear sound of the interviewee.
I have learned a lot by all your JS videos. Keep it up. Really great job Sir...Thanks Sir.
He did pretty well for a beginner
I like these videos, it gives me some actual "interview" (mock or not) practice that isn't leetcode (whose questions can be unrealistic at times).
your interview is awesome.so helpful for freshers.kindly try to give more explanation on each question. keep going on further.
correct Answer for 14:00 is
Array.prototype.print = function() {
console.log(...this.join(','));
// OR console.log(this.toString());
// OR console.log(String(this));
}
Array.from([1,2]).print();
this in Arrow function will have reference to global scope and not the array the function is called upon
or to remove the trailing comma call result.slice(0, result.length-1)
This is a perfect mock interview. Great job
You can just minus the last ',' in the end, however, this would refer to the Window object, not the array, i tested it in the console.
First question on how to get values from an object. The solution would have only return the properties: a, b. should be: xArr.push(x[i]) which would return the values: 1, 2 . Object.values(x) would also return values: 1, 2.
Object.values is the shortest answer
I think he did really well given he basically has no real world experience. But, it's like taking a computer science grad and putting him into a professional setting. He might have all this great knowledge, but zero know-how of how to actually work on a team, in a production codebase, and in code that was written with bias and various styles. It's great that he can figure out how to fix a 'this' context issue, but how many times have I had to do that in my 4 years of professional coding....ZERO!. I worked with someone like this previously, had great theoretical knowledge, but could not work with a team. He ended up getting fired for this reason. This is why coding interviews are BROKEN! We need to be asking not only theoretical interview questions, but also practical ones as well. Let him dive into some production code and figure out a small bug, something that he might do in his first few weeks on a job. Put him into the deep end where he couldn't have practiced and memorized theory and see how he handles it! The true test of a successful developer in my mind.
thank you so much for these sessions sir. I suck at JS interviews and I find this really helpful.
41:00 call works as well if you do it without trying to call the result (inner.call(this))
14:55 'this' won't work here if it's an arrow function. all u get is undefined.
yep. Should not have used arrow function there.
Why does that happen though? I faced the same issue.
@@arpitbajpai6984 Arrow functions "don't have a 'this' by default". So when calling them they dont provide their own binding for 'this', instead 'this' stays the lexical context they are called in. If you want 'this' in a function to automatically be binded to the object the function is called on, use regular function.
My day ends with your video. Thank you so much sir for this wonderful experience
Again , thanks for watching!
const reverse = (str) => {
if(str.length < 2){
return str;
}
return str[str.length - 1] + reverse(str.substring(0, str.length - 1));
};
At 14:05, is it possible to declare variables in for of loop? I'm getting error for this example.
const a = [1, 2, 5, 7, 9]
const b = [2, 5, 7, 12, 100]
// output should be [1, 2, 2, 5, 5, 7, 7, 9, 12, 100]
const c = [...a, ...b].sort((a, b) => {
return a - b;
})
console.log(c)
here's my solution at 10:20 hope this helps :)
Array.prototype.print = function() {
console.log(this.join(', '));
}
const arr = [1,2,3,4];
arr.print();
That is a correct solution Thanks. :)
@39:58 we can use bind as well
Yes you can use bind aswell
//get the values from object as Array
let x = {
a: 1,
b: 2
}
const xArr = Object.values(x)
console.log(xArr)
Sir, we can also clone object using spread operator right ??
JSON.stringify({ key: undefined });
JSON.stringify({ key: Symbol() });
JSON.stringify({ key: function(){} });
// all will be converted to just "{}"
I believe it would have been pointed out before only as I'm watching this after 2years from the time it was published :D
At 14:00, the code should not work as expected as 'this' keyword is being used under the arrow function which will provide the scope of the Window object and not the Array. So, instead of the arrow function, Array.prototype.print = function(){} can be used.
Sir last question when i try to execute i got diffreant output I don't know how: such as
let hello ={
x:1,
getXn(){
const inner = function(){
console.log(this.x)
}
inner();
}
};
hello.getXn()
output which got :-
Awesome job Sir, amazing idea of sharing knowledge ,great efforts ..thanks a lot and please continue as this is very helpful
29:28 the answer is wrong by using a>b in sort method its output is : [1, 2, 5, 7, 9, 2, 5, 7, 12, 100] and its not sorted properly , instead we should put a-b to have : [1, 2, 2, 5, 5, 7, 7, 9, 12, 100]. Thanks guys
at 3:55 it should be
let xArr = []
for(let i in x){
arr.push(x[i])
}
Damian, thanks for sharing the solution
function print(){
let arr=[1,2]
if(arr.length > 0){
console.log(`${arr[0]},${arr[1]}`);
}
}
print();
here also same output we got....
I have my interview this Friday, your videos are great and help me to boost my confidence. Thanks!
Good luck with your interview. :)
How did it go?
@@thatoneuser8600 It was 2 year ago, so since then I already had several interview. And after each of them I got a job offer so it seems that these videos really help :)
@@creativemember damn that's good to hear! Right now I only know Git basics, Java, HTML, and I'm learning CSS layout + Sass right now. I don't know JavaScript, HTTP, any SQL, or any frameworks yet, so I'm pretty sure I still have a long way to go. I can only hope to be as consistent as you 🙏
@@thatoneuser8600 If I did it, anyone can do it. The amount of knowledge that you need to aquire to start working as a developer can be quite overwhelming so I would suggest focusing first on front end or back end instead of trying to be full stack developer from the very begining. I have focused on frontend and minimum what you need is git, java script, html, css/scss and a framework (most often angular / react). This is just advice, you know best what serves you :) Good luck!
3:58 shouldn't it be pushing x[i] instead of just i? Just pushing i would push the key, not the value, resulting in a and b instead of 1 and 2
You are right it should have been x[i] not just i.
this is my answer :
Array.prototype.print = function () {
this.forEach((value) => console.log(value));
};
//reverse the string
let x = "hi";
let y = x.split('').reverse().join('');
console.log(y)
14:58 The way he made an arrow function would not work, in this case this would point to the parents scope and not the array as we want.
const a=[1,2,5,7,9];
const b=[2,5,7,12,100];
const c= a.join('') + b.join('');
const d=c.split('').map(Number).sort();
console.log(d);
sir is this good algo?
Only legends in JS know that arrow function will fail for question at 15:00
The fix is using regular function expression
19:37 It seems that in a Function constructor we should use "this" and dot (.) before a function, then I think it should be this.getX = function(){}.
Hoc, that is correct , in function constructor we need to use this.getX = function(){}
This stuff is helpful. I almost think I should start my own channel to help teach and better learn myself :-P
Let me know I can help you create your own channel.
Woww. Such a good time watching this video and learning new stuff.
Please continue this series.
Mock or questions on Angular is very much appreciated 🙂
Angular mock questions is very high in demand. I will try to make one. thanks for suggestion.
@@Techsithtube Thank you man. Looking forward to it
This is really a great thing you are doing. Its really helping me to practice for the interviews. I have started watching your videos and till now its been a great experience. Hopefully i will crack any interview.
Thanks for putting out such a great content :D
Good luck Vinay. Work hard and you will crack it.
Thank you sir I will surely try my best :)