• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ganqqwerty/123-Essential-JavaScript-Interview-Questions: JavaScript interview Qu ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

ganqqwerty/123-Essential-JavaScript-Interview-Questions

开源软件地址:

https://github.com/ganqqwerty/123-Essential-JavaScript-Interview-Questions

开源编程语言:


开源软件介绍:

123-JavaScript-Interview-Questions

This book's goal is to help javascript frontend developers prepare for technical job interviews through a collection of carefully compiled questions.

Want to buy a book in paper form? Want some badass flashcards?

  • This Book will be soon completed and then it will be available to buy in paper form. If you want me to send you an early copy of this book, please add your name and email address in this Google Form.
  • If you don't want to wait, you can buy Yuri's JavaScript Flashcards, a set of frontend interview questions sorted by popularity among interviewers printed on beautiful poker-size flashcards.

Question 1. What's the difference between undefined and not defined in JavaScript

Answer

In JavaScript if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error var name is not defined and the script will stop executing thereafter. But If you use typeof undeclared_variable then it will return undefined.

Before starting further discussion let's understand the difference between declaration and definition.

var x is a declaration because we are not defining what value it holds yet, but we are declaring its existence and the need for memory allocation.

var x; // declaring x
console.log(x); // output: undefined

var x = 1 is both declaration and definition, here declaration and assignment of value happen inline for variable x—what we are doing is called "initialisation". In JavaScript both variable declarations and function declarations go to the top of the scope in which they are declared, then assignment happens—this series of events is called "hoisting".

A variable can be declared but not defined. When we try to access it, It will result undefined.

var x; // Declaration
typeof x === 'undefined'; // Will return true

A variable can be neither declared nor defined. When we try to reference such variable then the result will be not defined.

console.log(y);  // Output: ReferenceError: y is not defined

Ref Link:

http://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration

Question 2. For which value of x the results of the following statements are not the same?

if( x <= 100 ) {...}
if( !(x > 100) ) {...}
Answer

NaN <= 100 is false and NaN > 100 is also false, so if the value of x is NaN, the statements are not the same.

The same holds true for any value of x that being converted to type Number, returns NaN, e.g.: undefined, [1,2,5], {a:22} , etc.

This is why you need to pay attention when you deal with numeric variables. NaN can’t be equal, less than or more than any other numeric value, so the only reliable way to check if the value is NaN, is to use the isNaN() function.

Question 3. What is the drawback of declaring methods directly in JavaScript objects?

Answer

One of the drawbacks of declaring methods directly in JavaScript objects is that they are very memory inefficient. When you do that, a new copy of the method is created for each instance of an object. Here's an example:

var Employee = function (name, company, salary) {
  this.name = name || "";       
  this.company = company || "";
  this.salary = salary || 5000;

  // We can create a method like this:
  this.formatSalary = function () {
      return "$ " + this.salary;
  };
};

// Alternatively we can add the method to Employee's prototype:
Employee.prototype.formatSalary2 = function() {
    return "$ " + this.salary;
}

//creating objects
var emp1 = new Employee('Yuri Garagin', 'Company 1', 1000000);
var emp2 = new Employee('Dinesh Gupta', 'Company 2', 1039999);
var emp3 = new Employee('Erich Fromm', 'Company 3', 1299483);

In this case each instance variable emp1, emp2, emp3 has its own copy of theformatSalary method. However the formatSalary2 will only be added once to Employee.prototype.

Question 4. What is “closure” in javascript? Can you provide an example?

Answer

A closure is a function defined inside another function (called parent function) and as such it has access to the variables declared and defined within its parent function's scope.

The closure has access to the variables in three scopes:

  • Variable declared in its own scope
  • Variable declared in its parent function's scope
  • Variable declared in the global namespace
var globalVar = "abc"; //Global variable

// Parent self-invoking function
(function outerFunction (outerArg) { // start of outerFunction's scope

  var outerFuncVar = 'x'; // Variable declared in outerFunction's function scope   
  
  // Closure self-invoking function
  (function innerFunction (innerArg) { // start of innerFunction's scope

    var innerFuncVar = "y"; // variable declared in innerFunction's function scope
    console.log(         
      "outerArg = " + outerArg + "\n" +
      "outerFuncVar = " + outerFuncVar + "\n" +
      "innerArg = " + innerArg + "\n" +
      "innerFuncVar = " + innerFuncVar + "\n" +
      "globalVar = " + globalVar);
  	
  // end of innerFunction's scope
  
  })(5); // Pass 5 as parameter to our Closure

// end of outerFunction's scope

})(7); // Pass 7 as parameter to the Parent function

innerFunction is a closure which is defined inside outerFunction and consequently has access to all the variables which have been declared and defined within outerFunction's scope as well as any variables residing in the program's global scope.

The output of the code above would be:

outerArg = 7
outerFuncVar = x
innerArg = 5
innerFuncVar = y
globalVar = abc

Question 5. Write a mul function which will work properly when invoked with following syntax.

console.log(mul(2)(3)(4)); // output : 24
console.log(mul(4)(3)(4)); // output : 48
Answer
function mul (x) {
  return function (y) { // anonymous function
    return function (z) { // anonymous function
      return x * y * z;
    };
  };
}

Here the mul function accepts the first argument and returns an anonymous function which then takes the second parameter and returns one last anonymous function which finally takes the third and final parameter; the last function then multiplies x, y and z, and returns the result of the operation.

In Javascript, a function defined inside another function has access to the outer function's scope and can consequently return, interact with or pass on to other functions, the variables belonging to the scopes that incapsulate it.

  • A function is an instance of the Object type
  • A function can have properties and has a link to its constructor method
  • A function can be stored as a variable
  • A function can be passed as a parameter to another function
  • A function can be returned by another function

