JavaScript Interview Questions Flashcards Preview

Interview Questions > JavaScript Interview Questions > Flashcards

Flashcards in JavaScript Interview Questions Deck (91)
Loading flashcards...
1
Q

What is JavaScript?

A

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.

The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.

2
Q

Name some of the JavaScript features.

A

Following are the features of JavaScript −

JavaScript is a lightweight, interpreted programming language.

JavaScript is designed for creating network-centric applications.

JavaScript is complementary to and integrated with Java.

JavaScript is is complementary to and integrated with HTML.

JavaScript is open and cross-platform.

3
Q

What are the advantages of using JavaScript?

Following are the advantages of using JavaScript −

A

Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.

Immediate feedback to the visitors − They don’t have to wait for a page reload to see if they have forgotten to enter something.

Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.

Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

4
Q

What are disadvantages of using JavaScript?

A

We can not treat JavaScript as a full fledged programming language. It lacks the following important features −

Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.

JavaScript can not be used for Networking applications because there is no such support available.

JavaScript doesn’t have any multithreading or multiprocess capabilities.

5
Q

Is JavaScript a case-sensitive language?

A

Yes! JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

6
Q

How can you create an Object in JavaScript?

A

JavaScript supports Object concept very well. You can create an object using the object literal as follows −

var emp = {
   name: "Zara",
   age: 10
};
7
Q

You can write and read properties of an object using the dot notation as follows −

A
// Getting object properties
emp.name  // ==> Zara
emp.age   // ==> 10
// Setting object properties
emp.name = "Daisy"  // <== Daisy
emp.age  =  20      // <== 20
8
Q

How can you create an Array in JavaScript?

A

You can define arrays using the array literal as follows −

var x = [];
var y = [1, 2, 3, 4, 5];
9
Q

How to read elements of an array in JavaScript?

A

An array has a length property that is useful for iteration. We can read elements of an array as follows −

var x = [1, 2, 3, 4, 5];
for (var i = 0; i < x.length; i++) {
   // Do something with x[i]
}
10
Q

What is a named function in JavaScript? How to define a named function?

A

A named function has a name when it is defined. A named function can be defined using function keyword as follows −

function named(){
   // do some stuff here
}
11
Q

How many types of functions JavaScript supports?

A

A function in JavaScript can be either named or anonymous.

12
Q

How to define a anonymous function?

A

An anonymous function can be defined in similar way as a normal function but it would not have any name.

13
Q

Can you assign a anonymous function to a variable?

A

Yes! An anonymous function can be assigned to a variable.

14
Q

Can you pass a anonymous function as an argument to another function?

A

Yes! An anonymous function can be passed as an argument to another function.

15
Q

What is arguments object in JavaScript?

A

JavaScript variable arguments represents the arguments passed to a function.

16
Q

How can you get the type of arguments passed to a function?

A

Using typeof operator, we can get the type of arguments passed to a function. For example −

function func(x){
   console.log(typeof x, arguments.length);
}
func();                //==> "undefined", 0
func(1);               //==> "number", 1
func("1", "2", "3");   //==> "string", 3
17
Q

How can you get the total number of arguments passed to a function?

A

Using arguments.length property, we can get the total number of arguments passed to a function. For example −

function func(x){
   console.log(typeof x, arguments.length);
}
func();                //==> "undefined", 0
func(1);               //==> "number", 1
func("1", "2", "3");   //==> "string", 3
18
Q

How can you get the reference of a caller function inside a function?

A

The arguments object has a callee property, which refers to the function you’re inside of. For example −

function func() {
   return arguments.callee; 
}
func();                // ==> func
19
Q

What is the purpose of ‘this’ operator in JavaScript?

A

JavaScript famous keyword this always refers to the current context.

20
Q

What are the valid scopes of a variable in JavaScript?

A

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

Global Variables − A global variable has global scope which means it is visible everywhere in your JavaScript code.

Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

21
Q

Which type of variable among global and local, takes precedence over other if names are same?

A

A local variable takes precedence over a global variable with the same name.

22
Q

What is callback?

A

A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered.

23
Q

What is closure?

A

Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope.

24
Q

Give an example of closure?

A

Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them −

function create() {
   var counter = 0;
   return {
      increment: function() {
         counter++;
      },
  print: function() {
     console.log(counter);
  }    } } var c = create(); c.increment(); c.print();     // ==> 1
25
Q

Which built-in method returns the character at the specified index?

A

charAt() method returns the character at the specified index.

26
Q

Which built-in method combines the text of two strings and returns a new string?

A

concat() method returns the character at the specified index.

27
Q

Which built-in method calls a function for each element in the array?

A

forEach() method calls a function for each element in the array.

28
Q

Which built-in method returns the index within the calling String object of the first occurrence of the specified value?

A

indexOf() method returns the index within the calling String object of the first occurrence of the specified value, or −1 if not found.

29
Q

Which built-in method returns the length of the string?

A

length() method returns the length of the string.

30
Q

Which built-in method removes the last element from an array and returns that element?

A

pop() method removes the last element from an array and returns that element.

31
Q

Which built-in method adds one or more elements to the end of an array and returns the new length of the array?

A

push() method adds one or more elements to the end of an array and returns the new length of the array.

32
Q

Which built-in method reverses the order of the elements of an array?

A

reverse() method reverses the order of the elements of an array −− the first becomes the last, and the last becomes the first.

33
Q

Which built-in method sorts the elements of an array?

A

sort() method sorts the elements of an array.

34
Q

Which built-in method returns the characters in a string beginning at the specified location?

A

substr() method returns the characters in a string beginning at the specified location through the specified number of characters.

35
Q

Which built-in method returns the calling string value converted to lower case?

A

