diff --git a/js2.html b/js2.html index 4c2a2b1..02f0d59 100644 --- a/js2.html +++ b/js2.html @@ -5,20 +5,20 @@ - +
June 22, 2014
- -var str = 'hello world', how could i get str.reverse() return 'dlrow olleh'?var and let?More Questions: Algorithm related questions, dom related, css related, html related
+More Questions: Algorithm related questions, dom related, css related, html related
Question: What are the differences between null and undefined?
undefinedundefinednull 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".
Btw, null == undefined ref: history of typeof null
Question: What are the differences between == and ===?
Special note: NaN, null and undefined will never === another type. NaN does not even === itself.
+ +Special note: NaN, null and undefined will never === another type. NaN does not even === itself.
Homework: Read confusing special cases of NaN
Question: How would you compare two objects in JavaScript?
Basics: 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.
Answer: 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.
@@ -197,7 +198,7 @@truthy: There are only two truthy things- true and everything that is not false
Question: Is 'false' is false?
Answer: No. Because, it's a string with length greater than 0. Only empty string is false.
Question: Is ' ' is false?
ref: angus croll: truth and eqality in JS, ref: truthy and falsy
Question: How could you write a method on an instance of a date which will give you the next day?
@@ -266,7 +267,7 @@Answer: We need to add a method in the prototype of Array object.
Array.prototype.duplicator = function(){
- return this.concat(this);
+ return this.concat(this);
}
[1,2,3,4,5].duplicator(); // [1,2,3,4,5,1,2,3,4,5]
@@ -306,7 +307,7 @@ 7. bind
total: 400,
deductMontlyFee: function(fee){
this.total = this.total - fee;
- return this.name + ' remaining balance is '+ this.total;
+ return this.name + ' remaining balance is '+ this.total;
}
}
@@ -351,7 +352,7 @@ Danger: Don't name any argument as "arguments" or dont create any local variable named as "arguments", this will override build in arguments object.
Answer: 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.
function getMax(arr){
- return Math.max.apply(null, arr);
+ return Math.max.apply(null, arr);
}
- Extra: 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.
+Extra: 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.
Tip: If you have weaker memory like me, you can remember apply starts with "a" and array starts with "a"
Question: What is typeof []
Question: Why .1+.2 != .3
Answer:
Question: 42..toString()
Anwser: "42"
Answer: "42"
Question: 4.2..toString
Anwser: //SyntaxError: Unexpected token .
+Answer: //SyntaxError: Unexpected token .
Question:42 . toString()
Anwser: "42"
Answer: "42"
Question: typeof(NaN)
Anwser:"number"
+Answer:"number"
Question: 2 in [1,2]
Anwser: 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.
-Answer: 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.
+Question: How could you set a prefix before everything you log? for example, if you log('my message') it will log: "(app) my message"
Answer: 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.
@@ -452,7 +453,7 @@ 12. log prefix
}
log('my message'); //(app) my message
-log('my message', 'your message'); //(app) my message your message
+log('my message', 'your message'); //(app) my message your message
ref: This is a really good materials, walks you through an interview process.
Question: What will you see in the console for the following example?
-var a = 1;
-function b() {
- a = 10;
- return;
- function a() {}
-}
-b();
-console.log(a);
+var a = 1;
+function b() {
+ a = 10;
+ return;
+ function a() {}
+}
+b();
+console.log(a);
Answer: 1
Question: for the following code, what will be returned for executing foo
+Question: for the following code, what will be returned for executing foo
function foo(){
function bar() {
@@ -495,7 +496,7 @@ Explanation:
Answer: 8
Explanation: 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.
-ref: watch this video or learn more about scope and hoisting
@@ -505,13 +506,13 @@
for(var i = 0; i < 10; i++) {
setTimeout(function() {
- console.log(i);
+ console.log(i);
}, 10);
}
Answer: The above will not output the numbers 0 through 9, but will simply print the number 10 ten times.
Explanation: 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.
-Solution: 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.
+Solution: 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.
for(var i = 0; i < 10; i++) {
setTimeout((function(i) {
@@ -525,7 +526,7 @@ 14. Closures Inside Loops
setTimeout(console.log.bind(console, i), 10);
}
-
+
Question: 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?
@@ -546,7 +547,7 @@Explanation: This is very interesting question. When you create object.create(myObject) you are creating new object where the myObject will be the parent of the newly created object. Hence the price property will be at the parent.
When you are assigning some value to customObject.price, you are creating a new property on the child. This means, when you delete customObject.price it deletes the price property in the customObject (in the child). However, when you call the method getprice, first it looks for this.price 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 price property, the get_price method returns the price from parent. Hence, you are getting 20.99
Question: Does JavaScript pass parameter by value or by reference?
Answer: 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.
@@ -574,7 +575,7 @@Better Implementation: implement memoization in JavaScript
+ +Better Implementation: implement memoization in JavaScript
function cacheFn(fn) {
var cache={};
-
+
return function(arg){
if (cache[arg]){
return cache[arg];
@@ -621,7 +622,7 @@ 18. Cache function execution
Answer: 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.
return function(){
- var args = arguments;
+ var args = arguments;
var key = [].slice.call(args).join('');
if(cache[key]){
return cache[key];
@@ -665,7 +666,7 @@ 19. JQuery style chaining
}
obj.first().second().third();
-
+
isNaN(undefined) returns true. how could you fix it? Answer: use function isReallyNaN (x){return x!==x;}window.location.search;ref: great place to learn JavaScript JS Garden
Question: What is the difference between var and let?
Answer: var and let differ because of scoping.
+ var is function scoped if used inside a function otherwise its scope is global.
+ This means that the value of a variable defined with var in a function will be accessible anywhere inside that function.
+
+
+ function countTill(number) {
+ for(var i = 1; i <= number; i++) {
+ console.log(i);
+ }
+ // Let's check value of i
+ console.log(i);
+ }
+
+ countTill(9);
+
+
+ Here, the value of i after the loop will be 10 and this will be logged to the console. This happens because the variable i is still in score even after execution has come out of the loop.
+let is block scoped. This means that the value of a variable defined with let will be accessible inside the block that it was declared in.
+
+ function countTill(number) {
+ for(let i = 1; i <= number; i++) {
+ console.log(i);
+ }
+ // Let's check value of i
+ console.log(i);
+ }
+
+ countTill(9);
+
+
+ Here, we will get a ReferenceError after the loop as i is not defined for that scope because no such variable exists outside the for loop. The varable only exists inside the block in which it was created.
+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.
@@ -770,10 +813,10 @@