Monday, March 21, 2016

Closure Example

Example of a closure

var scoreCounter = (function() {
  var score = 0;
  return {
    incrementBy: function(a) {
      score+=a;
    },
    decrementBy: function(b) {
      score-=b;
    },
    getValue: function() {
      return score;
    }
  };   
})();

console.log(scoreCounter.getValue()); // logs 0scoreCounter.incrementBy(10);
scoreCounter.incrementBy(5);
console.log(scoreCounter.getValue()); // logs 15scoreCounter.decrementBy(2);
console.log(scoreCounter.getValue()); // logs 13

Javascript Interview Questions

1. How do you define a String?
2. What are the string methods available?
3. What is the difference between substring and substr? substring extraction:String.slice( begin [, end ] ) String.substring( from [, to ] ) String.substr( start [, length ] )
4. How do you convert a string into a number?
5. How do you write an array? What is a 2 dimensional array?
6. How do you remove an item in the middle of an array?
7. var a = function() { return 20; }
    function a() { return 10; }

    What is the output for
    console.log(a);  //
    console.log(a());  //
8. What are the ways of defining an object in javascript?
9. How do you define a point on any window or a canvas?
10. How do you get the distance between two points?
11. How do you stop a loop? How do you skip one step in a loop?
12. What are the data types available in javascript?
13. What is encapsulation ?
14. How do you handle errors in javascript?
15. How many ways are there to debug javascript code?  console.log, breakpoints, debugger
16. What is variable hoisting? // declare the variables any where, js will take the declarations to top
17. What is use strict; ?
18. Does javascript allow you to delete a variable, a function or an object?
19. How do you define a readonly property for an object?
      var obj = {};
      Object.defineProperty(obj, "x", {value:0, writable:false});
20. What is closure in javascript?
21. Which is faster = = or  = = = ?
22. How do you start javascript execution after the content is loaded? defer='true' works only for external js
23. Can u create a copy of an object? no
24. What is the difference between call and apply?
25. What is a closure?
26. Can a global variable be used by multiple js files?


Closure Example
var scoreToAdd = 50;
var addScore=(function(){
     var score = 0;
     return function() { return score+scoreToAdd; };
} )();

addScore();

27. what is the output for below
      function a() {
            return
                    {
                        'a': 100
                     }
      }

      a();

28.  var a=[1,2,3,4,'satya',5,7,8,9];
a.reduce(function(a,b) {return a+b},1);

Some more interview questions are here
http://www.tutorialspoint.com/javascript/javascript_interview_questions.htm

https://www.toptal.com/javascript/interview-questions