Question 6. How to empty an array in JavaScript?

For instance:

var arrayList =  ['a', 'b', 'c', 'd', 'e', 'f'];

How can we empty the array above?

Answer

There are a 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.

Method 1

arrayList = [];

The code above 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 a 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 referenced the array by its original variable arrayList.

For instance:

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var anotherArrayList = arrayList;  // Referenced arrayList by another variable
arrayList = []; // Empty the array
console.log(anotherArrayList); // Output ['a', 'b', 'c', 'd', 'e', 'f']

Method 2

arrayList.length = 0;

The code above will clear the existing array by setting its length to 0. This way of emptying an array will also update all the reference variables that point to the original array.

For instance:

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var anotherArrayList = arrayList;  // Referenced arrayList by another variable
arrayList.length = 0; // Empty the array by setting length to 0
console.log(anotherArrayList); // Output []

Method 3

arrayList.splice(0, arrayList.length);

Above implementation will also work perfectly. This way of empty the array will also update all the references of the original array.

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var anotherArrayList = arrayList;  // Referenced arrayList by another variable
arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0
console.log(anotherArrayList); // Output []

Method 4

while(arrayList.length) {
  arrayList.pop();
}

Above implementation can also empty the array. But not recommended to use often.

Question 7. How to check if an object is an array or not?

Answer

The best way to find whether an object is instance of a particular class or not using toString method from Object.prototype

var arrayList = [1 , 2, 3];

One of the best use cases of type checking of an object is when we do method overloading in JavaScript. To understand this, let's say we have a method called greet which can take a single string and also a list of strings. To make 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 values?

function greet(param) {
  if() {
    // here have to check whether param is array or not
  }
  else {
  }
}

However, in the above implementation it might not necessary to check the type of the array, we can check for single value string and put array logic code in else block, let see below code for the same.

 function greet(param) {
   if(typeof param === 'string') {
   }
   else {
     // If param is of type array then this block of code would execute
   }
 }

Now it's fine we can go with the previous two implementations, but when we have a situation like a parameter can be single value, array, and object type then we will be in trouble.

Coming back to checking the type of an object, As we mentioned that we can use Object.prototype.toString

if(Object.prototype.toString.call(arrayList) === '[object Array]') {
  console.log('Array!');
}

If you are using jQuery then you can also used jQuery isArray method:

if($.isArray(arrayList)) {
  console.log('Array');
} else {
  console.log('Not an array');
}

FYI jQuery uses Object.prototype.toString.call internally to check whether an object is an array or not.

In modern browser, you can also use:

Array.isArray(arrayList);

Array.isArray is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5

Question 8. What will be the output of the following code?

var output = (function(x) {
  delete x;
  return x;
})(0);

console.log(output);
Answer

The code above will output 0 as output. delete operator is used to delete a property from an object. Here x is not an object, it's a local variable. delete operator doesn't affect local variables.

Question 9. What will be the output of the following code?

var x = 1;
var output = (function() {
  delete x;
  return x;
})();

console.log(output);
Answer

The code above will output 1 as output. delete operator is used to delete a property from an object. Here x is not an object it's global variable of type number.

Question 10. What will be the output of the following code?

var x = { foo : 1};
var output = (function() {
  delete x.foo;
  return x.foo;
})();

console.log(output);
Answer

The code above will output undefined as output. delete operator is used to delete a property from an object. Here x is an object which has foo as a property and from a self-invoking function, we are deleting the foo property of object x and after deletion, we are trying to reference deleted property foo which result undefined.

Question 11. What will be the output of the following code?

var Employee = {
  company: 'xyz'
}
var emp1 = Object.create(Employee);
delete emp1.company
console.log(emp1.company);
Answer The code above will output `xyz` as output. Here `emp1` object got company as **prototype** property. delete operator doesn't delete prototype property.

emp1 object doesn't have company as its 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.

Question 12. What is undefined x 1 in JavaScript

var trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
Answer - When you run the code above and do `console.log(trees);` in chrome developer console then you will get `["redwood", "bay", "cedar", undefined × 1, "maple"]`. - In the recent versions of Chrome you will see the word `empty` of `undefined x 1`. - When you run the same code in Firefox browser console then you will get `["redwood", "bay", "cedar", undefined, "maple"]`

Clearly we can see that Chrome has its own way of displaying uninitialized index in arrays. However when you check trees[3] === undefined in any browser you will get similar output as true.

Note: Please remember that you need not check for the uninitialized index of the array in trees[3] === 'undefined × 1' it will give an error because 'undefined × 1' this is just way of displaying an uninitialized index of an array in chrome.

Question 13. What will be the output of the following code?

var trees = ["xyz", "xxxx", "test", "ryan", "apple"];
delete trees[3];
console.log(trees.length);
Answer The code above will output `5` as output. When we used `delete` operator for deleting an array element then, the array length is not affected by this. This holds even if you deleted all elements of an array using `delete` operator.

So when delete operator removes an array element that deleted element is no longer present in the array. In place of value at deleted index undefined x 1 in chrome and undefined 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"].

Question 14. What will be the output of the following code?

var bar = true;
console.log(bar + 0);   
console.log(bar + "xyz");  
console.log(bar + true);  
console.log(bar + false);
Answer

The code above will output 1, "truexyz", 2, 1 as output. Here's a general guideline for the plus operator:

  • Number + Number -> Addition
  • Boolean + Number -> Addition
  • Boolean + Boolean -> Addition
  • Number + String -> Concatenation
  • String + Boolean -> Concatenation
  • String + String -> Concatenation

Question 15. What will be the output of the following code?

var z = 1, y = z = typeof y;
console.log( 
                       
                    
                    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap