-
Notifications
You must be signed in to change notification settings - Fork 1
/
js2.html
809 lines (771 loc) · 47.6 KB
/
js2.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="javascript interview question, front end interview, front end interview preparation, front end interview questions">
<meta name="that js dude" content="">
<title>JS: Basics and Tricky Questions</title>
<link rel="shortcut icon" href="images/favicon.jpg">
<link rel="stylesheet" href="css/bootstrap.min.css" >
<link rel="stylesheet" href="css/zenburn.css">
<!-- Custom styles for this template -->
<style>
/* Move down content because we have a fixed navbar that is 50px tall */
body {
padding-bottom: 20px;
}
.purpleBold{
color:purple;
font-weight: bold;
}
.gray{
color: gray;
}
.blueish{
color: rgba(151, 182, 209, 0.98);
}
.singInStuff{
margin-top: 9px;
}
#uName{
margin-top: -7px;
}
.skipListItem{
list-style-type: none;
}
.skipListItem a{
color: inherit;
}
a:visited
{
color: rgba(218, 209, 149, 0.98);
}
.imageContainer{
overflow: hidden;
margin: 1% 0 1% 0;
}
.imageHolder{
float: left;
padding: 1%;
margin: 0 1%;
border: 10px solid #f5f5f5;
border-radius: 8px;
}
.imageHolder img{
max-height: 180px;
height: 180px;
width: 280px;
float: left;
}
.imgTitleHolder{
margin: 0 0 0 8%;
}
.imageHolder .imageTitle{
font-weight: bold;
font-size: 1.2em;
}
.toggleContent{
padding: 10px;
}
/*style for demo*/
</style>
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="docs-assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
<h1>JS: Basics and Tricky Questions</h1>
<h2>Part -2: intermediate</h2>
<p>June 22, 2014</p>
<div id="fb-root"></div><div class="fb-like" data-href="http://www.thatjsdude.com/interview/js2.html" data-layout="button_count" data-action="like" data-show-faces="false" data-share="false"></div> <div class="g-plusone"></div>
</div>
</div>
<div class="container">
<!-- Example row of columns -->
<div class="row center">
<!-- <iframe width="853" height="480" src="//www.youtube.com/embed/Rx_JFOSxgpY" frameborder="0" allowfullscreen></iframe> -->
</div>
<div>
<h4>List of Questions</h4>
<ol>
<li><a href="#nullVsUndefined">What are the differences between <code>null</code> and <code>undefined</code>?</a></li>
<li><a href="#doubleVsTripleEqual">What are the differences between <code>==</code> and <code>===</code>?</a></li>
<li><a href="#objectEquality">How would you compare two objects in JavaScript?</a></li>
<li><a href="#trueLies">11+ true false related questions that will trick you.</a></li>
<li><a href="#truthyVsEqality">As <code>[]</code> is true, <code>[]==true</code> should also be true. right?</a></li>
<li><a href="#extendObject">How could you write a method on instance of a date which will give you next day?</a></li>
<li class="skipListItem"><a href="#extendObject">If i have a <code>var str = 'hello world'</code>, how could i get <code>str.reverse()</code> return 'dlrow olleh'?</a></li>
<li class="skipListItem"><a href="#extendObject">How could you make this work [1,2,3,4,5].duplicator(); // [1,2,3,4,5,1,2,3,4,5] ?</a></li>
<li value="7"><a href="#bindthis">If you want to use an arbitrary object as value of this, how will you do that?</a></li>
<li class="skipListItem"><a href="#bindthis"> If an older browser dont have bind function, how will you shim it</a></li>
<li value="8"><a href="#call">Write a simple function to tell whether 2 is passed as parameter or not?</a></li>
<li><a href="#apply">How could you use Math.max to find the max value in an array?</a></li>
<li><a href="#this">What the heck is this in JavaScript?</a></li>
<li><a href="#rapidFire">21+ small but tricky questions</a></li>
<li><a href="#insertSpace">How could you set a prefix before everything you log? for example, if you log('my message') it will log: "(app) my message"</a></li>
<li><a href="#scopeAndHoisting">What will you see in the console for the following example?</a></li>
<li><a href="#closure">Look at the code below, you have a for loop if you have setTimeout inside it. If log the loop counter inside setTimeout, what will be logged?</a></li>
<li><a href="#deleteProperty">Look at the code below, I have a property in a object and I am creating a new object where I am setting it to a new value. If I delete that property what will i get if I try to access that property?</a></li>
<li><a href="#byValueByRef">Does JavaScript pass parameter by value or by reference?</a></li>
<li><a href="#memoization">How could you implement cache to save calculation time for a recursive fibonacci function?</a></li>
<li><a href="#cacheFunction">How could you cache execution of any function?</a></li>
<li><a href="#chianing">If you need to implement the following chaining with call back, how will you implement it?</a></li>
<li><a href="#animation">How could you implement moveLeft animation?</a></li>
<li><a href="#currying">How would you implement currying for any functions?</a></li>
</ol>
</div>
<!-- <p class="gray">if you are little more comfortable or claim to be comfortable with javascript, these questions would not be enough for you. more coming</p>-->
<p class="gray"> <span class="purpleBold">More Questions: </span><a href="js1.html">Algorithm related questions</a>, <a href="dom.html">dom related</a>, <a href="css.html">css related</a>, <a href="html.html">html related</a> </p>
<div id="nullVsUndefined">
<h2>1. null vs undefined</h2>
<p><strong>Question: </strong> What are the differences between <code>null</code> and <code>undefined</code>?</p>
<p><strong>Answer:</strong> JavaScript has two distinct values for nothing, null and undefined.</p>
<h4>undefined</h4>
<p><code>undefined</code> means, value of the variable is not defined. JavaScript has a global variable <code>undefined</code> whose value is "undefined" and <code>typeof undefined</code> is also "undefined". Remember, undefined is not a constant or a keyword. undefined is a type with exactly one value: undefined. Assigning a new value to it does not change the value of the type undefined.</p>
<strong>8 Ways to get Undefined:</strong>
<ul>
<li>A declared variable without assigning any value to it.</li>
<li>Implicit returns of functions due to missing return statements.</li>
<li>return statements that do not explicitly return anything.</li>
<li>Lookups of non-existent properties in an object.</li>
<li>Function parameters that have not passed.</li>
<li>Anything that has been set to the value of undefined.</li>
<li>Any expression in the form of void(expression)</li>
<li>The value of the global variable <code>undefined</code></li>
</ul>
<h4>null</h4>
<p><code>null</code> means empty or non-existent value which is used by programmers to indicate “no value”. null is a primitive value and you can assign null to any variable. null is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because typeof null returns "object".</p>
<p>Btw, <code>null == undefined</code> ref: <a href="http://www.2ality.com/2013/10/typeof-null.html">history of typeof null</a></p>
</div>
<div id="doubleVsTripleEqual">
<h2>2. == Vs ===</h2>
<p><strong>Question:</strong> What are the differences between <code>==</code> and <code>===</code>?</p>
<p><strong>Answer: </strong> The simplest way of saying it is that == will not check types and === will check whether both sides are of the same type. So, == is tolerant. But under the hood it converts to a convenient type, in order to have both as the same type, and then does the comparison.</p>
<p>=== compares the types and values. Hence, if both sides are not same type, the answer is always false. For example, if you are comparing two strings, they must have identical character sets. For other primitives (number, boolean), they must share the same value.</p>
<p><strong>Rule for implicit coercion:</strong> Comparison by using == does implicit type conversion under the hood. The rules for implicit coercion are as follows-</p>
<ul>
<li>If both operands are same type use ===</li>
<li>undefined == null</li>
<li>If one operands is string another is number, convert string to number</li>
<li>If one is boolean and another is non-boolean, convert boolean to number and then perform comparison</li>
<li>While comparing a string or number to an object, try to convert the object to a primitive type and then try to compare</li>
</ul>
<p>Be careful while comparing objects — identifiers must reference the same objects or same array.</p>
<pre><code>
var a = {a: 1};
var b = {a: 1};
a == b //false
a === b //false
var c = a;
a == c//true
a === c //true
</code></pre>
<p>Special note: NaN, null and undefined will never === another type. NaN does not even === itself.</p>
<p><strong>Homework:</strong> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN"> Read confusing special cases of NaN</a></p>
</div>
<div id="objectEquality">
<h2>3. Object Equality</h2>
<p><strong>Question: </strong> How would you compare two objects in JavaScript?</p>
<p><strong>Basics:</strong> JavaScript has two different approaches for testing equality. Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and user defined objects are compared by their reference. This means it compares whether two objects are referring to the same location in memory.</p>
<p><strong>Answer:</strong> Equality check will check whether two objects have the same value for the same property. To check that, you can get the keys for both the objects. If the number of properties doesn't match, these two objects are not equal. Secondly, you will check whether each property has the same value in both objects. If all the properties have the same value, they are equal.</p>
<pre><code>
function isEqual(a, b) {
var aProps = Object.getOwnPropertyNames(a),
bProps = Object.getOwnPropertyNames(b);
if (aProps.length != bProps.length) {
return false;
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
if (a[propName] !== b[propName]) {
return false;
}
}
return true;
}
</code></pre>
<strong>Limitation:</strong>
<ul>
<li>If one of the property values is itself an object</li>
<li>If one of the property values is NaN (the only value in JavaScript that is not equal to itself?)</li>
<li>If one object has a property with value undefined, while another object doesn't have the property (which thus evaluates as undefined). Btw, you can solve this problem by using hasOwnProperty</li>
</ul>
<p>ref: <a href="http://designpepper.com/blog/drips/object-equality-in-javascript.html">object equality in JS</a>, <a href="http://underscorejs.org/docs/underscore.html#section-90">Underscore.js isEqual function</a></p>
</div>
<div id="trueLies">
<h2>4. True Lies</h2>
<p><strong>Question:</strong> 11+ true false related questions that will trick you.</p>
<p><strong>falsy:</strong> In javascript 6 things are falsy and they are- false, null, undefined, '', 0, NaN</p>
<p><strong>truthy:</strong> There are only two truthy things- true and everything that is not false</p>
<div>
<h3>True False Rapid Fire</h3>
<div id="trueFalseRapidExample" class="bg-success toggleContent">
<p><strong>Question:</strong> Is <code>'false'</code> is false?</p>
<p><strong>Answer:</strong> No. Because, it's a string with length greater than 0. Only empty string is false.</p>
<p><strong>Question:</strong> Is <code>' '</code> is false?</p>
<p><strong>Answer:</strong> No. Because, it's not an empty string. There is a white space in it. </p>
<p><strong>Question: </strong>What about <code>{}</code>?</p>
<p><strong>Answer: </strong>true. It's an object. An object without any property is an object can't be falsy.</p>
<p><strong>Question: </strong>Tell me about <code>[]</code>?</p>
<p><strong>Answer: </strong> This is also truthy. It's an array object (array is child of object) is truthy.</p>
<p><strong>Question: </strong>You talked bout <code>''</code> to be falsy. What about <code>new String('')</code>? </p>
<p><strong>Answer:</strong> Though you are passing empty string to the string constructor, it is creating an String object. More precisely a instance of String object. It becomes an object. Hence, it is not false. so, it is truthy.</p>
<p><strong>Question:</strong> Tell me about <code>new Boolean(false)</code></p>
<p><strong>Answer:</strong> truthy. As it creates an instance of the Boolean object which is an object. Object is truthy.</p>
<p><strong>Question: </strong> <code>Boolean(function(){})</code></p>
<p><strong>Answer: </strong> <code>true</code> if you pass a truthy value to Boolean, it will be true.</p>
<p><strong>Question: </strong> <code>Boolean(/foo/)</code></p>
<p><strong>Answer: </strong> <code>true</code></p>
<P><strong>Question:</strong> <code>true%1</code></P>
<P><strong>Answer:</strong> 0. When you are trying to find reminder of true, true becomes 1 and reminder of 1 while dividing by 1 is 0. You will get same result if you do <code>false%1</code></P>
<P><strong>Question:</strong> <code>''%1</code></P>
<P><strong>Answer:</strong> 0</P>
</div>
</div>
<div id="truthyVsEqality">
<h2>5. Truthy isn't Equal to true</h2>
<p><strong>Question: </strong> As <code>[]</code> is true, <code>[]==true</code> should also be true. right?</p>
<p><strong>Answer:</strong> You are right about first part, <code>[]</code>, empty array is an object and object is always truthy. Hence, if you use <code>if([]){console.log('its true')}</code> you will see the log.</p>
<p>However, special case about <code>==</code> (double equal) is that it will do some implicit coercion.</p>
<p>Since the left and right sides of the equality are two different types, JavaScript can't compare them directly. Hence, under the hood, JavaScript will convert them to compare. First, the right side of the equality will be cooereced to a number and number of <code>true</code> would be 1.</p>
<p>After that, JavaScript implementation will try to convert <code>[]</code> by using<code>toPrimitive</code> (of JavaScript implementation). Since <code>[].valueOf</code> is not primitive, it will use <code>toString</code> and will get <code>""</code></p>
<p> Now you are comparing "" == 1 and still, the left and right are not the same type. Hence, the left side will be converted again to a number and empty string will be 0.</p>
<p>Finally, they are of same type. You are comparing <code>0 === 1</code> which will be false.</p>
<p>ref: <a href="http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/">angus croll: truth and eqality in JS</a>, ref: <a href="http://www.sitepoint.com/javascript-truthy-falsy/">truthy and falsy</a></p>
</div>
</div>
<div id="extendObject">
<h2>6. Extend Core Object</h2>
<p><strong>Question:</strong> How could you write a method on an instance of a date which will give you the next day?</p>
<p><strong>Answer:</strong> I have to declare a method on the prototype of Date object. To get access to the current value of the instance of the date, i will use <code>this</code></p>
<pre><code>
Date.prototype.nextDay = function(){
var currentDate = this.getDate();
return new Date(this.setDate(currentDate +1));
}
var date = new Date();
date; //Fri May 16 2014 20:47:14 GMT-0500 (Central Daylight Time)
date.nextDay();//Sat May 17 2014 20:47:14 GMT-0500 (Central Daylight Time)
</code></pre>
<div>
<button id = "extendCoreObjectMore" type="button" class="toggleExample btn btn-primary">Show Similar Question</button>
<div id="extendCoreObjectMoreExample" class="hide bg-success toggleContent">
<p><strong>Question: </strong> If i have a <code>var str = 'hello world'</code>, how could i get <code>str.reverse()</code> return 'dlrow olleh'? </p>
<p><strong>Answer:</strong> You have to extend the core String Object</p>
<pre><code>
String.prototype.reverse = function(){
return this.split('').reverse().join('');
}
var str = 'hello world';
str.reverse();//"dlrow olleh"
</code></pre>
<p><strong>Question: </strong> How could you make this work [1,2,3,4,5].duplicator(); // [1,2,3,4,5,1,2,3,4,5] ?</p>
<p><strong>Answer:</strong> We need to add a method in the prototype of Array object.</p>
<pre><code>
Array.prototype.duplicator = function(){
return this.concat(this);
}
[1,2,3,4,5].duplicator(); // [1,2,3,4,5,1,2,3,4,5]
</code></pre>
<p>If you don't understand, how this works. take a nap and don't come back.</p>
</div>
</div>
</div>
<div id="bindthis">
<h2>7. bind</h2>
<p><strong>Question: </strong>If you want to use an arbitrary object as value of <code>this</code>, how will you do that?</p>
<p><strong>Answer:</strong> There are at least three different ways to doing this by using bind, call and apply. For example, I have a method named deductMontlyFee in the object monica and by default value of this would be monica inside the method.</p>
<pre><code>
var monica = {
name: 'Monica Geller',
total: 400,
deductMontlyFee: function(fee){
this.total = this.total - fee;
return this.name + ' remaining balance is '+ this.total;
}
}
</code></pre>
<p>If I bind the deductMontlyFee of monica with another object <code>rachel</code> and pass rachel as first parameter of the bind function, rachel would be the value of <code>this</code>.</p>
<pre><code>
var rachel = {name: 'Rachel Green', total: 1500};
var rachelFeeDeductor = monica.deductMonthlyFee.bind(rachel, 200);
rachelFeeDeductor(); //"Rachel Green remaining balance is 1300"
rachelFeeDeductor(); //"Rachel Green remaining balance is 1100"
</code></pre>
<p><code>bind</code> allows you to borrow a method and set the value of <code>this</code> without calling the function. It simply returns an exact copy of the function with new value of <code>this</code>. You can reuse the same function with new value of this without harming the old one.</p>
<pre><code>
var ross = {name:'Ross Geller', total:250};
var rossFeeDeductor = monica.deductMonthlyFee.bind(ross, 25);
rossFeeDeductor(); //"Ross Geller remaining balance is 225"
rossFeeDeductor(); //"Ross Geller remaining balance is 200"
rachelFeeDeductor(); //"Rachel Green remaining balance is 900"
</code></pre>
<p><strong>Question:</strong> If an older browser dont have bind function, how will you shim it</p>
<p><strong>Answer:</strong> Look at the code below and use your brain.</p>
<pre><code>
Function.prototype.bind = Function.prototype.bind || function(context){
var self = this;
return function(){
return self.apply(context, arguments);
};
}
</code></pre>
</div>
<div id="call">
<h2>8. arguments and call</h2>
<p><strong>Question:</strong> Write a simple function to tell whether 2 is passed as parameter or not?</p>
<p><strong>Basics:</strong> arguments is a local variable, available inside all functions that provides a collection of all the arguments passed to the function. <code>arguments</code> is not an array rather an array like object. It has length but doesn't have the methods like forEach, indexOf, etc. </p>
<p><strong>Answer: </strong>First convert arguments to an array by calling slice method on an array and pass arguments. After that simply use indexOf.</p>
<pre><code>
function isTwoPassed(){
var args = Array.prototype.slice.call(arguments);
return args.indexOf(2) != -1;
}
isTwoPassed(1,4) //false
isTowPassed(5,3,1,2) //true
</code></pre>
<p><strong>Danger:</strong> Don't name any argument as "arguments" or dont create any local variable named as "arguments", this will override build in arguments object.</p>
</div>
<div id="apply">
<h2>9. apply</h2>
<p><strong>Question:</strong> How could you use Math.max to find the max value in an array?</p>
<p><strong>Answer:</strong> Use apply on Math.max and pass the array as apply takes an array of arguments. Since we are not reading anything from this or using it at all. We can simply pass null as first parameter.</p>
<pre><code>
function getMax(arr){
return Math.max.apply(null, arr);
}
</code></pre>
<p><strong>Extra: </strong> call and apply, both takes the value of this as first parameter. However, call takes a collection of arguments after first parameter whereas apply use an array of arguments as second parameter.</p>
<p> <strong>Tip: </strong>If you have weaker memory like me, you can remember apply starts with "a" and array starts with "a"</p>
</div>
<div id="this">
<h2>10. this</h2>
<p><strong>Question:</strong> What the heck is <code>this</code> in JavaScript?</p>
<p><strong>Answer:</strong> At the time of execution of every function, JavaScript engine sets a property to the function called <code>this</code> which refer to the current execution context. <code>this</code> is always refer to an object and depends on how function is called. There are 7 different cases where the value of <code>this</code> varies.</p>
<ol>
<li>In the global context or inside a function this refers to the window object.</li>
<li>Inside IIFE (immediate invoking function) if you use "use strict", value of this is undefined. To pass access window inside IIFE with "use strict", you have to pass this.</li>
<li>While executing a function in the context of an object, the object becomes the value of this</li>
<li>Inside a setTimeout function, the value of this is the window object.</li>
<li>If you use a constructor (by using new keyword) to create an object, the value of this will refer to the newly created object.</li>
<li>You can set the value of this to any arbitrary object by passing the object as the first parameter of bind, call or apply</li>
<li>For dom event handler, value of this would be the element that fired the event</li>
</ol>
<p>ref: <a href="https://www.youtube.com/watch?v=yuo8YqKDQ-M">Understand JavaScript this in a crystal clear way</a></p>
</div>
<div id="rapidFire">
<h2>11. Rapid Fire</h2>
<p><strong>Question:</strong> What is <code>typeof []</code></p>
<p><strong>Answer:</strong> Object. Actually Array is derived from Object. If you want to check array use <code>Array.isArray(arr)</code></p>
<p><strong>Question:</strong> What is <code>typeof arguments</code></p>
<p><strong>Answer:</strong> Object. arguments are array like but not array. it has length, can access by index but can't push pop, etc.</p>
<p><strong>Question:</strong> What is <code>2+true</code></p>
<p><strong>Answer:</strong> 3. The plus operator between a number and a boolean or two boolean will convert boolean to number. Hence, true converts to 1 and you get result of 2+1 </p>
<p><strong>Question:</strong> What is <code>'6'+9</code></p>
<p><strong>Answer:</strong> 69. If one of the operands of the plus (+) operator is string it will convert other number or boolean to string and perform a concatenation. For the same reason, <code>"2"+true</code> will return "2true"</p>
<p><strong>Question:</strong> What is the value of <code>4+3+2+"1"</code></p>
<p><strong>Answer:</strong> 91 . The addition starts from the left, 4+3 results 7 and 7+2 is 9. So far, the plus operator is performing addition as both the operands are number. After that 9 + "1" where one of the operands is string and plus operator will perform concatenation.</p>
<p><strong>Question:</strong> What is the value of <code>"1"+2+4</code></p>
<p><strong>Answer:</strong> "124". For this one "1" + 2 will produce "12" and "12"+4 will generates "124".</p>
<p><strong>Question:</strong> What is the value of <code>-'34'+10</code></p>
<p><strong>Answer:</strong> -24. minus(-) in front of a string is an unary operator that will convert the string to a number and will make it negative. Hence, -'34' becomes, -34 and then plus (+) will perform simple addition as both the operands are number.</p>
<p><strong>Question:</strong> What is the value of <code>+'dude'</code></p>
<p><strong>Answer:</strong> NaN. The plus (+) operator in front of a string is an unary operator that will try to convert the string to number. Here, JavaScript will fail to convert the "dude" to a number and will produce NaN.</p>
<p><strong>Question:</strong> If you have <code>var y = 1, x = y = typeof x;</code> What is the value of x?</p>
<p><strong>Answer:</strong> "undefined"</p>
<p><strong>Question:</strong> for <code>var a = (2, 3, 5);</code> what is the value of a?</p>
<p><strong>Answer:</strong> 5. The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand. ref: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator">MDN</a></p>
<p><strong>Question:</strong> for <code>var a = (1, 5 - 1) * 2</code> what is the value of a?</p>
<p><strong>Answer:</strong> 8</p>
<p><strong>Question:</strong> What is the value of <code>!'bang'</code></p>
<p><strong>Answer:</strong> false. <code>!</code> is NOT. If you put <code>!</code> in front of truthy values, it will return false. Using !! (double bang) is a tricky way to check anything truthy or falsy by avoiding implicit type conversion of == comparison.</p>
<p><strong>Question:</strong> What is the value of <code>parseFloat('12.3.4')</code></p>
<p><strong>Answer:</strong> 12.3</p>
<p><strong>Question:</strong> What is the value of <code>Math.max([2,3,4,5]);</code></p>
<p><strong>Answer:</strong> NaN</p>
<p><strong>Question:</strong> <code>3 instanceof Number</code></p>
<p><strong>Answer:</strong> false</p>
<p><strong>Question:</strong><code>null == undefined</code></p>
<p><strong>Answer:</strong> true</p>
<p><strong>Question:</strong>What is the value of <code>!!function(){};</code></p>
<p><strong>Answer:</strong> true</p>
<p><strong>Question:</strong> What is the value of <code>typeof bar</code></p>
<p><strong>Answer:</strong> "undefined"</p>
<p><strong>Question:</strong> What is the value of <code>typeof null</code></p>
<p><strong>Answer:</strong> "object"</p>
<p><strong>Question:</strong> If <code> var a = 2, b =3</code> what would be value of <code>a && b</code></p>
<p><strong>Answer:</strong> 3</p>
<p><strong>Question:</strong> What would be consoled <code>var foo = 'outside'; function logIt(){console.log(foo); var foo = 'inside';} logIt();</code></p>
<p><strong>Answer:</strong> undefined</p>
<p><strong>Question:</strong> What is <code>-5%2</code></p>
<p><strong>Answer:</strong>-1. the result of remainder always get the symbol of first operand</p>
<p><strong>Question:</strong> Why <code>.1+.2 != .3</code> </p>
<p><strong>Answer:</strong> </p>
<p><strong>Question: <code>42..toString()</code></strong></p>
<p><strong>Anwser:</strong> <code>"42"</code></p>
<p><strong>Question:</strong> <code>4.2..toString</code></p>
<p><strong>Anwser:</strong> //SyntaxError: Unexpected token .</p>
<p><strong>Question:</strong><code>42 . toString()</code></p>
<p><strong>Anwser:</strong> <code>"42"</code></p>
<p><strong>Question:</strong> <code>typeof(NaN)</code></p>
<p><strong>Anwser:</strong>"number"</p>
<p><strong>Question:</strong> <code>2 in [1,2]</code></p>
<p><strong>Anwser:</strong> false. Because "in" returns whether a particular property/index available in the Object. In this case object has index 0 and 1 but don't have 2. Hence you get false.</p>
</div>
<div id="insertSpace">
<h2>12. log prefix</h2>
<p><strong>Question: </strong> How could you set a prefix before everything you log? for example, if you <code>log('my message')</code> it will log: "(app) my message"</p>
<p><strong>Answer:</strong> Just get the arguments, convert it to an array and unshift whatever prefix you want to set. Finally, use apply to pass all the arguments to console.</p>
<pre><code>
function log(){
var args = Array.prototype.slice.call(arguments);
args.unshift('(app)');
console.log.apply(console, args);
}
log('my message'); //(app) my message
log('my message', 'your message'); //(app) my message your message
</code></pre>
<p>ref: <a href="http://blog.sourcing.io/interview-questions">This is a really good materials, walks you through an interview process.</a></p>
</div>
<div id="scopeAndHoisting">
<h2>13. Scope and hoisting</h2>
<p><strong>Question:</strong> What will you see in the console for the following example?</p>
<pre><code>
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
console.log(a);
</code></pre>
<p><strong>Answer:</strong> 1</p>
<h4>Explanation:</h4>
<ul>
<li>function declaration <code>function a(){}</code> is hoisted first and it behaves like <code>var a = function () {};</code>. Hence in local scope variable <code>a</code> is created.</li>
<li>If you have two variables with same name (one in global another in local), local variable always get precedence over global variable.</li>
<li>When you set <code>a = 10;</code>, you are setting the local variable <code>a</code> , not the global one. Hence, the value of global variable remain same and you get, 1 in the log. ref: js hoisting/scope</li>
<li><strong>Extra:</strong> If you didnt have a function named as "a", you will see 10 in the log.</li>
</ul>
<div>
<button id = "hoistingExtra" type="button" class="toggleExample btn btn-primary">Show Tough Example</button>
<div id="hoistingExtraExample" class="hide bg-success toggleContent">
<p><strong>Question:</strong> for the following code, what will be returned for executing foo</p>
<pre><code>
function foo(){
function bar() {
return 3;
}
return bar();
function bar() {
return 8;
}
}
foo();//?
</code></pre>
<p><strong>Answer:</strong> 8</p>
<p><strong>Explanation:</strong> As function declaration is get hoisted. the first bar is at the top and second bar after the return will also be hoisted. Since there is already a bar (first function declaration), the second one will replace the first one. As there could be one function for a single name and the last one stays. Hence, when you executing bar, you are executed the second one (after hoisting) and you get.</p>
</div>
</div>
<p>ref: <a href="https://www.youtube.com/watch?v=7INtYcr8QIY">watch this video</a> or <a href="http://www.thatjsdude.com/jsConcepts/concepts/scope.html">learn more about scope and hoisting</a></p>
</div>
<div id="closure">
<h2>14. Closures Inside Loops</h2>
<p><strong>Question:</strong> Look at the code below, you have a for loop if you have setTimeout inside it. If log the loop counter inside setTimeout, what will be logged?</p>
<pre><code>
for(var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 10);
}
</code></pre>
<p><strong>Answer:</strong> The above will not output the numbers 0 through 9, but will simply print the number 10 ten times.</p>
<p><strong>Explanation:</strong> The console log is inside the anonymous function of setTimeout and setTimeout is executed when current call stack is over. So, the loop finishes and before setTimeout get the chance to execute. However, anonymous functions keep a reference to i by creating a closure. Since, the loop is already finished, the value i has been set to 10. When setTimeout use the value of i by reference, it gets the value of i as 10. Hence, you see 10 ten times.</p>
<p><strong>Solution: </strong> You can fix it by avoiding closure. Just create a IIFE (Immediately Invoked Function Expression), it will create its own scope and you can pass i to the function. In that case i will be a local variable (will not refer to i in the closure) and value of the i in every loop will be preserved.</p>
<pre><code>
for(var i = 0; i < 10; i++) {
setTimeout((function(i) {
console.log(i);
})(i), 10)
}
</code></pre>
<p><strong>Alternative Solution:</strong> Look at the code below and use your brain (if any).</p>
<pre><code>
for(var i = 0; i < 10; i++) {
setTimeout(console.log.bind(console, i), 10);
}
</code></pre>
</div>
<div id="deleteProperty">
<h2>15. delete can delete but</h2>
<p><strong>Question:</strong> Look at the code below, I have a property in a object and I am creating a new object where I am setting it to a new value. If I delete that property what will i get if I try to access that property?</p>
<pre><code>
var myObject = {
price: 20.99,
get_price : function() {
return this.price;
}
};
var customObject = Object.create(myObject);
customObject.price = 19.99;
delete customObject.price;
console.log(customObject.get_price());
</code></pre>
<p><strong>Answer:</strong> You will see 20.99</p>
<p><strong>Explanation:</strong> This is very interesting question. When you create <code>object.create(myObject)</code> you are creating new object where the <code>myObject</code> will be the parent of the newly created object. Hence the price property will be at the parent.</p>
<p>When you are assigning some value to <code>customObject.price</code>, you are creating a new property on the child. This means, when you <code>delete customObject.price</code> it deletes the <code>price</code> property in the customObject (in the child). However, when you call the method getprice, first it looks for <code>this.price</code> in the child since the customObject doesn't have price property, JavaScript executor walks through the prototype chain towards the parent. Since customObject was inherited from myObject and myObject has a <code>price</code> property, the get_price method returns the price from parent. Hence, you are getting 20.99</p>
</div>
<div id="byValueByRef">
<h2>16. Pass by value or by reference</h2>
<p><strong>Question:</strong> Does JavaScript pass parameter by value or by reference?</p>
<p><strong>Answer:</strong> Primitive type (string, number, etc.) are passed by value and objects are passed by reference. If you change a property of the passed object, the change will be affected. However, you assign a new object to the passed object, the changes will not be reflected.</p>
<pre><code>
var num = 10,
name = "Addy Osmani",
obj1 = {
value: "first value"
},
obj2 = {
value: "second value"
},
obj3 = obj2;
function change(num, name, obj1, obj2) {
num = num * 10;
name = "Paul Irish";
obj1 = obj2;
obj2.value = "new value";
}
change(num, name, obj1, obj2);
console.log(num); // 10
console.log(name);// "Addy Osmani"
console.log(obj1.value);//"first value"
console.log(obj2.value);//"new value"
console.log(obj3.value);//"new value"
</code></pre>
<p>ref: <a href="http://snook.ca/archives/javascript/javascript_pass">Snook: passing by value or reference</a></p>
</div>
<div id="memoization">
<h2>17. memoization</h2>
<p><strong>Question:</strong> How could you implement cache to save calculation time for a recursive fibonacci function?</p>
<p><strong>Answer:</strong> You could use poor man's memoization with a global variable. If fibonacci is already calculated it is served from the global memo array otherwise it is calculated.</p>
<pre><code>
var memo = [];
function _fibonacci(n) {
if(memo[n]){
return memo[n];
}
else if (n < 2){
return 1;
}else{
_fibonacci(n-2) + _fibonacci(n-1);
}
}
</code></pre>
<p><strong>Better Implementation: </strong><a href="http://www.sitepoint.com/implementing-memoization-in-javascript/">implement memoization in JavaScript</a></p>
</div>
<div id="cacheFunction">
<h2>18. Cache function execution</h2>
<p><strong>Question:</strong> How could you cache execution of any function?</p>
<p><strong>Answer:</strong> You could have a method where you will pass a function and it will internally maintain a cache object where calculated value will be cached. When you will call the function with same argument, the cached value will be served.</p>
<pre><code>
function cacheFn(fn) {
var cache={};
return function(arg){
if (cache[arg]){
return cache[arg];
}
else{
cache[arg] = fn(arg);
return cache[arg];
}
}
}
</code></pre>
<p><strong>Question:</strong> What if you are passing more than one argument?</p>
<p><strong>Answer: </strong> First we have to use arguments to get all the parameters passed to the function and then we can generate key for the cache object. Generating key for the cache object could be tricky and one solution could be just get the all the parameters and concatenate those. Look at the code below.</p>
<pre><code>
return function(){
var args = arguments;
var key = [].slice.call(args).join('');
if(cache[key]){
return cache[key];
}
else{
cache[key] = fn.apply(thi, args);
return cache[key];
}
}
</code></pre>
</div>
<div id="chianing">
<h2>19. JQuery style chaining</h2>
<p><strong>Question:</strong> If you need to implement the following chaining with call back, how will you implement it?</p>
<pre><code>
function slow(callback) {
setTimeout(function(){
if (Math.random() > 0.5) {
return callback("Error 417",null)
}
callback(null, {id:123})
},500);
}
function exec(fn){
//write your code here
}
exec(slow).done(function(data){
console.log(data);
}).fail(function(err){
console.log("Error: " + err);
})
</code></pre>
<p>Too much sleepy now. will try to put it up tomorrow.</p>
<pre><code>
var obj = { // every method returns obj---------v
first: function() { console.log('first'); return obj; },
second: function() { console.log('second'); return obj; },
third: function() { console.log('third'); return obj; }
}
obj.first().second().third();
</code></pre>
<p>ref: <a href="http://blog.buymeasoda.com/creating-a-jquery-like-chaining-api/">jquery like chaining</a> or <a href="http://stackoverflow.com/questions/7475336/how-does-jquery-chaining-work">jquery like chaining</a></p>
</div>
<div id="animation">
<h2>20. Animation</h2>
<p><strong>Question: </strong>How could you implement moveLeft animation?</p>
<p><strong>Answer:</strong> Use setInterval that will place the element to the left position by some pixels in every 10ms. Hence, you will see the element moving towards the desired position. When you call setInterval, it returns a timeId. After reaching the desired location, you have to clear the time interval so that function will not be called again and again in every 10ms.</p>
<pre><code>
function moveLeft(elem, distance) {
var left = 0;
function frame() {
left++;
elem.style.left = left + 'px';
if (left == distance)
clearInterval(timeId)
}
var timeId = setInterval(frame, 10); // draw every 10ms
}
</code></pre>
</div>
<div id ="currying">
<h2>21. Currying</h2>
<p><strong>Question:</strong> How would you implement currying for any functions?</p>
<p><strong>What is curring:</strong> Curring is partial invocation of a function. Currying means first few arguments of a function is pre-processed and a function is returned. The returning function can add more arguments to the curried function. It's like if you have given one or two spice to the curry and cooked little bit, still you can add further spice to it. A simple example will look like-</p>
<pre><code>
function addBase(base){
return function(num){
return base + num;
}
}
var addTen = addBase(10);
addTen(5); //15
addTen(80); //90
addTen(-5); //5
</code></pre>
<p><strong>Explanation:</strong> You are creating a closure that return a function. When you are curring with a new number, new number is added to the base you have provided.</p>
<p><strong>Answer: </strong> You can add a curry method to the prototype of Function. If now parameters is passed to curry, you simply return the current function. If you have provided arguments to curry there are two steps</p>
<ul>
<li><strong>Step-1:</strong> Concatenate old arguments (provided while creating curry), with new arguments (added after cooking little bit) by using <code> args.concat(toArray(arguments))</code></li>
<li><strong>Step-2:</strong> Pass all the arguments to the function by using apply.</li>
<li><strong>Extra:</strong> Just be careful to retain the value of this.</li>
</ul>
<pre><code>
Function.prototype.curry = function() {
if (arguments.length<1) {
return this; //nothing to curry. return function
}
var self = this;
var args = toArray(arguments);
return function() {
return self.apply(this, args.concat(toArray(arguments)));
}
}
function toArray(args) {
return Array.prototype.slice.call(args);
}
</code></pre>
<p><strong>To use it:</strong> Just pass the argument to the function.curry method and a function will be returned. Use returned function for further currying</p>
<pre><code>
function converter = function(factor, symbol, input){
return input * factor + symbol;
}
var milesToKm = converter.curry(1.62, 'km');
mileToKm(3); //result here
var kgToLb = converter.curry(2.2, 'lb');
kgToLb(3); //result here
</code></pre>
<p>ref: <a href="http://fr.umio.us/favoring-curry/">Favoring Curry</a>, <a href="http://javascriptweblog.wordpress.com/2010/04/05/curry-cooking-up-tastier-functions/">curry: cooking up tastier functions</a></p>
</div>
<div>
<h3>Deleted Questions</h3>
<ul>
<li>In JavaScript <code>isNaN(undefined)</code> returns true. how could you fix it? Answer: use <code>function isReallyNaN (x){return x!==x;}</code></li>
<li>What are differences between host object and native object? <a href="http://stackoverflow.com/a/7614380/1535443">read answer here</a></li>
<li>Why extending build in JavaScript object is a bad idea? Answer: google it</li>
<li>How will you get query string in a browsers URL? <a href="http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript?page=3&tab=votes#tab-top">detail answer</a> or <code>window.location.search;</code></li>
<li>Why does nearly every object have a toString method?</li>
<li>Why Everything in JavaScript acts like an object, with the only two exceptions being null and undefined?</li>
<li>How would you perform inheritance in JavaScript?</li>
<li>How would you apply asynchronous call without any help of library</li>
<li>What is the difference between slice, substr, substring?</li>
</ul>
</div>
<div>
<h3>Need more</h3>
<p>ref: great place to learn JavaScript <a href="http://bonsaiden.github.io/JavaScript-Garden/">JS Garden</a></p>
</div>
<div>
<h3 class="purpleBold">Express anger!</h3>
<p class="gray">Feel free to express your anger (sorry folks, you have to use g+.). Also point out my mistakes ( technical, wrong answer, spelling, grammar, sentence..., whatever), let your dude learn and grow.</p>
<script src="https://apis.google.com/js/plusone.js"></script>
<div class="g-comments"
data-href="http://www.thatjsdude.com/interview/js2.html"
data-width="642"
data-first_party_property="BLOGGER"
data-view_type="FILTERED_POSTMOD">
</div>
</div>
<hr>
<footer>
<p>©thatJSDude <script type="text/javascript">document.write(new Date().getFullYear());</script></p>
</footer>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery-2.0.3.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script src="js/toggleExample.js"></script>
<script type="text/javascript">
//social plugins
//g+
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/platform.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
//fb
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
</body>
</html>