From 6b051ce4f813b8733efc8ee102d4a61e5674775d Mon Sep 17 00:00:00 2001 From: utkarsh Date: Sun, 8 Oct 2017 19:52:18 +0530 Subject: [PATCH 1/2] Added a JS question: var vs let. --- js2.html | 177 ++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 110 insertions(+), 67 deletions(-) diff --git a/js2.html b/js2.html index 4c2a2b1..fcd52f3 100644 --- a/js2.html +++ b/js2.html @@ -5,20 +5,20 @@ - + JS: Basics and Tricky Questions - + @@ -83,23 +83,23 @@ - +
-

JS: Basics and Tricky Questions

+

JS: Basics and Tricky Questions

Part -2: intermediate

June 22, 2014

 
- -
+ +
- -

More Questions: Algorithm related questions, dom related, css related, html related

+

More Questions: Algorithm related questions, dom related, css related, html related

1. null vs undefined

Question: What are the differences between null and undefined?

@@ -148,12 +149,12 @@

undefined

  • Function parameters that have not passed.
  • Anything that has been set to the value of undefined.
  • Any expression in the form of void(expression)
  • -
  • The value of the global variable undefined
  • +
  • The value of the global variable undefined
  • null

    null 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

    -
    +

    2. == Vs ===

    Question: What are the differences between == and ===?

    @@ -177,12 +178,12 @@

    2. == Vs ===

    var c = a; a == c//true a === c //true - -

    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

    -

    3. Object Equality

    +

    3. Object Equality

    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 @@

    3. Object Equality

    for (var i = 0; i < aProps.length; i++) { var propName = aProps[i]; - + if (a[propName] !== b[propName]) { return false; } @@ -205,7 +206,7 @@

    3. Object Equality

    return true; } - Limitation: + Limitation:

    11. Rapid Fire

    Question: What is typeof []

    @@ -434,14 +435,14 @@

    11. Rapid Fire

    Question: 4.2..toString

    Anwser: //SyntaxError: Unexpected token .

    Question:42 . toString()

    -

    Anwser: "42"

    +

    Anwser: "42"

    Question: typeof(NaN)

    Anwser:"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.

    -
    +
    -

    12. log prefix

    +

    12. log prefix

    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.

    @@ -460,14 +461,14 @@

    12. log prefix

    13. Scope and hoisting

    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

    Explanation:

    @@ -480,7 +481,7 @@

    Explanation:

    -

    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 @@

    14. Closures Inside Loops

    
       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); }
    - +

    15. delete can delete but

    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 @@

    15. delete can delete but

    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

    -
    +

    16. Pass by value or by reference

    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 @@

    16. Pass by value or by reference

    console.log(name);// "Addy Osmani" console.log(obj1.value);//"first value" console.log(obj2.value);//"new value" -console.log(obj3.value);//"new value" +console.log(obj3.value);//"new value"

    ref: Snook: passing by value or reference

    @@ -586,7 +587,7 @@

    17. memoization

    var memo = []; function _fibonacci(n) { - if(memo[n]){ + if(memo[n]){ return memo[n]; } else if (n < 2){ @@ -595,8 +596,8 @@

    17. memoization

    _fibonacci(n-2) + _fibonacci(n-1); } } - -

    Better Implementation: implement memoization in JavaScript

    + +

    Better Implementation: implement memoization in JavaScript

    18. Cache function execution

    @@ -605,7 +606,7 @@

    18. Cache function execution

    
     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(); -
    +

    ref: jquery like chaining or jquery like chaining

    @@ -686,7 +687,7 @@

    20. Animation

    var timeId = setInterval(frame, 10); // draw every 10ms } - +

    21. Currying

    @@ -737,15 +738,15 @@

    21. Currying

    mileToKm(3); //result here var kgToLb = converter.curry(2.2, 'lb'); -kgToLb(3); //result here +kgToLb(3); //result here

    ref: Favoring Curry, curry: cooking up tastier functions

    -
    +

    Deleted Questions

    +
    +

    22. var vs. let

    +

    Question: What is the difference between var and let?

    +

    Answer: var and let differ because of scoping.

    +

    var

    +

    + 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. +

    + Example: +
    +          
    +            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

    +

    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.

    + Example: +
    +          
    +            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.

    +
    + -

    Express anger!

    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 @@

    Express anger!

    data-width="642" data-first_party_property="BLOGGER" data-view_type="FILTERED_POSTMOD"> -
    +
    - + @@ -783,9 +826,9 @@

    Express anger!

    - + - + + From b6eff0db52ca55d20505d168da71710a1acca8b0 Mon Sep 17 00:00:00 2001 From: utkarsh Date: Sun, 8 Oct 2017 19:55:13 +0530 Subject: [PATCH 2/2] Typo fix. --- js2.html | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/js2.html b/js2.html index fcd52f3..02f0d59 100644 --- a/js2.html +++ b/js2.html @@ -431,15 +431,15 @@

    11. Rapid Fire

    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.

    12. log prefix