toLowerCase() method returns the calling string value converted to lower case.

36
Q

Which built-in method returns the calling string value converted to upper case?

A

toUpperCase() method returns the calling string value converted to upper case.

37
Q

Which built-in method returns the string representation of the number’s value?

A

toString() method returns the string representation of the number’s value.

38
Q

What are the variable naming conventions in JavaScript?

A

While naming your variables in JavaScript keep following rules in mind.

You should not use any of the JavaScript reserved keyword as variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.

JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123test is an invalid variable name but _123test is a valid one.

JavaScript variable names are case sensitive. For example, Name and name are two different variables.

39
Q

How typeof operator works?

A

The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.

The typeof operator evaluates to “number”, “string”, or “boolean” if its operand is a number, string, or boolean value and returns true or false based on the evaluation.

40
Q

What typeof returns for a null value?

A

It returns “object”

41
Q

Can you access Cookie using javascript?

A

JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current web page.

42
Q

How to create a Cookie using JavaScript?

A

The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this −

Syntax −

document.cookie = “key1 = value1; key2 = value2; expires = date”;

Here expires attribute is option. If you provide this attribute with a valid date or time then cookie will expire at the given date or time and after that cookies’ value will not be accessible.

43
Q

How to read a Cookie using JavaScript?

A

Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie.

The document.cookie string will keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value.

You can use strings’ split() function to break the string into key and values.

44
Q

How to delete a Cookie using JavaScript?

A

Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past.

45
Q

How to redirect a url using JavaScript?

A

his is very simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows −

46
Q

How to print a web page using javascript?

A

JavaScript helps you to implement this functionality using print function of window object. The JavaScript print function window.print() will print the current web page when executed.

47
Q

What is Date object in JavaScript?

A

The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ).

Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.

48
Q

What is Number object in JavaScript?

A

The Number object represents numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class.

Syntax −

Creating a number object −

var val = new Number(number);

If the argument cannot be converted into a number, it returns NaN (Not-a-Number).

49
Q

How to handle exceptions in JavaScript?

A

The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try…catch…finally construct as well as the throw operator to handle exceptions.

You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.

50
Q

What is purpose of onError event handler in JavaScript?

A

The onerror event handler was the first feature to facilitate error handling for JavaScript. The error event is fired on the window object whenever an exception occurs on the page.

The onerror event handler provides three pieces of information to identify the exact nature of the error −

Error message − The same message that the browser would display for the given error.

URL − The file in which the error occurred.

Line number − The line number in the given URL that caused the error.

51
Q

What will the code below output to the console and why?

(function(){
  var a = b = 3;
})();

console. log(“a defined? “ + (typeof a !== ‘undefined’));
console. log(“b defined? “ + (typeof b !== ‘undefined’));

A

Since both a and b are defined within the enclosing scope of the function, and since the line they are on begins with the var keyword, most JavaScript developers would expect typeof a and typeof b to both be undefined in the above example.

However, that is not the case. The issue here is that most developers incorrectly understand the statement var a = b = 3; to be shorthand for:

var b = 3;
var a = b;
But in fact, var a = b = 3; is actually shorthand for:
b = 3;
var a = b;
As a result (if you are not using strict mode), the output of the code snippet would be:
a defined? false
b defined? true
But how can b be defined outside of the scope of the enclosing function? Well, since the statement var a = b = 3; is shorthand for the statements b = 3; and var a = b;, b ends up being a global variable (since it is not preceded by the var keyword) and is therefore still in scope even outside of the enclosing function.

Note that, in strict mode (i.e., with use strict), the statement var a = b = 3; will generate a runtime error of ReferenceError: b is not defined, thereby avoiding any headfakes/bugs that might othewise result. (Yet another prime example of why you should use use strict as a matter of course in your code!)

52
Q

What will the code below output to the console and why?

var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};
myObject.func();
A

The above code will output the following to the console:

outer func:  this.foo = bar
outer func:  self.foo = bar
inner func:  this.foo = undefined
inner func:  self.foo = bar
In the outer function, both this and self refer to myObject and therefore both can properly reference and access foo.

In the inner function, though, this no longer refers to myObject. As a result, this.foo is undefined in the inner function, whereas the reference to the local variable self remains in scope and is accessible there.

53
Q

What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?

A

This is an increasingly common practice, employed by many popular JavaScript libraries (jQuery, Node.js, etc.). This technique creates a closure around the entire contents of the file which, perhaps most importantly, creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries.

Another feature of this technique is to allow for an easily referenceable (presumably shorter) alias for a global variable. This is often used, for example, in jQuery plugins. jQuery allows you to disable the $ reference to the jQuery namespace, using jQuery.noConflict(). If this has been done, your code can still use $ employing this closure technique, as follows:

(function($) { /* jQuery plugin code referencing $ */ } )(jQuery);

54
Q

What is the significance, and what are the benefits, of including ‘use strict’ at the beginning of a JavaScript source file?

A

The short and most important answer here is that use strict is a way to voluntarily enforce stricter parsing and error handling on your JavaScript code at runtime. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions. In general, it is a good practice.

Some of the key benefits of strict mode include:

Makes debugging easier. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions, alerting you sooner to problems in your code and directing you more quickly to their source.
Prevents accidental globals. Without strict mode, assigning a value to an undeclared variable automatically creates a global variable with that name. This is one of the most common errors in JavaScript. In strict mode, attempting to do so throws an error.
Eliminates this coercion. Without strict mode, a reference to a this value of null or undefined is automatically coerced to the global. This can cause many headfakes and pull-out-your-hair kind of bugs. In strict mode, referencing a a this value of null or undefined throws an error.
Disallows duplicate parameter values. Strict mode throws an error when it detects a duplicate named argument for a function (e.g., function foo(val1, val2, val1){}), thereby catching what is almost certainly a bug in your code that you might otherwise have wasted lots of time tracking down.
Note: It used to be (in ECMAScript 5) that strict mode would disallow duplicate property names (e.g. var object = {foo: "bar", foo: "baz"};) but as of ECMAScript 2015 this is no longer the case.
Makes eval() safer. There are some differences in the way eval() behaves in strict mode and in non-strict mode. Most significantly, in strict mode, variables and functions declared inside of an eval() statement are not created in the containing scope (they are created in the containing scope in non-strict mode, which can also be a common source of problems).
Throws error on invalid usage of delete. The delete operator (used to remove properties from objects) cannot be used on non-configurable properties of the object. Non-strict code will fail silently when an attempt is made to delete a non-configurable property, whereas strict mode will throw an error in such a case.
55
Q

Consider the two functions below. Will they both return the same thing? Why or why not?

function foo1()
{
  return {
      bar: "hello"
  };
}
function foo2()
{
  return
  {
      bar: "hello"
  };
}
A

Surprisingly, these two functions will not return the same thing. Rather:

console.log(“foo1 returns:”);
console.log(foo1());
console.log(“foo2 returns:”);
console.log(foo2());
will yield:

foo1 returns:
Object {bar: "hello"}
foo2 returns:
undefined 
Not only is this surprising, but what makes this particularly gnarly is that foo2() returns undefined without any error being thrown.

The reason for this has to do with the fact that semicolons are technically optional in JavaScript (although omitting them is generally really bad form). As a result, when the line containing the return statement (with nothing else on the line) is encountered in foo2(), a semicolon is automatically inserted immediately after the return statement.

No error is thrown since the remainder of the code is perfectly valid, even though it doesn’t ever get invoked or do anything (it is simply an unused code block that defines a property bar which is equal to the string “hello”).

This behavior also argues for following the convention of placing an opening curly brace at the end of a line in JavaScript, rather than on the beginning of a new line. As shown here, this becomes more than just a stylistic preference in JavaScript.

56
Q

What is NaN? What is its type? How can you reliably test if a value is equal to NaN?

A

The NaN property represents a value that is “not a number”. This special value results from an operation that could not be performed either because one of the operands was non-numeric (e.g., “abc” / 4), or because the result of the operation is non-numeric (e.g., an attempt to divide by zero).

While this seems straightforward enough, there are a couple of somewhat surprising characteristics of NaN that can result in hair-pulling bugs if one is not aware of them.

For one thing, although NaN means “not a number”, its type is, believe it or not, Number:

console.log(typeof NaN === “number”); // logs “true”
Additionally, NaN compared to anything – even itself! – is false:

console.log(NaN === NaN); // logs “false”
A semi-reliable way to test whether a number is equal to NaN is with the built-in function isNaN(), but even using isNaN() is an imperfect solution.

A better solution would either be to use value !== value, which would only produce true if the value is equal to NaN. Also, ES6 offers a new Number.isNaN() function, which is a different and more reliable than the old global isNaN() function.

57
Q

What will the code below output? Explain your answer.

console. log(0.1 + 0.2);
console. log(0.1 + 0.2 == 0.3);

A

An educated answer to this question would simply be: “You can’t be sure. it might print out “0.3” and “true”, or it might not. Numbers in JavaScript are all treated with floating point precision, and as such, may not always yield the expected results.”

The example provided above is classic case that demonstrates this issue. Surprisingly, it will print out:

0.30000000000000004
false

58
Q

Discuss possible ways to write a function isInteger(x) that determines if x is an integer.

A

This may sound trivial and, in fact, it is trivial with ECMAscript 6 which introduces a new Number.isInteger() function for precisely this purpose. However, prior to ECMAScript 6, this is a bit more complicated, since no equivalent of the Number.isInteger() method is provided.

The issue is that, in the ECMAScript specification, integers only exist conceptually; i.e., numeric values are always stored as floating point values.

With that in mind, the simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following:

function isInteger(x) { return (x^0) === x; } 
The following solution would also work, although not as elegant as the one above:
function isInteger(x) { return Math.round(x) === x; }
Note that Math.ceil() or Math.floor() could be used equally well (instead of Math.round()) in the above implementation.

Or alternatively:

function isInteger(x) { return (typeof x === 'number') &amp;&amp; (x % 1 === 0); }
One fairly common incorrect solution is the following:
function isInteger(x) { return parseInt(x, 10) === x; }
While this parseInt-based approach will work well for many values of x, once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe:

> String(1000000000000000000000)
‘1e+21’

> parseInt(1000000000000000000000, 10)
1

> parseInt(1000000000000000000000, 10) === 1000000000000000000000
false

59
Q

In what order will the numbers 1-4 be logged to the console when the code below is executed? Why?

(function() {
console.log(1);
setTimeout(function(){console.log(2)}, 1000);
setTimeout(function(){console.log(3)}, 0);
console.log(4);
})();

A

The values will be logged in the following order:

1
4
3
2
Let’s first explain the parts of this that are presumably more obvious:

1 and 4 are displayed first since they are logged by simple calls to console.log() without any delay
2 is displayed after 3 because 2 is being logged after a delay of 1000 msecs (i.e., 1 second) whereas 3 is being logged after a delay of 0 msecs.
OK, fine. But if 3 is being logged after a delay of 0 msecs, doesn’t that mean that it is being logged right away? And, if so, shouldn’t it be logged before 4, since 4 is being logged by a later line of code?

The answer has to do with properly understanding JavaScript events and timing.

The browser has an event loop which checks the event queue and processes pending events. For example, if an event happens in the background (e.g., a script onload event) while the browser is busy (e.g., processing an onclick), the event gets appended to the queue. When the onclick handler is complete, the queue is checked and the event is then handled (e.g., the onload script is executed).

Similarly, setTimeout() also puts execution of its referenced function into the event queue if the browser is busy.

When a value of zero is passed as the second argument to setTimeout(), it attempts to execute the specified function “as soon as possible”. Specifically, execution of the function is placed on the event queue to occur on the next timer tick. Note, though, that this is not immediate; the function is not executed until the next tick. That’s why in the above example, the call to console.log(4) occurs before the call to console.log(3) (since the call to console.log(3) is invoked via setTimeout, so it is slightly delayed).

60
Q

Write a simple function (less than 160 characters) that returns a boolean indicating whether or not a string is a palindrome.

A

The following one line function will return true if str is a palindrome; otherwise, it returns false.

function isPalindrome(str) {
  str = str.replace(/\W/g, '').toLowerCase();
  return (str == str.split('').reverse().join(''));
}
For example:

console. log(isPalindrome(“level”)); // logs ‘true’
console. log(isPalindrome(“levels”)); // logs ‘false’
console. log(isPalindrome(“A car, a man, a maraca”)); // logs ‘true’

61
Q

Write a sum method which will work properly when invoked using either syntax below.

console. log(sum(2,3)); // Outputs 5
console. log(sum(2)(3)); // Outputs 5

A

There are (at least) two ways to do this:

METHOD 1

function sum(x) {
  if (arguments.length == 2) {
    return arguments[0] + arguments[1];
  } else {
    return function(y) { return x + y; };
  }
}
In JavaScript, functions provide access to an arguments object which provides access to the actual arguments passed to a function. This enables us to use the length property to determine at runtime the number of arguments passed to the function.

If two arguments are passed, we simply add them together and return.

Otherwise, we assume it was called in the form sum(2)(3), so we return an anonymous function that adds together the argument passed to sum() (in this case 2) and the argument passed to the anonymous function (in this case 3).

METHOD 2

function sum(x, y) {
  if (y !== undefined) {
    return x + y;
  } else {
    return function(y) { return x + y; };
  }
}
When a function is invoked, JavaScript does not require the number of arguments to match the number of arguments in the function definition. If the number of arguments passed exceeds the number of arguments in the function definition, the excess arguments will simply be ignored. On the other hand, if the number of arguments passed is less than the number of arguments in the function definition, the missing arguments will have a value of undefined when referenced within the function. So, in the above example, by simply checking if the 2nd argument is undefined, we can determine which way the function was invoked and proceed accordingly.
62
Q

Consider the following code snippet:

for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
  btn.addEventListener('click', function(){ console.log(i); });
  document.body.appendChild(btn);
}
(a) What gets logged to the console when the user clicks on “Button 4” and why?

(b) Provide one or more alternate implementations that will work as expected.

A

(a) No matter what button the user clicks the number 5 will always be logged to the console. This is because, at the point that the onclick method is invoked (for any of the buttons), the for loop has already completed and the variable i already has a value of 5. (Bonus points for the interviewee if they know enough to talk about how execution contexts, variable objects, activation objects, and the internal “scope” property contribute to the closure behavior.)
(b) The key to making this work is to capture the value of i at each pass through the for loop by passing it into a newly created function object. Here are three possible ways to accomplish this:

for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
  btn.addEventListener('click', (function(i) {
    return function() { console.log(i); };
  })(i));
  document.body.appendChild(btn);
}
Alternatively, you could wrap the entire call to btn.addEventListener in the new anonymous function:
for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
  (function (i) {
    btn.addEventListener('click', function() { console.log(i); });
  })(i);
  document.body.appendChild(btn);
}
Or, we could replace the for loop with a call to the array object’s native forEach method:
['a', 'b', 'c', 'd', 'e'].forEach(function (value, i) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
  btn.addEventListener('click', function() { console.log(i); });
  document.body.appendChild(btn);
});
63
Q

Assuming d is an “empty” object in scope, say:

var d = {};
…what is accomplished using the following code?

[ ‘zebra’, ‘horse’ ].forEach(function(k) {
d[k] = undefined;
});

A

The snippet of code shown above sets two properties on the object d. Ideally, any lookup performed on a JavaScript object with an unset key evaluates to undefined. But running this code marks those properties as “own properties” of the object.

This is a useful strategy for ensuring that an object has a given set of properties. Passing this object to Object.keys will return an array with those set keys as well (even if their values are undefined).

64
Q

What will the code below output to the console and why?

var arr1 = “john”.split(‘’);
var arr2 = arr1.reverse();
var arr3 = “jones”.split(‘’);
arr2.push(arr3);
console.log(“array 1: length=” + arr1.length + “ last=” + arr1.slice(-1));
console.log(“array 2: length=” + arr2.length + “ last=” + arr2.slice(-1));

A

The logged output will be:

“array 1: length=5 last=j,o,n,e,s”
“array 2: length=5 last=j,o,n,e,s”
arr1 and arr2 are the same after the above code is executed for the following reasons:

Calling an array object’s reverse() method doesn’t only return the array in reverse order, it also reverses the order of the array itself (i.e., in this case, arr1).
The reverse() method returns a reference to the array itself (i.e., in this case, arr1). As a result, arr2 is simply a reference to (rather than a copy of) arr1. Therefore, when anything is done to arr2 (i.e., when we invoke arr2.push(arr3);), arr1 will be affected as well since arr1 and arr2 are simply references to the same object.
And a couple of side points here that can sometimes trip someone up in answering this question:

Passing an array to the push() method of another array pushes that entire array as a single element onto the end of the array. As a result, the statement arr2.push(arr3); adds arr3 in its entirety as a single element to the end of arr2 (i.e., it does not concatenate the two arrays, that’s what the concat() method is for).
Like Python, JavaScript honors negative subscripts in calls to array methods like slice() as a way of referencing elements at the end of the array; e.g., a subscript of -1 indicates the last element in the array, and so on.

65
Q

What will the code below output to the console and why ?

console. log(1 + “2” + “2”);
console. log(1 + +”2” + “2”);
console. log(1 + -“1” + “2”);
console. log(+”1” + “1” + “2”);
console. log( “A” - “B” + “2”);
console. log( “A” - “B” + 2);

A

The above code will output the following to the console:

"122"
"32"
"02"
"112"
"NaN2"
NaN
Here’s why…

The fundamental issue here is that JavaScript (ECMAScript) is a loosely typed language and it performs automatic type conversion on values to accommodate the operation being performed. Let’s see how this plays out with each of the above examples.

Example 1: 1 + “2” + “2” Outputs: “122” Explanation: The first operation to be performed in 1 + “2”. Since one of the operands (“2”) is a string, JavaScript assumes it needs to perform string concatenation and therefore converts the type of 1 to “1”, 1 + “2” yields “12”. Then, “12” + “2” yields “122”.

Example 2: 1 + +”2” + “2” Outputs: “32” Explanation: Based on order of operations, the first operation to be performed is +”2” (the extra + before the first “2” is treated as a unary operator). Thus, JavaScript converts the type of “2” to numeric and then applies the unary + sign to it (i.e., treats it as a positive number). As a result, the next operation is now 1 + 2 which of course yields 3. But then, we have an operation between a number and a string (i.e., 3 and “2”), so once again JavaScript converts the type of the numeric value to a string and performs string concatenation, yielding “32”.

Example 3: 1 + -“1” + “2” Outputs: “02” Explanation: The explanation here is identical to the prior example, except the unary operator is - rather than +. So “1” becomes 1, which then becomes -1 when the - is applied, which is then added to 1 yielding 0, which is then converted to a string and concatenated with the final “2” operand, yielding “02”.

Example 4: +”1” + “1” + “2” Outputs: “112” Explanation: Although the first “1” operand is typecast to a numeric value based on the unary + operator that precedes it, it is then immediately converted back to a string when it is concatenated with the second “1” operand, which is then concatenated with the final “2” operand, yielding the string “112”.

Example 5: “A” - “B” + “2” Outputs: “NaN2” Explanation: Since the - operator can not be applied to strings, and since neither “A” nor “B” can be converted to numeric values, “A” - “B” yields NaN which is then concatenated with the string “2” to yield “NaN2”.

Example 6: “A” - “B” + 2 Outputs: NaN Explanation: As exlained in the previous example, “A” - “B” yields NaN. But any operator applied to NaN with any other numeric operand will still yield NaN.

66
Q

The following recursive code will cause a stack overflow if the array list is too large. How can you fix this and still retain the recursive pattern?

var list = readHugeList();

var nextListItem = function() {
    var item = list.pop();
    if (item) {
        // process the list item...
        nextListItem();
    }
};
A

The potential stack overflow can be avoided by modifying the nextListItem function as follows:

var list = readHugeList();

var nextListItem = function() {
    var item = list.pop();
    if (item) {
        // process the list item...
        setTimeout( nextListItem, 0);
    }
};
The stack overflow is eliminated because the event loop handles the recursion, not the call stack. When nextListItem runs, if item is not null, the timeout function (nextListItem) is pushed to the event queue and the function exits, thereby leaving the call stack clear. When the event queue runs its timed-out event, the next item is processed and a timer is set to again invoke nextListItem. Accordingly, the method is processed from start to finish without a direct recursive call, so the call stack remains clear, regardless of the number of iterations.
67
Q

What is a “closure” in JavaScript? Provide an example.

A

A closure is an inner function that has access to the variables in the outer (enclosing) function’s scope chain. The closure has access to variables in three scopes; specifically: (1) variable in its own scope, (2) variables in the enclosing function’s scope, and (3) global variables.

Here is a simple example:

var globalVar = “xyz”;

(function outerFunc(outerArg) {
  var outerVar = 'a';
  (function innerFunc(innerArg) {
    var innerVar = 'b';
    console.log(
      "outerArg = " + outerArg + "\n" +
      "innerArg = " + innerArg + "\n" +
      "outerVar = " + outerVar + "\n" +
      "innerVar = " + innerVar + "\n" +
      "globalVar = " + globalVar);

})(456);
})(123);

In the above example, variables from innerFunc, outerFunc, and the global namespace are all in scope in the innerFunc. The above code will therefore produce the following output:

outerArg = 123
innerArg = 456
outerVar = a
innerVar = b
globalVar = xyz
68
Q

What will be the output of the following code:

for (var i = 0; i < 5; i++) {
  setTimeout(function() { console.log(i); }, i * 1000 );
}
Explain your answer. How could the use of closures help here?
A

The code sample shown will not display the values 0, 1, 2, 3, and 4 as might be expected; rather, it will display 5, 5, 5, 5, and 5.

The reason for this is that each function executed within the loop will be executed after the entire loop has completed and all will therefore reference the last value stored in i, which was 5.

Closures can be used to prevent this problem by creating a unique scope for each iteration, storing each unique value of the variable within its scope, as follows:

for (var i = 0; i < 5; i++) {
	(function(x) {
    	setTimeout(function() { console.log(x); }, x * 1000 );
    })(i);
}
This will produce the presumably desired result of logging 0, 1, 2, 3, and 4 to the console.
69
Q

What would the following lines of code output to the console?

console.log(“0 || 1 = “+(0 || 1));
console.log(“1 || 2 = “+(1 || 2));
console.log(“0 && 1 = “+(0 && 1));
console.log(“1 && 2 = “+(1 && 2));
Explain your answer.

A

The code will output the following four lines:

0 || 1 = 1
1 || 2 = 1
0 &amp;&amp; 1 = 0
1 &amp;&amp; 2 = 2
In JavaScript, both || and &amp;&amp; are logical operators that return the first fully-determined “logical value” when evaluated from left to right.

The or (||) operator. In an expression of the form X||Y, X is first evaluated and interpreted as a boolean value. If this boolean value is true, then true (1) is returned and Y is not evaluated, since the “or” condition has already been satisfied. If this boolean value is “false”, though, we still don’t know if X||Y is true or false until we evaluate Y, and interpret it as a boolean value as well.

Accordingly, 0 || 1 evaluates to true (1), as does 1 || 2.

The and (&&) operator. In an expression of the form X&&Y, X is first evaluated and interpreted as a boolean value. If this boolean value is false, then false (0) is returned and Y is not evaluated, since the “and” condition has already failed. If this boolean value is “true”, though, we still don’t know if X&&Y is true or false until we evaluate Y, and interpret it as a boolean value as well.

However, the interesting thing with the && operator is that when an expression is evaluated as “true”, then the expression itself is returned. This is fine, since it counts as “true” in logical expressions, but also can be used to return that value when you care to do so. This explains why, somewhat surprisingly, 1 && 2 returns 2 (whereas you might it expect it to return true or 1).

70
Q

What will be the output when the following code is executed? Explain.

console. log(false == ‘0’)
console. log(false === ‘0’)

A

The code will output:

true
false
In JavaScript, there are two sets of equality operators. The triple-equal operator === behaves like any traditional equality operator would: evaluates to true if the two expressions on either of its sides have the same type and the same value. The double-equal operator, however, tries to coerce the values before comparing them. It is therefore generally good practice to use the === rather than ==. The same holds true for !== vs !=.

71
Q

What is the output out of the following code? Explain your answer.

var a={},
    b={key:'b'},
    c={key:'c'};

a[b]=123;
a[c]=456;

console.log(a[b]);

A

The output of this code will be 456 (not 123).

The reason for this is as follows: When setting an object property, JavaScript will implicitly stringify the parameter value. In this case, since b and c are both objects, they will both be converted to “[object Object]”. As a result, a[b] anda[c] are both equivalent to a[“[object Object]”] and can be used interchangeably. Therefore, setting or referencing a[c] is precisely the same as setting or referencing a[b].

72
Q

What will the following code output to the console:

console.log((function f(n){return ((n > 1) ? n * f(n-1) : n)})(10));
Explain your answer.

A

The code will output the value of 10 factorial (i.e., 10!, or 3,628,800).

Here’s why:

The named function f() calls itself recursively, until it gets down to calling f(1) which simply returns 1. Here, therefore, is what this does:

f(1): returns n, which is 1
f(2): returns 2 * f(1), which is 2
f(3): returns 3 * f(2), which is 6
f(4): returns 4 * f(3), which is 24
f(5): returns 5 * f(4), which is 120
f(6): returns 6 * f(5), which is 720
f(7): returns 7 * f(6), which is 5040
f(8): returns 8 * f(7), which is 40320
f(9): returns 9 * f(8), which is 362880
f(10): returns 10 * f(9), which is 3628800
73
Q

Consider the code snippet below. What will the console output be and why?

(function(x) {
    return (function(y) {
        console.log(x);
    })(2)
})(1);
A

The output will be 1, even though the value of x is never set in the inner function. Here’s why:

As explained in our JavaScript Hiring Guide, a closure is a function, along with all variables or functions that were in-scope at the time that the closure was created. In JavaScript, a closure is implemented as an “inner function”; i.e., a function defined within the body of another function. An important feature of closures is that an inner function still has access to the outer function’s variables.

Therefore, in this example, since x is not defined in the inner function, the scope of the outer function is searched for a defined variable x, which is found to have a value of 1.

74
Q

What will the following code output to the console and why:

var hero = {
    _name: 'John Doe',
    getSecretIdentity: function (){
        return this._name;
    }
};

var stoleSecretIdentity = hero.getSecretIdentity;

console.log(stoleSecretIdentity());
console.log(hero.getSecretIdentity());
What is the issue with this code and how can it be fixed.

A

The code will output:

undefined
John Doe
The first console.log prints undefined because we are extracting the method from the hero object, so stoleSecretIdentity() is being invoked in the global context (i.e., the window object) where the _name property does not exist.

One way to fix the stoleSecretIdentity() function is as follows:

var stoleSecretIdentity = hero.getSecretIdentity.bind(hero);

75
Q

Create a function that, given a DOM Element on the page, will visit the element itself and all of its descendents (not just its immediate children). For each element visited, the function should pass that element to a provided callback function.

The arguments to the function should be:

a DOM element
a callback function (that takes a DOM element as its argument)

A

Visiting all elements in a tree (DOM) is a classic Depth-First-Search algorithm application. Here’s an example solution:

function Traverse(p_element,p_callback) {
p_callback(p_element);
var list = p_element.children;
for (var i = 0; i < list.length; i++) {
Traverse(list[i],p_callback); // recursive call
}
}

76
Q

Testing your this knowledge in JavaScript: What is the output of the following code?

var length = 10;
function fn() {
	console.log(this.length);
}
var obj = {
  length: 5,
  method: function(fn) {
    fn();
    arguments[0]();
  }
};

obj.method(fn, 1);

A

Output:

10
2
Justification:

In first case, as fn is passed as a parameter to the function method, the scope (this) of the function fn is window. var length = 10; is declared at the window level. It also can be accessed as window.length or length or this.length (when this === window.)

method is bound to Object obj, and obj.method is called with parameters fn and 1. Though method is accepting only one parameter, while invoking it has passed two parameters; the first is a function callback and other is just a number.

When fn() is called inside method, which was passed the function as a parameter at the global level, this.length will have access to var length = 10 (declared globally) not length = 5 as defined in Object obj.

Now, we know that we can access any number of arguments in a JavaScript function using the arguments[] array.

Hence arguments0 is nothing but calling fn(). Inside fn now, the scope of this function becomes the arguments array, and logging the length of arguments[] will return 2.

Hence the output will be as above.

77
Q

Consider the following code. What will the output be, and why?

(function () {
    try {
        throw new Error();
    } catch (x) {
        var x = 1, y = 2;
        console.log(x);
    }
    console.log(x);
    console.log(y);
})();
A

1
undefined
2
var statements are hoisted (without their value initialization) to the top of the global or function scope it belongs to, even when it’s inside a with or catch block. However, the error’s identifier is only visible inside the catch block. It is equivalent to:

(function () {
    var x, y; // outer and hoisted
    try {
        throw new Error();
    } catch (x /* inner */) {
        x = 1; // inner x, not the outer one
        y = 2; // there is only one y, which is in the outer scope
        console.log(x /* inner */);
    }
    console.log(x);
    console.log(y);
})();
78
Q

What will be the output of this code?

var x = 21;
var girl = function () {
    console.log(x);
    var x = 20;
};
girl ();
A

Neither 21, nor 20, the result is undefined

It’s because JavaScript initialization is not hoisted.

(Why doesn’t it show the global value of 21? The reason is that when the function is executed, it checks that there’s a local x variable present but doesn’t yet declare it, so it won’t look for global one.)

79
Q

How do you clone an object?

A
var obj = {a: 1 ,b: 2}
var objclone = object.assign({},obj);
Now the value of objclone is {a: 1 ,b: 2} but points to a different object than obj.
80
Q
for (let i = 0; i < 5; i++) {
  setTimeout(function() { console.log(i); }, i * 1000 );
}
What will this code print?
A

The first statement returns true which is as expected.

The second returns false because of how the engine works regarding operator associativity for < and >. It compares left to right, so 3 > 2 > 1 JavaScript translates to true > 1. true has value 1, so it then compares 1 > 1, which is false.

81
Q

How do you add an element at the begining of an array? How do you add one at the end?

A

var myArray = new Array(‘a’, ‘b’, ‘c’, ‘d’);
myArray.push(‘end’);
myArray.unshift(‘start’);
console.log(myArray); // [“start”, “a”, “b”, “c”, “d”, “end”]

82
Q

Imagine you have this code:

var a = [1, 2, 3];
a) Will this result in a crash?

a[10] = 99;
b) What will this output?

console.log(a[6]);

A

a) It will not crash. The JavaScript engine will fill array slots 3 through 9 with undefined.
b) Likewise, a[6] will output undefined.

83
Q

What is the value of typeof undefined == typeof NULL?

A

The expression will be evaluated to true, since NULL will be treated as any other undefined variable.

Note: JavaScript is case-sensitive and here we are using NULL instead of null.

84
Q

What would following code return?

console.log(typeof typeof 1);

A

string

typeof 1 will return “number” and typeof “number” will return string.

85
Q

Difference between Function, Method and Constructor calls in JavaScript.

A

functions : The simplest usages of function call:

function helloWorld(name) {
  return "hello world, " + name;
}

helloWorld(“JS Geeks”); // “hello world JS Geeks”
Methods in JavaScript are nothing more than object properties that reference to a function.

var obj = {
  helloWorld : function() {
    return "hello world, " + this.name;
  },
  name: 'John Carter'
}
obj.helloWorld(); // // "hello world John Carter"
Notice how helloWorld refer to this properties of obj. Here it's clear or you might have already understood that this gets bound to obj. But the interesting point that we can copy a reference to the same function helloWorld in another object and get a difference answer. Let see:

var obj2 = {
helloWorld : obj.helloWorld,
name: ‘John Doe’
}
obj2.helloWorld(); // “hello world John Doe”
You might be wonder what exactly happens in a method call here. Here we call the expression itself determine the binding of this this, The expression obj2.helloWorld() looks up the helloWorld property of obj and calls it with receiver object obj2.

The third use of functions is as constructors. Like function and method, constructors are defined with function.

function Employee(name, age) {
  this.name = name;
  this.age = age;
}

var emp1 = new Employee(‘John Doe’, 28);
emp1.name; // “John Doe”
emp1.age; // 28
Unlike function calls and method calls, a constructor call new Employee(‘John Doe’, 28) create a brand new object and passes it as the value of this, and implicitly returns the new object as its result.

The primary role of the constructor function is to initialize the object.

86
Q

Write a mul function which will output when invoked as below syntax.

console. log(mul(2)(3)(4)); // output : 24
console. log(mul(4)(3)(4)); // output : 48

A

Below is code followed by an explanation how it works:

function mul (x) {
  return function (y) { // anonymous function
    return function (z) { // anonymous function
      return x * y * z;
    };
  };
}
Here mul function accept the first argument and return anonymous function which take the second parameter and return anonymous function which take the third parameter and return multiplication of arguments which is being passed in successive.

In Javascript function defined inside has access to outer function variable and function is a first class object so it can be returned by a function as well and passed as the argument in another function.

A function is an instance of the Object type
A function can have properties and has a link back to its constructor method
Function can be stored as variable
Function can be pass as a parameter to another function
Function can be returned from function

87
Q

What is the difference between a method and a function in javascript?

A

A function is a piece of code that is called by name and function itself not associated with any object and not defined inside any object. It can be passed data to operate on (i.e. parameter) and can optionally return data (the return value).

// Function definition
function myFunc() {
  // Do some stuff;
}
// Calling function
myFunc();
Here myFunc() function call is not associated with object hence not invoked through any object.

A function can be self-invoking anonymous function or named self-invoking function

// Named Self-invoking Function
(function myFunc() {
  // Do some stuff;
})();
// Anonymous Self-invoking Function
(function() {
  // Do some stuff;
})();
In a case of named self-invoking anonymous function or anonymous self-invoking function, there is no need of call function explicitly.

A method is a piece of code that is called by name and that is associated with the object. In most respects it is identical to function call except for some key difference:

It is implicitly passed for the object for which it was called.
It is able to operate on data that is contained within the class (remembering that an object is an instance of a class- the class is the definition, the object is an instance of that)
Method call is always associated with object
var methodObject = {
  attribute: "xyz",
  display: function () {  // Method
    console.log(this.attribute);
  }
};

// Call method
methodObject.display();
Here methodObject is an object and display is a method which is associated with methodObject.

88
Q

What is JavaScript Self-Invoking anonymous function or Self-Executing anonymous function.

A

A self-invoking anonymous function also called self-executing anonymous function runs immediately or automatically when we define it and self-invoking anonymous function doesn’t have any name at all. Self-Invoking anonymous function syntax:

(function() {
console.log(“Self-Invoking function code logic “);
})();
Output: Self-Invoking function code logic
We must have to know the fact that JavaScript functions run immediately when we put () after their names.

function display() {
console.log(“Display me”);
}
display(); // This will run immediately

Output: “Display me”
/*
This will not run immediately as we haven’t put () after function
name, function name is use full when we want to pass it as
callback to another function or method.
*/
display;

function testCallBack(callback) {
  callback ();  // This will be call display method immediately if callback parameter is being set method display
}
testCallBack(display); // Here display function is being passed as callback
89
Q

What are the way by which we can create object in JavaScript ?

A

Method 1: Function Based

If we want to create several similar objects. In below code sample, Employee which is called constructor function. This is similar to classes in object oriented languages.

  function Employee(fName, lName, age, salary){
  	this.firstName = fName;
  	this.lastName = lName;
  	this.age = age;
  	this.salary = salary;
  }
  // Creating multiple object which have similar property but diff value assigned to object property.
  var employee1 = new Employee('John', 'Moto', 24, '5000$');
  var employee1 = new Employee('Ryan', 'Jor', 26, '3000$');
  var employee1 = new Employee('Andre', 'Salt', 26, '4000$');
Method 2: Object Literal

Object Literal is best way to create an object and this is used frequently. Below is code sample for create employee object which contains property as well as method.

var employee = {
	name : 'Nishant',
	salary : 245678,
	getName : function(){
		return this.name;
	}
}
Below code sample is Nested Object Literal, Here address is an object inside employee object.
var employee = {
	name : 'Nishant',
	salary : 245678,
	address : {
		addressLine1 : 'BITS Pilani',
		addressLine2 : 'Vidya Vihar'.
		phoneNumber: {
		  workPhone: 7098889765,
		  homePhone: 1234567898
		}
	}
}
Method 3: Using JavaScript new keyword

In below code sample object has been created using Object constructor function.

var employee = new Object(); // Created employee object using new keywords and Object()
employee.name = 'Nishant';
employee.getName = function(){
	return this.name;
}
Note: As a best practices object literal way is used to create object over this method.
90
Q

Write a function called deepClone which takes an object and creates a object copy of it.

A
var newObject = deepClone(obj);
Solution:
function deepClone(object){
	var newObject = {};
	for(var key in object){
		if(typeof object[key] === 'object'){
		 newObject[key] = deepClone(object[key]);
		}else{
		 newObject[key] = object[key];
		}
	}
	return newObject;
}
Explanation: We have been asked to do deep copy of object so What's basically it's mean ??. Let's understand in this way you have been given an object personalDetail this object contains some property which again a type of object here as you can see address is an object and phoneNumber in side an address is also an object. In simple term personalDetail is nested object(object inside object). So Here deep copy means we have to copy all the property of personalDetail object including nested object.
var personalDetail = {
	name : 'Nishant',
	address : {
	  location: 'xyz',
	  zip : '123456',
	  phoneNumber : {
	    homePhone: 8797912345,
	    workPhone : 1234509876
	  }
	}
}
So when we do deep clone then we should copy every property (including the nested object).
91
Q

What is Function binding ?

A

Function binding falls in advance JavaScript category and this is very popular technique to use in conjunction with event handler and callback function to preserve code execution context while passing function as a parameter.
Let’s consider the following example:

var clickHandler = {
	message: 'click event handler',
	handleClick: function(event) {
		console.log(this.message);
	}
};

var btn = document.getElementById(‘myBtn’);
// Add click event to btn
btn.addEventListener(‘click’, clickHandler.handleClick);
Here in this example clickHandler object is created which contain message properties and handleClick method.

We have assigned handleClick method to a DOM button, which will be executed in response of click. When the button is clicked, then handleClick method is being called and console message. Here console.log should log the click event handler message but it actually log undefined.

The problem of displaying undefined is because of the execution context of clickHandler.handleClick method is not being saved hence this pointing to button btn object. We can fix this issue using bind method.

var clickHandler = {
	message: 'click event handler',
	handleClick: function(event) {
		console.log(this.message);
	}
};
var btn = document.getElementById('myBtn');
// Add click event to btn and bind the clickHandler object
btn.addEventListener('click', clickHandler.handleClick.bind(clickHandler));
bind method is available to all the function similar to call and apply method which take argument value of this.