-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparams.json
More file actions
1 lines (1 loc) · 23.9 KB
/
Copy pathparams.json
File metadata and controls
1 lines (1 loc) · 23.9 KB
1
{"name":"101-javascript-interview-question","tagline":"JavaScript 101 interview Question ","body":"##### 1. Difference between `undefined` and `not defined` in JavaScript \r\n\r\n> In JavaScript if you try to use variable that doesn't exist and has not been declared, then JavaScript will throw an error `var name is not defined` and script will stop execution there after. But If you use `typeof undeclared_variable` then it will return `undefined`.\r\n\r\nBefore starting further discussion let understand the difference between deceleration and definition.\r\n\r\n`var x` is a declaration because you are not defining what value it holds yet, but you are declaring it's existence and the need of memory allocation. \r\n\r\n```javascript\r\n> var x; // declaring x\r\n> console.log(x); //output: undefined \r\n```\r\n\r\n`var x = 1` is both declaration and definition (also we can say we are doing initialisation), Here declaration and assignment of value happen inline for variable x, In JavaScript every variable declaration and function declaration brings to the top of it's current scope in which It's declared then assignment happen in order this term is called `hoisting`. \r\n\r\n> A variable that is declare but not define and when we try to access it, It will result `undefined`.\r\n\r\n```javascript\r\nvar x; // Declaration\r\nif(typeof x === 'undefined') // Will return true\r\n\r\n```\r\n> A variable that is neither declare nor defined, when we try to reference such variable then It result `not defined`.\r\n\r\n```javascript\r\n> console.log(y); // Output: ReferenceError: y is not defined\r\n```\r\n\r\n###### Ref Link: \r\nhttp://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration\r\n\r\n##### 2. What will be the output of below code ?\r\n\r\n```javascript\r\n var y = 1;\r\n if (function f(){}) {\r\n y += typeof f;\r\n }\r\n console.log(y);\r\n```\r\n> Above code would give output `1undefined`. If condition statement evaluate using `eval` so `eval(function f(){})` which return `function f(){}` which is true so inside if statement code execute. `typeof f` return undefined because if statement code execute at run time, so statement inside `if` condition evaluated at run time. \r\n\r\n```javascript\r\n var k = 1;\r\n if (1) {\r\n eval(function foo(){});\r\n k += typeof foo;\r\n }\r\n console.log(k); \r\n```\r\nAbove code will also output `1undefined`.\r\n\r\n```javascript\r\n var k = 1;\r\n if (1) {\r\n function foo(){};\r\n k += typeof foo;\r\n }\r\n console.log(k); // output 1function\r\n```\r\n##### 3. What is drawback of creating true private in JavaScript?\r\n\r\n> One of the drawback of creating true private method in JavaScript is that they are very memory inefficient because a new copy of the method would be created for each instance.\r\n\r\n```javascript\r\nvar Employee = function (name, company, salary) {\r\n this.name = name || \"\"; //Public attribute default value is null\r\n this.company = company || \"\"; //Public attribute default value is null\r\n this.salary = salary || 5000; //Public attribute default value is null\r\n\r\n // Private method\r\n var increaseSlary = function () {\r\n this.salary = this.salary + 1000;\r\n };\r\n\r\n // Public method\r\n this.dispalyIncreasedSalary = function() {\r\n increaseSlary();\r\n console.log(this.salary);\r\n };\r\n};\r\n\r\n// Create Employee class object\r\nvar emp1 = new Employee(\"John\",\"Pluto\",3000);\r\n// Create Employee class object\r\nvar emp2 = new Employee(\"Merry\",\"Pluto\",2000);\r\n// Create Employee class object\r\nvar emp3 = new Employee(\"Ren\",\"Pluto\",2500);\r\n```\r\nHere each instance variable `emp1`, `emp2`, `emp3` has own copy of increaseSalary private method.\r\n\r\nSo as recommendation don’t go for private method unless it’s necessary.\r\n\r\n##### 4.What is “closure” in javascript? Provide an example ?\r\n\r\n> A closure is a function defined inside another function (called parent function) and has access to variable which is declared and defined in parent function scope.\r\n\r\nThe closure has access to variable in three scopes:\r\n\r\n * Variable declared in his own scope \r\n * Variable declared in parent function scope \r\n * Variable declared in global namespace\r\n\r\n```javascript\r\nvar globalVar = \"abc\"; \r\n\r\n// Parent self invoking function \r\n(function outerFunction (outerArg) { // begin of scope outerFunction\r\n // Variable declared in outerFunction function scope \r\n var outerFuncVar = 'x'; \r\n // Closure self-invoking function \r\n (function innerFunction (innerArg) { // begin of scope innerFunction\r\n // variable declared in innerFunction function scope\r\n var innerFuncVar = \"y\"; \r\n console.log( \r\n \"outerArg = \" + outerArg + \"\\n\" +\r\n \"outerFuncVar = \" + outerFuncVar + \"\\n\" +\r\n \"innerArg = \" + innerArg + \"\\n\" +\r\n \"innerFuncVar = \" + innerFuncVar + \"\\n\" +\r\n \"globalVar = \" + globalVar);\r\n \r\n }// end of scope innerFunction)(5); // Pass 5 as parameter \r\n}// end of scope outerFunction )(7); // Pass 7 as parameter \r\n```\r\n`innerFunction` is closure which is defined inside `outerFunction` and has access to all variable which is declared and defined in outerFunction scope. In addition to this function defined inside function as closure has access to variable which is declared in `global namespace`.\r\n\r\nOutput of above code would be:\r\n\r\n```javascript\r\nouterArg = 7\r\nouterFuncVar = x\r\ninnerArg = 5\r\ninnerFuncVar = y\r\nglobalVar = abc\r\n\r\n```\r\n\r\n##### 5. Write a mul function which will properly when invoked as below syntax.\r\n \r\n ```javascript\r\n console.log(mul(2)(3)(4)); // output : 24 \r\n console.log(mul(4)(3)(4)); // output : 48\r\n ```\r\n\r\n> Below is code followed by an explanation how it works:\r\n\r\n```javascript\r\nfunction mul (x) {\r\n return function (y) { // anonymous function \r\n return function (z) { // anonymous function \r\n return x * y * z; \r\n };\r\n };\r\n}\r\n```\r\n\r\nHere `mul` function accept first argument and return anonymous function which take second parameter and return anonymous function which take third parameter and return multiplication of arguments which is being passed in successive \r\n\r\nIn Javascript function defined inside has access to outer function variable and function is first class object so it can be returned by function as well and passed as argument in another function.\r\n\r\n* A function is an instance of the Object type\r\n* A function can have properties and has a link back to its constructor method\r\n* Function can be stored as variable \r\n* Function can be pass as a parameter to another function\r\n* Function can be return from function\r\n\r\n#### 6. How to empty an array in JavaScript ?\r\n\r\nFor instance,\r\n\r\n```javascript\r\n var arrayList = ['a','b','c','d','e','f'];\r\n```\r\nHow can we empty above array ?\r\n\r\n> There are couple of ways by which we can empty an array, So let's discuss all the possible way by which we can empty an array.\r\n\r\n#### Method 1 \r\n```javascript\r\narrayList = []\r\n```\r\nAbove code will set the variable `arrayList` to a new empty array. This is recommended if you don't have **references to the original array** `arrayList` anywhere else because It will actually create new empty array. You should be careful with this way of empty the array,because if you have referenced this array from another variable, then the original reference array will remain unchanged, Only use this way if you have only reference the array by it's original variable `arrayList`.\r\n\r\nFor Instance,\r\n\r\n```javascript\r\nvar arrayList = ['a','b','c','d','e','f']; // Created array \r\nvar anotherArrayList = arrayList; // Referenced arrayList by another variable \r\narrayList = []; // Empty the array \r\nconsole.log(anotherArrayList); // Output ['a','b','c','d','e','f']\r\n```\r\n \r\n#### Method 2\r\n```javascript\r\narrayList.length = 0;\r\n```\r\nAbove code will clear the existing array by setting it's length to 0. This way of empty the array also update all the reference variable which pointing to the original array. This way of empty the array is useful when you want to update all the another reference variable which pointing to `arrayList`.\r\n\r\nFor Instance,\r\n\r\n```javascript\r\nvar arrayList = ['a','b','c','d','e','f']; // Created array \r\nvar anotherArrayList = arrayList; // Referenced arrayList by another variable \r\narrayList.length = 0; // Empty the array by setting length to 0\r\nconsole.log(anotherArrayList); // Output []\r\n```\r\n#### Method 3\r\n```javascript\r\narrayList.splice(0, arrayList.length);\r\n```\r\nAbove implementation will also work perfectly. This way of empty the array will also update all the references of original array.\r\n\r\n```javascript\r\nvar arrayList = ['a','b','c','d','e','f']; // Created array \r\nvar anotherArrayList = arrayList; // Referenced arrayList by another variable \r\narrayList.splice(0, arrayList.length); // Empty the array by setting length to 0\r\nconsole.log(anotherArrayList); // Output []\r\n```\r\n#### Method 4\r\n\r\n```javascript\r\nwhile(arrayList.length){\r\n\tarrayList.pop();\r\n}\r\n```\r\nAbove implementation can also empty the array. But not recommended to use often. \r\n\r\n#### 7. How to check if an object is an array or not ?\r\n\r\n> The best way to find whether a object is instance of a particular class or not using `toString` method from `Object.prototype`\r\n\r\n```javascript\r\n var arrayList = [1,2,3];\r\n```\r\nOne of the best use cases of type checking of object is when we do method overloading in JavaScript. For understanding this let sat we have a method called `greet` which take one single string and also list of string, so making our greet method workable in both situation we need to know what kind of parameter is being passed, is it single value or list of value ?\r\n\r\n```javascript\r\n function greet(param){\r\n \tif(){ // here have to check whether param is array or not \r\n \t}else{\r\n \t}\r\n }\r\n```\r\nHowever in above implementation it might not necessary to check type for array, we can check for single value string and put array logic code in else block, let see below code for the same.\r\n\r\n```javascript\r\n function greet(param){\r\n \tif(typeof param === 'string'){ \r\n \t}else{\r\n \t // If param is of type array then this block of code would execute\r\n \t}\r\n }\r\n```\r\nNow It's fine we can go with above two implementation, but when we have situation like parameter can be `single value`, `array`, and `object` type then we will be in trouble. \r\n\r\nComing back to checking type of object, As we mentioned that we can use \r\n`Object.prototype.toString` \r\n\r\n```javascript\r\nif( Object.prototype.toString.call( arrayList ) === '[object Array]' ) {\r\n console.log('Array!');\r\n}\r\n```\r\n\r\nIf you are using `jQuery` then you can also used jQuery `isArray` method:\r\n\r\n```javascript\r\n if($.isArray(arrayList)){\r\n console.log('Array');\r\n }else{\r\n \tconsole.log('Not an array');\r\n }\r\n```\r\nFYI jQuery uses `Object.prototype.toString.call` internally to check whether object is an array or not.\r\n\r\nIn Modern browser you can also use \r\n```javascript\r\nArray.isArray(arrayList);\r\n```\r\n`Array.isArray` is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5\r\n \r\n##### 8. What will be the output of below code ?\r\n\r\n```javascript\r\nvar output = (function(x){\r\n delete x;\r\n return x;\r\n })(0);\r\n \r\n console.log(output);\r\n```\r\n> Above code will output `0` as output. `delete` operator is used to delete property from object. Here `x` is not an object it's **local variable**. `delete` operator doesn't affect local variable.\r\n\r\n##### 9. What will be the output of below code ?\r\n\r\n```javascript\r\nvar x = 1;\r\nvar output = (function(){\r\n delete x;\r\n return x;\r\n })();\r\n \r\n console.log(output);\r\n```\r\n> Above code will output `1` as output. `delete` operator is used to delete property from object. Here `x` is not an object it's **global variable** of type `number`.\r\n\r\n##### 10. What will be the output of below code ?\r\n\r\n```javascript\r\nvar x = { foo : 1};\r\nvar output = (function(){\r\n delete x.foo;\r\n return x.foo;\r\n })();\r\n \r\n console.log(output);\r\n```\r\n> Above code will output `undefined` as output. `delete` operator is used to delete property from object. Here `x` is an object which has foo as a property and from self-invoking function we are deleting foo property of object `x` and after deletion we are trying to reference deleted property `foo` which result `undefined`.\r\n\r\n##### 11. What will be the output of below code ?\r\n\r\n```javascript\r\nvar Employee = {\r\n company: 'xyz'\r\n}\r\nvar emp1 = Object.create(Employee);\r\ndelete emp1.company\r\nconsole.log(emp1.company);\r\n```\r\n> Above code will output `xyz` as output. Here `emp1` object got company as **prototype** property. delete operator doesn't delete prototype property. \r\n\r\n`emp1` object doesn't have **company** as it's own property. you can test it `console.log(emp1.hasOwnProperty('company')); //output : false` However we can delete company property directly from `Employee` object using `delete Employee.company` or we can also delete from `emp1` object using `__proto__` property `delete emp1.__proto__.company`.\r\n\r\n##### 12. What is `undefined x 1` in JavaScript\r\n\r\n```javascript\r\nvar trees = [\"redwood\",\"bay\",\"cedar\",\"oak\",\"maple\"];\r\ndelete trees[3];\r\n```\r\nwhen you run above code and do `console.log(trees);` in chrome developer console then you will get \r\n`[\"redwood\", \"bay\", \"cedar\", undefined × 1, \"maple\"]` and when you run above code in Firefox browser console then you will get `[\"redwood\", \"bay\", \"cedar\", undefined, \"maple\"]` so from these It's cleared that chrome has it's own way of displaying uninitialised index in array. But when you check `trees[3] === undefined` in both of the browser you will get similar output as `true`. \r\n\r\n**Note:** Please remember you need not check for uninitialised index of array in `trees[3] === 'undefined × 1'` it will give error, Because `'undefined × 1'` this is just way of displaying uninitialised index of array in chrome.\r\n\r\n##### 13. What will be the output of below code ?\r\n\r\n```javascript\r\nvar trees = [\"xyz\",\"xxxx\",\"test\",\"ryan\",\"apple\"];\r\ndelete trees[3];\r\n \r\n console.log(trees.length);\r\n```\r\n> Above code will output `5` as output. When we used `delete` operator for deleting an array element then, the array length is not affected from this. This holds even if you deleted all the element of array using `delete` operator.\r\n\r\nSo when delete operator removes an array element that deleted element is not longer present in array. In place of value at deleted index `undefiend x 1` in **chrome** and `undefiend` is placed at the index. If you do `console.log(trees)` output `[\"xyz\", \"xxxx\", \"test\", undefined × 1, \"apple\"]` in Chrome and in Firefox `[\"xyz\", \"xxxx\", \"test\", undefined, \"apple\"]`.\r\n\r\n##### 14. What will be the output of below code ?\r\n\r\n```javascript\r\nvar bar = true;\r\nconsole.log(bar + 0); \r\nconsole.log(bar + \"xyz\"); \r\nconsole.log(bar + true); \r\nconsole.log(bar + false); \r\n```\r\n> Above code will output `1, \"truexyz\", 2, 1` as output. General guideline for addition of operator: \r\n \r\n> * Number + Number -> Addition \r\n> * Boolean + Number -> Addition \r\n> * Boolean + Number -> Addition \r\n> * Number + String -> Concatenation\r\n> * String + Boolean -> Concatenation\r\n> * String + String \t-> Concatenation\r\n\r\n\r\n##### 15. What will be the output of below code ?\r\n\r\n```javascript\r\nvar z = 1, y = z = typeof y;\r\nconsole.log(y); \r\n```\r\n> Above code will output `undefined` as output. According to `associativity` rule operator with same precedence are processed based on there associativity property of operator. Here associativity of assignment operator is `Right to Left` so first `typeof y` will evaluate first which is `undefined` and assigned to `z` and then `y` would be assigned value of z and then `z` would be assign value `1`.\r\n\r\n##### 16. What will be the output of below code ?\r\n\r\n```javascript\r\n // NFE (Named Function Expression \r\n var foo = function bar(){ return 12; };\r\n typeof bar(); \r\n```\r\n> Above code will output `Reference Error` as output. For making above code work you can re-write above code as follow: \r\n\r\n**Sample 1**\r\n\r\n```javascript\r\n var bar = function(){ return 12; };\r\n typeof bar(); \r\n```\r\nor \r\n\r\n**Sample 2**\r\n\r\n```javascript\r\n function bar(){ return 12; };\r\n typeof bar(); \r\n```\r\nfunction definition can have only one reference variable as a function name, In above code **sample 1** bar is reference variable which is pointing to `anonymous function` and in **sample 2** function definition is name function.\r\n\r\n```javascript\r\n var foo = function bar(){ \r\n // foo is visible here \r\n // bar is visible here\r\n \tconsole.log(typeof bar()); // Work here :)\r\n };\r\n // foo is visible here\r\n // bar is undefined here\r\n \r\n```\r\n\r\n##### 17. what is difference between declaring function in below format ?\r\n\r\n```javascript\r\n var foo = function(){ \r\n\t// Some code\r\n }; \r\n```\r\n\r\n```javascript\r\n function bar(){ \r\n\t// Some code\r\n }; \r\n```\r\nThe main difference is function `foo` is defined at `run-time` whereas function `bar` is defined at parse time. For understanding It in better way let see below code : \r\n\r\n```javascript\r\nRun-Time function declaration \r\n<script>\r\nfoo(); // Call foo function here, It will give Error\r\n var foo = function(){ \r\n\t\tconsole.log(\"Hi I am inside Foo\");\r\n }; \r\n </script>\r\n```\r\n```javascript\r\n<script>\r\nParse-Time function declaration \r\nbar(); // Call foo function here, It will not give Error\r\n function bar(){ \r\n\tconsole.log(\"Hi I am inside Foo\");\r\n }; \r\n </script>\r\n```\r\nThe another advantage of first-one way of declaration that you can declare function based on certain condition for example: \r\n\r\n```javascript\r\n<script>\r\nif(testCondition) {// If testCondition is true then \r\n\t var foo = function(){ \r\n\t\tconsole.log(\"inside Foo with testCondition True value\");\r\n\t }; \r\n }else{\r\n \t var foo = function(){ \r\n\t\tconsole.log(\"inside Foo with testCondition false value\");\r\n\t }; \r\n }\r\n </script>\r\n```\r\nBut If you try to run similar code in below format It would give error \r\n\r\n```javascript\r\n<script>\r\nif(testCondition) {// If testCondition is true then \r\n\t function foo(){ \r\n\t\tconsole.log(\"inside Foo with testCondition True value\");\r\n\t }; \r\n }else{\r\n \t function foo(){ \r\n\t\tconsole.log(\"inside Foo with testCondition false value\");\r\n\t }; \r\n }\r\n </script>\r\n```\r\n##### 18. what is function hoisting in JavaScript? \r\n\r\n**Function Expression**\r\n\r\n```javascript\r\n var foo = function foo(){ \r\n \treturn 12; \r\n }; \r\n```\r\n> In JavaScript variable and functions are `hoisted`. Let's take function `hoisting` first. Basically, the JavaScript interpreter looks ahead to find all the variable declaration and hoists them to the top of the function where it's declared. For Example:\r\n\r\n```javascript\r\n foo(); // Here foo is still undefined \r\n var foo = function foo(){ \r\n \treturn 12; \r\n }; \r\n```\r\nAbove code behind the scene look something like below code: \r\n\r\n ```javascript\r\n var foo = undefined;\r\n foo(); // Here foo is undefined \r\n \t foo = function foo(){\r\n \t / Some code stuff\r\n }\r\n ```\r\n ```javascript\r\n var foo = undefined;\r\n \t foo = function foo(){\r\n \t / Some code stuff\r\n }\r\n foo(); // Now foo is defined here\r\n ```\r\n\r\n ##### 19. What will be the output of below code ? \r\n\r\n ```javascript\r\n var salary = \"1000$\";\r\n\r\n (function () {\r\n console.log(\"Original salary was \" + salary);\r\n\r\n var salary = \"5000$\";\r\n\r\n console.log(\"My New Salary \" + salary);\r\n })();\r\n ```\r\n > Above code will output: `undefined, 5000$`. JavaScript has hoisting concept where newbie get tricked. In above code, you might be expecting `salary` to retain it's value from outer scope until the point that `salary` was re-declared in the inner scope. But due to `hoisting` salary value was `undefined` instead. To understand It better have a look of below code, here `salary` variable is hoisted and declared at the top in function scope and while doing console.log it's result `undefined` and after that it's been redeclare and assigned `5000$`.\r\n\r\n ```javascript\r\n var salary = \"1000$\";\r\n\r\n (function () {\r\n var salary = undefined;\r\n console.log(\"Original salary was \" + salary);\r\n\r\n salary = \"5000$\";\r\n\r\n console.log(\"My New Salary \" + salary);\r\n })();\r\n ```\r\n\r\n ##### 20. What is the `instanceof` operator in JavaScript? what would be the output of below code ? \r\n\r\n```javascript\r\nfunction foo(){ \r\n\treturn foo; \r\n}\r\nnew foo() instanceof foo;\r\n```\r\n> `instanceof` operator checks the current object and return true if the object is of the the specified type.\r\n\r\nFor Example: \r\n\r\n```javascript\r\n var dog = new Animal();\r\n dog instanceof Animal // Output : true\r\n```\r\nHere `dog instanceof Animal` is true since `dog` inherits from `Animal.prototype`\r\n\r\n```javascript\r\n var name = new String(\"xyz\");\r\n name instanceof String // Output : true\r\n```\r\nHere `name instanceof String` is true since `dog` inherits from `String.prototype`. Now let's understand the working of below code \r\n\r\n```javascript\r\nfunction foo(){ \r\n\treturn foo; \r\n}\r\nnew foo() instanceof foo;\r\n```\r\nHere function `foo` is returning `foo` which is again pointer to function `foo`\r\n\r\n```javascript\r\nfunction foo(){ \r\n\treturn foo; \r\n}\r\nvar bar = new foo();\r\n// here bar is pointer to function foo(){return foo}.\r\n```\r\nSo the `new foo() instanceof foo` return `false`;\r\n\r\n\r\nRef Link: http://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript\r\n\r\n##### 21. If we have JavaScript associative array as below code : \r\n\r\n```javascript\r\n var counterArray = {\r\n \t\t A : 3,\r\n \t\t B : 4\r\n };\r\n counterArray[\"C\"] = 1;\r\n```\r\n##### How we will calculate length of the above associative array `counterArray` \r\n\r\n> There are no in-built function and property available to calculate length of associative array object, However there are ways by which we can calculate the length of associative array object, In addition to this we can also extend `Object` by adding method or property on prototype for calculate length but extending object might break enumeration in various libraries or might create cross-browser issue, so It's not recommended unless it's necessary. There are various way by which we can calculate length.\r\n\r\n`Object` has `keys` method which can we used to calculate the length of object.\r\n\r\n``` \r\n Object.keys(counterArray).length // Output 2 \r\n```\r\nWe can also calculate length of object by iterating through object and by doing count of own property of object. \r\n\r\n```\r\nfunction getSize(object){\r\n\tvar count = 0;\r\n\tfor(key in object){\r\n\t // hasOwnProperty method check own property of object\r\n\t if(object.hasOwnProperty(key)) count++;\r\n\t}\r\n\treturn count;\r\n}\r\n```\r\n> We can also add `length` method directly on `Object` see below code.\r\n\r\n```\r\n Object.length = function(){\r\n \tvar count = 0;\r\n\tfor(key in object){\r\n\t // hasOwnProperty method check own property of object\r\n\t if(object.hasOwnProperty(key)) count++;\r\n\t}\r\n\treturn count;\r\n }\r\n //Get the size of any object using\r\n console.log(Object.length(counterArray))\r\n```\r\n**Bonus**: We can also use `Underscore` (recommended, As it's lightweight) to calculate object length.\r\n","google":"","note":"Don't delete this file! It's used internally to help with page regeneration."}