Javascript Interview Questions

Javascript Interview Questions


1. What Is Node.js?

Node.js is a web application framework built on Google Chrome's JavaScript Engine(V8 Engine).

Node.js comes with runtime environment on which a Javascript based script can be interpreted and executed (It is analogus to JVM to JAVA byte code). This runtime allows to execute a JavaScript code on any machine outside a browser. Because of this runtime of Node.js, JavaScript is now can be executed on server as well.

Node.js also provides a rich library of various javascript modules which eases the developement of web application using Node.js to great extents.

Node.js = Runtime Environment + JavaScript Library

2. What Do You Mean By Asynchronous Api?

All APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data. Server moves to next API after calling it and a notification mechanism of Events of Node.js helps server to get response from the previous API call.

3. What Are The Benefits Of Using Node.js?

Following are main benefits of using Node.js

Aynchronous and Event Driven All APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data. Server moves to next API after calling it and a notification mechanism of Events of Node.js helps server to get response from the previous API call.

Very Fast Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.

Single Threaded but highly Scalable - Node.js uses a single threaded model with event looping. Event mechanism helps server to respond in a non-bloking ways and makes server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and same program can services much larger number of requests than traditional server like Apache HTTP Server.

No Buffering - Node.js applications never buffer any data. These applications simply output the data in chunks.

4. Is It Free To Use Node.js?

Yes! Node.js is released under the MIT license and is free to use.

5. Is Node A Single Threaded Application?

Yes! Node uses a single threaded model with event looping.

6. What Is Repl In Context Of Node?

REPL stands for Read Eval Print Loop and it represents a computer environment like a window console or unix/linux shell where a command is entered and system responds with an output. Node.js or Node comes bundled with a REPL environment. It performs the following desired tasks.

Read - Reads user's input, parse the input into JavaScript data-structure and stores in memory.

Eval - Takes and evaluates the data structure

Print - Prints the result

Loop - Loops the above command until user press ctrl-c twice.

7. What Is The Difference Of Using Var And Not Using Var In Repl While Dealing With Variables?

Use variables to store values and print later. if var keyword is not used then value is stored in the variable and printed. Wheras if var keyword is used then value is stored but not printed. You can use both variables later.

8. What Is The Use Of Underscore Variable In Repl?

Use _ to get the last result.

C:Nodejs_WorkSpace>node

> var x = 10

undefined

> var y = 20

undefined

> x + y

30

> var sum = _

undefined

> console.log(sum)

30

undefined

> 

9. What Is Npm?

npm stands for Node Package Manager. npm provides following two main functionalities:

Online repositories for node.js packages/modules which are searchable on search.nodejs.org

Command line utility to install packages, do version management and dependency management of Node.js packages.

10. What Is Global Installation Of Dependencies?

Globally installed packages/dependencies are stored in <user-directory>/npm directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but can not be imported using require() in Node application directly. To install a Node project globally use -g flag.

C:Nodejs_WorkSpace>npm install express -g

11. What Is Local Installation Of Dependencies?

By default, npm installs any dependency in the local mode. Here local mode refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require(). To install a Node project locally following is the syntax.

C:Nodejs_WorkSpace>npm install express

12. How To Check The Already Installed Dependencies Which Are Globally Installed Using Npm?

Use the following command:

C:Nodejs_WorkSpace>npm ls -g

13. What Is Package.json?

package.json is present in the root directory of any Node application/module and is used to define the properties of a package.

14. Name Some Of The Attributes Of Package.json?

Following are the attributes of Package.json

name - name of the package

version - version of the package

description - description of the package

homepage - homepage of the package

author - author of the package

contributors - name of the contributors to the package

dependencies - list of dependencies. npm automatically installs all the dependencies mentioned here in the node_module folder of the package.

repository - repository type and url of the package

main - entry point of the package

keywords - keywords

15. How To Uninstall A Dependency Using Npm?

Use following command to uninstall a module.

C:Nodejs_WorkSpace>npm uninstall dependency-name

16. How To Update A Dependency Using Npm?

Update package.json and change the version of the dependency which to be updated and run the following command.

C:Nodejs_WorkSpace>npm update

17. What Is Callback?

Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is such a way that they supports callbacks. For example, a function to read a file may start reading file and return the control to execution environment immidiately so that next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result.

18. What Is A Blocking Code?

If application has to wait for some I/O operation in order to complete its execution any further then the code responsible for waiting is known as blocking code.

19. How Node Prevents Blocking Code?

By providing callback function. Callback function gets called whenever corresponding event triggered.

20. What Is Event Loop?

Node js is a single threaded application but it support concurrency via concept of event and callbacks. As every API of Node js are asynchronous and being a single thread, it uses async function calls to maintain the concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever any task get completed, it fires the corresponding event which signals the event listener function to get executed.

21. What Is Event Emmitter?

EventEmitter class lies in events module. It is accessibly via following syntax:

//import events module

var events = require('events');

//create an eventEmitter object

var eventEmitter = new events.EventEmitter();

When an EventEmitter instance faces any error, it emits an 'error' event. When new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired.

EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event.

22. What Is Purpose Of Buffer Class In Node?

Buffer class is a global class and can be accessed in application without importing buffer module. A Buffer is a kind of an array of integers and corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.

23. What Is Piping In Node?

Piping is a mechanism to connect output of one stream to another stream. It is normally used to get data from one stream and to pass output of that stream to another stream. There is no limit on piping operations. Consider the above example, where we've read test.txt using readerStream and write test1.txt using writerStream. Now we'll use the piping to simplify our operation or reading from one file and writing to another file.

24. Which Module Is Used For File Based Operations?

fs module is used for file based operations.

var fs = require("fs")

25. Which Module Is Used For Buffer Based Operations?

buffer module is used for buffer based operations.

var buffer = require("buffer")

26. Which Module Is Used For Web Based Operations?

http module is used for web based operations.

var http = require("http")

27. What Is Difference Between Synchronous And Asynchronous Method Of Fs Module?

Every method in fs module have synchronous as well as asynchronous form. Asynchronous methods takes a last parameter as completion function callback and first parameter of the callback function is error. It is preferred to use asynchronous method instead of synchronous method as former never block the program execution where the latter one does.

28. Name Some Of The Flags Used In Read/write Operation On Files.

flags for read/write operations are following:

r - Open file for reading. An exception occurs if the file does not exist.

r+ - Open file for reading and writing. An exception occurs if the file does not exist.

rs - Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache. This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it. Note that this doesn't turn fs.open() into a synchronous blocking call. If that's what you want then you should be using fs.openSync()

rs+ - Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about using this with caution.

w - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

wx - Like 'w' but fails if path exists.

w+ - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

wx+ - Like 'w+' but fails if path exists.

a - Open file for appending. The file is created if it does not exist.

ax - Like 'a' but fails if path exists.

a+ - Open file for reading and appending. The file is created if it does not exist.

ax+' - Like 'a+' but fails if path exists.

29. What Are Streams?

Streams are objects that let you read data from a source or write data to a destination in continous fashion.

30. How Many Types Of Streams Are Present In Node?

In Node.js, there are four types of streams.

Readable - Stream which is used for read operation.

Writable - Stream which is used for write operation.

Duplex - Stream which can be used for both read and write operation.

Transform - A type of duplex stream where the output is computed based on input.

31. Name Some Of The Events Fired By Streams.

Each type of Stream is an EventEmitter instance and throws several events at different instance of times. For example, some of the commonly used events are:

data - This event is fired when there is data is available to read.

end - This event is fired when there is no more data to read.

error - This event is fired when there is any error receiving or writing data.

finish - This event is fired when all data has been flushed to underlying system

32. What Is Chaining In Node?

Chanining is a mechanism to connect output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations.

33. How Will You Open A File Using Node?

Following is the syntax of the method to open a file in asynchronous mode:

fs.open(path, flags[, mode], callback)

Parameters

Here is the description of the parameters used:

path - This is string having file name including path.

flags - Flag tells the behavior of the file to be opened. All possible values have been mentioned below.

mode - This sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable.

callback - This is the callback function which gets two arguments (err, fd).

34. How Will You Read A File Using Node?

Following is the syntax of one of the methods to read from a file:

fs.read(fd, buffer, offset, length, position, callback)

This method will use file descriptor to read the file, if you want to read file using file name directly then you should use another method available.

Parameters

Here is the description of the parameters used:

fd - This is the file descriptor returned by file fs.open() method.

buffer - This is the buffer that the data will be written to.

offset - This is the offset in the buffer to start writing at.

length - This is an integer specifying the number of bytes to read.

position - This is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position.

callback - This is the callback function which gets the three arguments, (err, bytesRead, buffer).

35. How Will You Write A File Using Node?

Following is the syntax of one of the methods to write into a file:

fs.writeFile(filename, data[, options], callback)

This method will over-write the file if file already exists. If you want to write into an existing file then you should use another method available.

Parameters

Here is the description of the parameters used:

path - This is string having file name including path.

data - This is the String or Buffer to be written into the file.

options - The third parameter is an object which will hold {encoding, mode, flag}. By default encoding is utf8, mode is octal value 0666 and flag is 'w'

callback - This is the callback function which gets a single parameter err and used to to return error in case of any writing error.

36. How Will You Close A File Using Node?

Following is the syntax of one of the methods to close an opened file:

fs.close(fd, callback)

Parameters

Here is the description of the parameters used:

fd - This is the file descriptor returned by file fs.open() method.

callback - This is the callback function which gets no arguments other than a possible exception are given to the completion callback.

37. How Will You Get Information About A File Using Node?

Following is the syntax of the method to get the information about a file:

fs.stat(path, callback)

Parameters

Here is the description of the parameters used:

path - This is string having file name including path.

callback - This is the callback function which gets two arguments (err, stats) where stats is an object of fs.Stats type which is printed below in the example.

38. How Will You Truncate A File Using Node?

Following is the syntax of the method to truncate an opened file:

fs.ftruncate(fd, len, callback)

Parameters

Here is the description of the parameters used:

fd - This is the file descriptor returned by file fs.open() method.

len - This is the length of the file after which file will be truncated.

callback - This is the callback function which gets no arguments other than a possible exception are given to the completion callback.

39. How Will You Delete A File Using Node?

Following is the syntax of the method to delete a file:

fs.unlink(path, callback)

Parameters

Here is the description of the parameters used:

path - This is the file name including path.

callback - This is the callback function which gets no arguments other than a possible exception are given to the completion callback.

40. How Will You Create A Directory?

Following is the syntax of the method to create a directory:

fs.mkdir(path[, mode], callback)

Parameters

Here is the description of the parameters used:

path - This is the directory name including path.

mode - This is the directory permission to be set. Defaults to 0777.

callback - This is the callback function which gets no arguments other than a possible exception are given to the completion callback.

41. How Will You Delete A Directory?

Following is the syntax of the method to remove a directory:

fs.rmdir(path, callback)

Parameters

Here is the description of the parameters used:

path - This is the directory name including path.

callback - This is the callback function which gets no arguments other than a possible exception are given to the completion callback.

42. How Will You Read A Directory?

Following is the syntax of the method to read a directory:

fs.readdir(path, callback)

Parameters

Here is the description of the parameters used:

path - This is the directory name including path.

callback - This is the callback function which gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.

43. What Is The Purpose Of __filename Variable?

The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.

44. What Is The Purpose Of __dirname Variable?

The __dirname represents the name of the directory that the currently executing script resides in.

45. What Is The Purpose Of Settimeout Function?

The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days.

This function returns an opaque value that represents the timer which can be used to clear the timer.

46. What Is The Purpose Of Cleartimeout Function?

The clearTimeout( t ) global function is used to stop a timer that was previously created with setTimeout(). Here t is the timer returned by setTimeout() function.

47. What Is The Purpose Of Setinterval Function?

The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days.

This function returns an opaque value that represents the timer which can be used to clear the timer using the function clearInterval(t).

48. What Is The Purpose Of Console Object?

console object is used to Used to print information on stdout and stderr.

49. What Is The Purpose Of Process Object?

process object is used to get information on current process. Provides multiple events related to process activities.

50. Why To Use Node.js?

It is used to develop I/O intensive web applications like video streaming sites, single page applications (SPA) and other web applications. Node.js is open source and used by thousands of developers around the world.

51. What Is The Difference Between Undefined And Not Defined In Javascript?

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 script will stop executing. However, if you use typeof undeclared_variable, then it will return undefined.

Before getting further into this, let's first understand the difference between declaration and definition.

Let's say var x is a declaration because you have not defined what value it holds yet, but you have declared its existence and the need for memory allocation.

> var x; // declaring x

> console.log(x); //output: undefined

Here var x = 1 is both a declaration and definition (also we can say we are doing an initialisation). In the example above, the declaration and assignment of value happen inline for variable x. In JavaScript, every variable or function declaration you bring to the top of its current scope is called hoisting.

The assignment happens in order, so when we try to access a variable that is declared but not defined yet, we will get the result undefined.

var x; // Declaration

if(typeof x === 'undefined') // Will return true

If a variable that is neither declared nor defined, when we try to reference such a variable we'd get the result not defined.

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

52. What Will Be The Output Of The Code Below?

var Y = 1;

if (function F(){})

{

y += Typeof F;

}

console.log(y);

The output would be 1undefined. The if condition statement evaluates using eval, so eval(function f(){}) returns function f(){} (which is true). Therefore, inside the if statement, executing typeof f returns undefined because the if statement code executes at run time, and the statement inside the if condition is evaluated during run time.

 var k = 1;

  if (1)

{

    eval(function foo(){});

    k += typeof foo;

  }

console.log(k);

The code above will also output 1undefined.

 var k = 1;

  if (1)

{

    function foo(){};

    k += typeof foo;

  }

  console.log(k); // output 1function

53. What Is The Drawback Of Creating True Private Methods In Javascript?

One of the drawbacks of creating true private methods in JavaScript is that they are very memory-inefficient, as a new copy of the method would be created for each instance.

var Employee = function (name, company, salary)

{

    this.name = name || "";       //Public attribute default value is null

    this.company = company || ""; //Public attribute default value is null

    this.salary = salary || 5000; //Public attribute default value is null

    // Private method

    var increaseSalary = function ()

{

        this.salary = this.salary + 1000;

};

    // Public method

    this.dispalyIncreasedSalary = function()

{

        increaseSlary();

        console.log(this.salary);

 };

};

 

// Create Employee class object

var emp1 = new Employee("John","Pluto",3000);

// Create Employee class object

var emp2 = new Employee("Merry","Pluto",2000);

// Create Employee class object

var emp3 = new Employee("Ren","Pluto",2500);

Here each instance variable emp1, emp2, emp3 has its own copy of the increaseSalary private method.

So, as a recommendation, don’t use private methods unless it’s necessary.

54. What Is A “closure” In Javascript? Provide An Example

A closure is a function defined inside another function (called the parent function), and has access to variables that are declared and defined in the parent function scope.

The closure has access to variables in three scopes:

Variables declared in their own scope

Variables declared in a parent function scope

Variables declared in the global namespace

var globalVar = "abc";

// Parent self invoking function

(function outerFunction (outerArg) { // begin of scope outerFunction

    // Variable declared in outerFunction function scope

    var outerFuncVar = 'x';   

    // Closure self-invoking function

    (function innerFunction (innerArg) { // begin of scope innerFunction

        // variable declared in innerFunction function scope

        var innerFuncVar = "y";

        console.log(         

            "outerArg = " + outerArg + "n" +

            "outerFuncVar = " + outerFuncVar + "n" +

            "innerArg = " + innerArg + "n" +

            "innerFuncVar = " + innerFuncVar + "n" +

            "globalVar = " + globalVar);

     }// end of scope innerFunction)(5); // Pass 5 as parameter

}// end of scope outerFunction )(7); // Pass 7 as parameter

innerFunction is closure that is defined inside outerFunction and has access to all variables declared and defined in the outerFunction scope. In addition, the function defined inside another function as a closure will have access to variables declared in the global namespace.

Thus, the output of the code above would be:

outerArg = 7

outerFuncVar = x

innerArg = 5

innerFuncVar = y

globalVar = abc

55. Write A Mul Function Which Will Produce The Following Outputs When Invoked?

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

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

Below is the answer followed by an explanation to how it works:

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 takes the second parameter and returns another anonymous function that will take the third parameter and return the multiplication of the arguments that have been passed.

In JavaScript, a function defined inside another one has access to the outer function's variables. Therefore, a function is a first-class object that can be returned by other functions as well and be passed as an 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

A function can be stored as a variable

A function can be pass as a parameter to another function

A function can be returned from another function

56. How To Empty An Array In Javascript?

For instance,

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

How can we empty the array above?

There are a couple ways we can use to empty an array, so let's discuss them all.

Method 1 :

arrayList = []

Above 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 a new, empty array. You should be careful with this method of emptying the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged.

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 the array also updates all the reference variables that point to the original array. Therefore, this method is useful when you want to update all reference variables pointing to arrayList.

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

The implementation above will also work perfectly. This way of emptying the array will also update all the references to 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();

}

The implementation above can also empty arrays, but it is usually not recommended to use this method often.

57. How Do You Check If An Object Is An Array Or Not?

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

  var arrayList = [1,2,3];

One of the best use cases of type-checking an object is when we do method overloading in JavaScript. For example, let's say we have a method called greet, which takes one single string and also a list of strings. To make our greet method workable in both situations, we need to know what kind of parameter is being passed. Is it a single value or a list of values?

 function greet(param)

{

  if()

{ // here have to check whether param is array or not

  }

else

{

  }

 }

However, as the implementation above might not necessarily check the type for arrays, we can check for a single value string and put some array logic code in the else block. For example:

 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 either of the aforementioned two implementations, but when we have a situation where the parameter can be single value, array, and object type, we will be in trouble.

Coming back to checking the type of an object, as mentioned previously 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 use the 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 browsers, 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

58. What Will Be The Output Of The Following Code?

var Output = (function(x)

{   

Delete X;   

return X;  

}

)(0);

console.log(output);

The output would be 0. The delete operator is used to delete properties from an object. Here x is not an object but a local variable. delete operators don't affect local variables.

59. What Will Be The Output Of The Following Code?

var X = 1;

var Output = (function()

{   

Delete X;   

Return X;

  }

)();

 console.log(output);

The output would be 1. The delete operator is used to delete the property of an object. Here x is not an object, but rather it's the global variable of type number.

60. What Will Be The Output Of The Code Below?

var X = { Foo : 1};

var Output = (function()

{

delete X.foo;

return X.foo;

}

)();

console.log(output);

The output would be undefined. The delete operator is used to delete the property of an object. Here, x is an object which has the property foo, and as it is a self-invoking function, we will delete the foo property from object x. After doing so, when we try to reference a deleted property foo, the result isundefined.

61. What Will Be The Output Of The Code Below?

var Employee =

{

company: 'xyz'

}

var Emp1 = Object.create(employee);

delete Emp1.company Console.log(emp1.company);

The output would be xyz. Here, emp1 object has company as its prototype property. The 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 the company property directly from theEmployee object using delete Employee.company. Or, we can also delete the emp1 object using the __proto__ property delete emp1.__proto__.company.

62. What Is Undefined X 1 In Javascript?

var trees = ["redwood","bay","cedar","oak","maple"];

delete trees[3];

When you run the code above and type console.log(trees); into your Chrome developer console, you will get ["redwood", "bay", "cedar", undefined × 1, "maple"]. When you run the code in Firefox's browser console, you will get ["redwood", "bay", "cedar", undefined, "maple"]. Thus, it's clear that the Chrome browser has its own way of displaying uninitialised indexes in arrays. However, when you check trees[3] === undefined in both browsers, you will get similar output as true.

63. What Will Be The Output Of The Code Below?

var Trees = ["xyz","xxxx","test","ryan","apple"];

delete Trees[3];

console.log(trees.length);

The output would be 5. When we use the delete operator to delete an array element, the array length is not affected from this. This holds even if you deleted all elements of an array using the delete operator.

In other words, when the delete operator removes an array element, that deleted element is not longer present in 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"].

64. If We Have A Javascript Associative Array

Var Counterarray =

{

A : 3,

b : 4

};

Counterarray["c"] = 1;

how Can We Calculate The Length Of The Above Associative Array's Counter Array?

There are no in-built functions and properties available to calculate the length of associative array object here. However, there are other ways by which we can calculate the length of an associative array object. In addition to this, we can also extend an Object by adding a method or property to the prototype in order to calculate length. However, extending an object might break enumeration in various libraries or might create cross-browser issues, so it's not recommended unless it's necessary. Again, there are various ways by which we can calculate length.

Object has the keys method which can be used to calculate the length of an object:

 Object.keys(counterArray).length // Output 2

We can also calculate the length of an object by iterating through an object and by counting the object's own property.

function getSize(object)

{

  var count = 0;

  for(key in object)

{

    // hasOwnProperty method check own property of object

    if(object.hasOwnProperty(key)) count++;

  }

  return count;

}

We can also add a length method directly on Object:

  Object.length = function()

{

  var count = 0;

  for(key in object)

{

    // hasOwnProperty method check own property of object

    if(object.hasOwnProperty(key)) count++;

  }

  return count;

  }

  //Get the size of any object using

  console.log(Object.length(counterArray))

65. What Is The Instanceof Operator In Javascript? What Would Be The Output Of The Code Below?

function Foo()

{

return Foo;

}

new Foo() Instanceof Foo;

Here, instanceof operator checks the current object and returns true if the object is of the specified type.

For Example:

var dog = new Animal();

dog instanceof Animal // Output : true

Here dog instanceof Animal is true since dog inherits from Animal.prototype.

 var name = new String("xyz");

 name instanceof String // Output : true

Here name instanceof String is true since dog inherits from String.prototype. Now let's understand the code below:

function foo()

{

  return foo;

}

new foo() instanceof foo;

Here function foo is returning foo, which again points to function foo.

function foo()

{

  return foo;

}

var bar = new foo();

// here bar is pointer to function foo(){return foo}.

So the new foo() instanceof foo return false;

66. What Will Be The Output Of Code Below?

var Salary = "1000$";

(function ()

{

console.log("original Salary Was " + Salary);

var Salary = "5000$";

Console.log("my New Salary " + Salary);

}

)();

The output would be undefined, 5000$. Newbies often get tricked by JavaScript's hoisting concept. In the code above, you might be expecting salary to retain its value from the outer scope until the point that salary gets re-declared in the inner scope. However, due to hoisting, the salary value was undefined instead. To understand this better, have a look of the code below:

 var salary = "1000$";

 (function ()

{

     var salary = undefined;

     console.log("Original salary was " + salary);

     salary = "5000$";

     console.log("My New Salary " + salary);

 }

)();

salary variable is hoisted and declared at the top in the function's scope. The console.log inside returns undefined. After the console.log, salary is redeclared and assigned 5000$.

67. What Is Function Hoisting In Javascript?

function Expression

 var Foo = Function Foo()

{          

return 12; 

 };

In JavaScript, variable and functions are hoisted. Let's take function hoisting first. Basically, the JavaScript interpreter looks ahead to find all variable declarations and then hoists them to the top of the function where they're declared. For example:

 foo(); // Here foo is still undefined

 var foo = function foo()

{

  return 12;

 };

Behind the scene of the code above looks like this:

var foo = undefined;

    foo(); // Here foo is undefined

 foo = function foo()

{

       / Some code stuff

      }

   var foo = undefined;

    foo = function foo()

{

       / Some code stuff

      }

      foo(); // Now foo is defined here.

68. What Is The Difference Between The Function Declarations Below?

 var Foo = Function(){ 

  // Some Code

 }; 

  Function Bar(){ 

  // Some Code

 };

The main difference is the function foo is defined at run-time whereas function bar is defined at parse time. To understand this in better way, let's take a look at the code below:

Run-Time function declaration

 Another advantage of this first-one way of declaration is that you can declare functions based on certain conditions. For example:

 However, if you try to run similar code using the format below, you'd get an error:

69. What Will Be The Output Of The Code Below?

 // Nfe (named Function Expression 

 var Foo = Function Bar()

{

return 12;

};

 typeof Bar(); 

The output would be Reference Error. To make the code above work, you can re-write it as follows:

Sample 1

 var bar = function()

{

return 12;

};

 typeof bar(); 

or

Sample 2

 function bar()

{

return 12;

};

 typeof bar(); 

A function definition can have only one reference variable as its function name. In sample 1, bar's reference variable points to anonymous function. In sample 2, the function's definition is the name function.

var foo = function bar()

{

    // foo is visible here

    // bar is visible here

  console.log(typeof bar()); // Work here :)

 };

 // foo is visible here

 // bar is undefined here

70. What Will Be The Output Of The Code Below?

var Z = 1, Y = Z = Typeof Y;

console.log(y);

The output would be undefined. According to the associativity rule, operators with the same precedence are processed based on the associativity property of the operator. Here, the associativity of the assignment operator is Right to Left, so typeof y will evaluate first , which is undefined. It will be assigned to z, and then y would be assigned the value of z and then z would be assigned the value 1.

71. What Will Be The Output Of The Code Below?

var Bar = True;

console.log(bar + 0);

console.log(bar + "xyz");

console.log(bar + True);

console.log(bar + False);

The code will output 1, "truexyz", 2, 1. Here's a general guideline for addition operators:

Number + Number -> Addition

Boolean + Number -> Addition

Boolean + Number -> Addition

Number + String -> Concatenation

String + Boolean -> Concatenation

String + String -> Concatenation

72. What Is Polymer.js?

Polymer.js is an open source JavaScript library. It is developed by Google. It is used to develop web applications for using of web components like HTML

73. Describe Architecture Of Polymer.js?

The architecture of Polymer.js is divided into four important layers:

Native Layer- It represents the current state of browser support and implementation for the web component detail.

Foundation Layer- It consists polyfill libraries for the web component details. Polyfill is a code that implement the feature of web browser that does not support the feature.

Core Layers- It contains the Polymer library code which is found in polymer.html file.

Elements Layers- It consists of core and paper elements.

74. What Are The Features Of Polymer.js?

Following are the features of Polymer.js:

It is simplest way to create custom elements.

It has both One-way and Two-way data binding.

It provides polyfills for creating it's own customized elements.

It has computed properties.

It provides gesture events.

75. What Are The Polymer Elements?

It provides elements that we can use in our web pages and applications. These elements are built with the Polymer library.

76. Name The Types Of Polymer Elements?

Following are the types of polymer elements:

App element- It is used, when we build entire application.

Iron element- It is used to create basic building blocks of an application.

Paper element- It is a set of UI (User Interface) elements that implement the material design system.

Gold elements- This element is build for e commerce.

Neon element- It is used for animation-related elements.

Platinum elements- This element is like application features, like push notifications, offline caching and bluetooth.

77. What Is Custom Elements?

It provide a component model for the web.

78. What Are The Features Provided By Custom Elements?

Custom elements provides the following features:

It provides a mechanism for associating class with custom element name.

It requests the lifecycle methods when we change the state of custom element object.

It requests for the method when we change the attribute of an instance.

79. What Are The Reactions Apply In Custom Elements Life Cycle?

It provides the set of custom element reactions that allows to change in elements lifecycle.

Reactiom->Description

Constructor:It is called when element is upgraded.

Connected Callback:It is called when element is added to a document.

Disconnected Callback:It is called when element is removed to a document.

AttributeChanged Callback:It is called when element is change, append, remove or replace.

80. What Are Events In Polymer.js?

Event is something that happens at specific time and lead to some changes. polymer.js provides own methods to perform events like: on-click, on-tap, on-mouseover etc. we can also create our own custom events.

It also provides listener objects that can be used to bind events to execute functions.

81. What Is Data System In Polymer.js?

In Data system, polymer.js allows us to observe changes on an element's properties by taking different actions.

Data system actions include following properties:

Observers: It invokes specified method whenever data changes.

Computed properties: It computes the virtual properties which is based on other properties and recompute when the input data change.

Data binding: By using of annotation we can update the properties, attributes or text content whenever data changes.

82. What Is Shadow Dom?

Shadow DOM is a new DOM (Document Object Modeling) features Which is used for Building component.

83. What Is Shadow Dom Styling?

It is a process of styling shadow DOM by using style properties. It inherits properties from host to shadow tree.

Let's see an example.

Shadow DOM Style Example:

my demo {background-color:grey;} 

</style> 

<my-element> 

#shadow-root 

<style> 

//this div will have blue background color 

div { background-color: orange; } 

</style> 

<div class="mydemo">Demo</div> 

84. What Is Javascript Objects?

JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called object-oriented if it provides four basic capabilities to developers −

Encapsulation − the capability to store related information, whether data or methods, together in an object.

Aggregation − the capability to store one object inside another object.

Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its properties and methods.

Polymorphism − the capability to write one function or method that works in a variety of different ways.

Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of the object, otherwise the attribute is considered a property.

85. What Are Object Properties?

Object properties can be any of the three primitive data types, or any of the abstract data types, such as another object. Object properties are usually variables that are used internally in the object's methods, but can also be globally visible variables that are used.

The syntax for adding a property to an object is:

objectName.objectProperty = propertyValue;

For example − The following code gets the document title using the "title" property of the document object.

var str = document.title;

86. What Is Object Methods?

Methods are the functions that let the object do something or let something be done to it. There is a small difference between a function and a method – at a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword.

Methods are useful for everything from displaying the contents of the object to the screen to performing complex mathematical operations on a group of local properties and parameters.

For example − Following is a simple example to show how to use the write() method of document object to write any content on the document.

document.write("This is test");

87. What Is User-defined Objects?

User-Defined Objects: All user-defined objects and built-in objects are descendants of an object called Object.

The new Operator: The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method.

In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions.

var employee = new Object();

var books = new Array("C++", "Perl", "Java");

var day = new Date("August 15, 1947");

The Object() Constructor: A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable.

The variable contains a reference to the new object. The properties assigned to the object are not variables and are not defined with the var keyword.

Example 1: Try the following example; it demonstrates how to create an Object.

<html>

   <head>

      <title>User-defined objects</title>

      <script type="text/javascript">

         var book = new Object();   // Create the object

         book.subject = "Perl"; // Assign properties to the object

         book.author  = "Mohtashim";

      </script>

   </head>

   <body>

      <script type="text/javascript">

         document.write("Book name is : " + book.subject + "<br>");

         document.write("Book author is : " + book.author + "<br>");

      </script>

   </body>

</html>

88. Defining Methods For An Object?

The previous examples demonstrate how the constructor creates the object and assigns properties. But we need to complete the definition of an object by assigning methods to it.

Example: Try the following example; it shows how to add a function along with an object.

<html>

   <head>

   <title>User-defined objects</title>

      <script type="text/javascript">

         // Define a function which will work as a method

         function addPrice(amount){

            this.price = amount;

         }     

     function book(title, author){

            this.title = title;

            this.author  = author;

            this.addPrice = addPrice; // Assign that method as property.

         }

      </script>     

   </head>

   <body>

      <script type="text/javascript">

         var myBook = new book("Perl", "Mohtashim");

         myBook.addPrice(100);   

         document.write("Book title is : " + myBook.title + "<br>");

         document.write("Book author is : " + myBook.author + "<br>");

         document.write("Book price is : " + myBook.price + "<br>");

      </script>  

   </body>

</html>

89. What Is The 'with' Keyword?

The ‘with’ keyword is used as a kind of shorthand for referencing an object's properties or methods.

The object specified as an argument to with becomes the default object for the duration of the block that follows. The properties and methods for the object can be used without naming the object.

Syntax: The syntax for with object is as follows --

with (object){

   properties used without the object name and dot

}

90. What Are The Javascript Native Objects?

JavaScript has several built-in or native objects. These objects are accessible anywhere in your program and will work the same way in any browser running in any operating system.

Here is the list of all important JavaScript Native Objects −

JavaScript Number Object

JavaScript Boolean Object

JavaScript String Object

JavaScript Array Object

JavaScript Date Object

JavaScript Math Object

JavaScript RegExp Object

91. What Is Javascript Number Object?

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: The syntax for creating a number object is as follows:

var val = new Number(number);

In the place of number, if you provide any non-number argument, then the argument cannot be converted into a number, it returns NaN (Not-a-Number).

92. What Are The Number Properties?

Here is a list of each property and their description.

MAX_VALUE: The largest possible value a number in JavaScript can have 1.7976931348623157E+308

MIN_VALUE: The smallest possible value a number in JavaScript can have 5E-324

NaN: Equal to a value that is not a number.

NEGATIVE_INFINITY: A value that is less than MIN_VALUE.

POSITIVE_INFINITY: A value that is greater than MAX_VALUE

prototype: A static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document

constructor: Returns the function that created this object's instance. By default this is the Number object.

93. What Are The Number Methods?

The Number object contains only the default methods that are a part of every object's definition.

toExponential(): Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation.

toFixed(): Formats a number with a specific number of digits to the right of the decimal.

toLocaleString(): Returns a string value version of the current number in a format that may vary according to a browser's local settings.

toPrecision(): Defines how many total digits (including digits to the left and right of the decimal) to display of a number.

toString(): Returns the string representation of the number's value.

valueOf(): Returns the number's value.

94. What Is Javascript Boolean Object?

The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

Syntax: Use the following syntax to create a boolean object.

var val = new Boolean(value);

95. What Are The Boolean Properties?

Here is a list of the properties of Boolean object:

constructor: Returns a reference to the Boolean function that created the object.

prototype: The prototype property allows you to add properties and methods to an object.

96. What Are Boolean Methods?

Here is a list of the methods of Boolean object and their description.

toSource(): Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.

toString(): Returns a string of either "true" or "false" depending upon the value of the object.

valueOf(): Returns the primitive value of the Boolean object.

97. What Is Javascript Strings Object?

The String object lets you work with a series of characters; it wraps Javascript's string primitive data type with a number of helper methods.

As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive.

Syntax: Use the following syntax to create a String object −

var val = new String(string);

The String parameter is a series of characters that has been properly encoded.

98. What Are String Properties?

Here is a list of the properties of String object and their description.

constructor: Returns a reference to the String function that created the object.

length: Returns the length of the string.

prototype: The prototype property allows you to add properties and methods to an object.

99. What Are String Methods?

Here is a list of the methods available in String object along with their description.

charAt(): Returns the character at the specified index.

charCodeAt(): Returns a number indicating the Unicode value of the character at the given index.

concat(): Combines the text of two strings and returns a new string.

indexOf(): Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.

lastIndexOf(): Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.

localeCompare(): Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

match(): Used to match a regular expression against a string.

replace(): Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.

search(): Executes the search for a match between a regular expression and a specified string.

slice(): Extracts a section of a string and returns a new string.

split(): Splits a String object into an array of strings by separating the string into substrings.

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

substring(): Returns the characters in a string between two indexes into the string.

toLocaleLowerCase(): The characters within a string are converted to lower case while respecting the current locale.

toLocaleUpperCase(): The characters within a string are converted to upper case while respecting the current locale.

toLowerCase(): Returns the calling string value converted to lower case.

toString(): Returns a string representing the specified object.

toUpperCase(): Returns the calling string value converted to uppercase.

valueOf(): Returns the primitive value of the specified object.

100. What Are String Html Wrappers?

Here is a list of the methods that return a copy of the string wrapped inside an appropriate HTML tag.

anchor(): Creates an HTML anchor that is used as a hypertext target.

big(): Creates a string to be displayed in a big font as if it were in a tag.

blink(): Creates a string to blink as if it were in a tag.

bold(): Creates a string to be displayed as bold as if it were in a tag.

fixed(): Causes a string to be displayed in fixed-pitch font as if it were in a tag

fontcolor(): Causes a string to be displayed in the specified color as if it were in a tag.

fontsize(): Causes a string to be displayed in the specified font size as if it were in a tag.

italics(): Causes a string to be italic, as if it were in an tag.

link(): Creates an HTML hypertext link that requests another URL.

small(): Causes a string to be displayed in a small font, as if it were in a tag.

strike(): Causes a string to be displayed as struck-out text, as if it were in a tag.

sub(): Causes a string to be displayed as a subscript, as if it were in a tag

sup(): Causes a string to be displayed as a superscript, as if it were in a tag

101. What Is Javascript Arrays Object?

The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Syntax: Use the following syntax to create an Array object:

var fruits = new Array( "apple", "orange", "mango" );

The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295.

You can create array by simply assigning values as follows:

var fruits = [ "apple", "orange", "mango" ];

You will use ordinal numbers to access and to set values inside an array as follows.

fruits[0] is the first element

fruits[1] is the second element

fruits[2] is the third element

102. What Are Array Properties?

Here is a list of the properties of the Array object along with their description.

constructor: Returns a reference to the array function that created the object.

index: The property represents the zero-based index of the match in the string

input: This property is only present in arrays created by regular expression matches.

length: Reflects the number of elements in an array.

prototype: The prototype property allows you to add properties and methods to an object.

103. What Are Array Methods?

Here is a list of the methods of the Array object along with their description.

concat(): Returns a new array comprised of this array joined with other array(s) and/or value(s).

every(): Returns true if every element in this array satisfies the provided testing function.

filter(): Creates a new array with all of the elements of this array for which the provided filtering function returns true.

forEach(): Calls a function for each element in the array.

indexOf(): Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.

join(): Joins all elements of an array into a string.

lastIndexOf(): Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.

map(): Creates a new array with the results of calling a provided function on every element in this array.

pop(): Removes the last element from an array and returns that element.

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

reduce(): Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.

reduceRight(): Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.

reverse(): Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.

shift(): Removes the first element from an array and returns that element.

slice(): Extracts a section of an array and returns a new array.

some(): Returns true if at least one element in this array satisfies the provided testing function.

toSource(): Represents the source code of an object

sort(): Sorts the elements of an array

splice(): Adds and/or removes elements from an array.

toString(): Returns a string representing the array and its elements.

unshift(): Adds one or more elements to the front of an array and returns the new length of the array.

104. What Is Javascript Date Object?

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

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.

The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755

Syntax: You can use any of the following syntaxes to create a Date object using Date() constructor.

new Date( )

new Date(milliseconds)

new Date(datestring)

new Date(year,month,date[,hour,minute,second,millisecond ])

105. What Is Date Properties?

Here is a list of the properties of the Date object along with their description.

constructor: Specifies the function that creates an object's prototype.

prototype: The prototype property allows you to add properties and methods to an object.

106. What Are Date Methods?

Here is a list of the methods used with Date and their description.

Date(): Returns today's date and time

getDate(): Returns the day of the month for the specified date according to local time.

getDay(): Returns the day of the week for the specified date according to local time.

getFullYear(): Returns the year of the specified date according to local time.

getHours(): Returns the hour in the specified date according to local time.

getMilliseconds(): Returns the milliseconds in the specified date according to local time.

getMinutes(): Returns the minutes in the specified date according to local time.

getMonth(): Returns the month in the specified date according to local time.

getSeconds():Returns the seconds in the specified date  according to local time.

getTime(): Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.

getTimezoneOffset(): Returns the time-zone offset in minutes for the current locale.

getUTCDate(): Returns the day (date) of the month in the specified date according to universal time.

getUTCDay(): Returns the day of the week in the specified date according to universal time.

getUTCFullYear(): Returns the year in the specified date according to universal time.

getUTCHours(): Returns the hours in the specified date according to universal time.

getUTCMilliseconds(): Returns the milliseconds in the specified date according to universal time.

getUTCMinutes(): Returns the minutes in the specified date according to universal time.

getUTCMonth(): Returns the month in the specified date according to universal time.

getUTCSeconds(): Returns the seconds in the specified date according to universal time.

getYear(): Deprecated - Returns the year in the specified date according to local time. Use getFullYear instead.

setDate(): Sets the day of the month for a specified date according to local time.

setFullYear(): Sets the full year for a specified date according to local time.

setHours(): Sets the hours for a specified date according to local time.

setMilliseconds(): Sets the milliseconds for a specified date according to local time.

setMinutes(): Sets the minutes for a specified date according to local time.

setMonth(): Sets the month for a specified date according to local time.

setSeconds(): Sets the seconds for a specified date according to local time.

setTime(): Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.

setUTCDate(): Sets the day of the month for a specified date according to universal time.

setUTCFullYear(): Sets the full year for a specified date according to universal time.

setUTCHours(): Sets the hour for a specified date according to universal time.

setUTCMilliseconds(): Sets the milliseconds for a specified date according to universal time.

setUTCMinutes(): Sets the minutes for a specified date according to universal time.

setUTCMonth(): Sets the month for a specified date according to universal time.

setUTCSeconds(): Sets the seconds for a specified date according to universal time.

setYear(): Deprecated - Sets the year for a specified date according to local time. Use setFullYear instead.

toDateString(): Returns the "date" portion of the Date as a human-readable string.

toGMTString(): Deprecated - Converts a date to a string, using the Internet GMT conventions. Use toUTCString instead.

toLocaleDateString(): Returns the "date" portion of the Date as a string, using the current locale's conventions.

toLocaleFormat(): Converts a date to a string, using a format string.

toLocaleString(): Converts a date to a string, using the current locale's conventions.

toLocaleTimeString(): Returns the "time" portion of the Date as a string, using the current locale's conventions.

toSource(): Returns a string representing the source for an equivalent Date object; you can use this value to create a new object.

toString(): Returns a string representing the specified Date object.

toTimeString(): Returns the "time" portion of the Date as a human-readable string.

toUTCString(): Converts a date to a string, using the universal time convention.

valueOf(): Returns the primitive value of a Date object.

107. What Are Date Static Methods?

In addition to the many instance methods listed previously, the Date object also defines two static methods. These methods are invoked through the Date() constructor itself.

Date.parse( ): Parses a string representation of a date and time and returns the internal millisecond representation of that date.

Date.UTC( ): Returns the millisecond representation of the specified UTC date and time.

108. What Is Javascript Math Object?

The math object provides you properties and methods for mathematical constants and functions. Unlike other global objects, Math is not a constructor. All the properties and methods of Math are static and can be called by using Math as an object without creating it.

Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument.

Syntax: The syntax to call the properties and methods of Math are as follows

var pi_val = Math.PI;

var sine_val = Math.sin(30);

109. What Are The Math Properties?

Here is a list of all the properties of Math and their description.

E : Euler's constant and the base of natural logarithms, approximately 2.718.

LN2: Natural logarithm of 2, approximately 0.693.

LN10: Natural logarithm of 10, approximately 2.302.

LOG2E: Base 2 logarithm of E, approximately 1.442.

LOG10E: Base 10 logarithm of E, approximately 0.434.

PI: Ratio of the circumference of a circle to its diameter, approximately 3.14159.

SQRT1_2: Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.

SQRT2: Square root of 2, approximately 1.414.

110. What Are The Math Methods?

Here is a list of the methods associated with Math object and their description

abs(): Returns the absolute value of a number.

acos(): Returns the arccosine (in radians) of a number.

asin(): Returns the arcsine (in radians) of a number.

atan(): Returns the arctangent (in radians) of a number.

atan2(): Returns the arctangent of the quotient of its arguments.

ceil(): Returns the smallest integer greater than or equal to a number.

cos(): Returns the cosine of a number.

exp(): Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm.

floor(): Returns the largest integer less than or equal to a number.

log(): Returns the natural logarithm (base E) of a number.

max(): Returns the largest of zero or more numbers.

min(): Returns the smallest of zero or more numbers.

pow(): Returns base to the exponent power, that is, base exponent.

random(): Returns a pseudo-random number between 0 and 1.

round(): Returns the value of a number rounded to the nearest integer.

sin(): Returns the sine of a number.

sqrt(): Returns the square root of a number.

tan(): Returns the tangent of a number.

toSource(): Returns the string "Math".

111. What Are Regular Expressions And Regexp Object?

A regular expression is an object that describes a pattern of characters.

The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text.

Syntax: A regular expression could be defined with the RegExp () constructor, as follows −

var pattern = new RegExp(pattern, attributes);

or simply

var pattern = /pattern/attributes;

Here is the description of the parameters:

pattern − A string that specifies the pattern of the regular expression or another regular expression.

attributes − An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multiline matches, respectively.

112. What Are Brackets?

Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.

[...]: Any one character between the brackets.

[^...]: Any one character not between the brackets.

[0-9]: It matches any decimal digit from 0 through 9.

[a-z]: It matches any character from lowercase a through lowercase z.

[A-Z]: It matches any character from uppercase A through uppercase Z.

[a-Z]: It matches any character from lowercase a through uppercase Z.

The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.

113. What Are Quantifiers?

The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a character sequence.

p+: It matches any string containing one or more p's.

p*: It matches any string containing zero or more p's.

p?: It matches any string containing at most one p.

p{N}: It matches any string containing a sequence of N p's

p{2,3}: It matches any string containing a sequence of two or three p's.

p{2, }: It matches any string containing a sequence of at least two p's.

p$: It matches any string with p at the end of it.

^p: It matches any string with p at the beginning of it.

114. Why Do We Use Json?

The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.

115. What Is The Difference Between Xml And Json?

The fundamental difference, which no other answer seems to have mentioned, is that XML is a markup language (as it actually says in its name), whereas JSON is a way of representing objects (as also noted in its name). This is what makes markup languages so useful for representing documents.

116. Why Json Format Is Better Than Xml?

JSON and XML used different formats. When compared both JSON is easy to write and use it applications then XML. The XML format can also be determined by the XML DTD or XML Schema (XSL) and can be tested.

The JSON a data-exchange format which is getting more popular as the JavaScript applications possible format. Basically this is an object notation array. JSON has a very simple syntax so can be easily learned.

117. Is Json Markup Language?

JSON is like XML in that it is used to structure data in a text format and is commonly used to exchange data over the Internet. JSON is not a markup language. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write.

118. What Is Json Text?

A JSON text is a sequence of tokens formed from Unicode code points that conforms to the JSON value grammar. The set of tokens includes six structural tokens, strings, numbers, and three literal name tokens.

The six structural tokens:

[ U+005B left square bracket

{ U+007B left curly bracket

] U+005D right square bracket

} U+007D right curly bracket

: U+003A colon

, U+002C comma

These are the three literal name tokens:

true U+0074 U+0072 U+0075 U+0065

false U+0066 U+0061 U+006C U+0073 U+0065

null U+006E U+0075 U+006C U+006C

Insignificant whitespace is allowed before or after any token. Whitespace is any sequence of one or more of the following code points: character tabulation (U+0009), line feed (U+000A), carriage return (U+000D), and space (U+0020). Whitespace is not allowed within any token, except that space is allowed in strings.

119. What Is Json Value?

A JSON value can be an object, array, number, string, true, false, or null.

120. What Is Json Syntax?

JSON syntax is derived from JavaScript object notation syntax. Data is in name/value pairs. Data is separated by commas. Curly braces hold objects. Square brackets hold arrays.

121. What Is Json Array?

An array structure is a pair of square bracket tokens surrounding zero or more values. An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma). The values are separated by commas. The JSON syntax does not define any specific meaning to the ordering of the values. However, the JSON array structure is often used in situations where there is some semantics to the ordering.

122. What Is Number In Json?

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used. A number is a sequence of decimal digits with no superfluous leading zero.

It may have a preceding minus sign (U+002D). It may have a fractional part prefixed by a decimal point (U+002E). It may have an exponent, prefixed by e (U+0065) or E (U+0045) and optionally + (U+002B) or – (U+002D). The digits are the code points U+0030 through U+0039.

Numeric values that cannot be represented as sequences of digits (such as Infinity and NaN) are not permitted.

123. What Is Json Object?

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

 124. What Is Json Rpa Java?

JSON-RPC is a simple remote procedure call protocol similar to XML-RPC although it uses the lightweight JSON format instead of XML (so it is much faster).

125. What Is A Json Parser?

JSON parser to parse JSON object and MAINTAIN comments. By using JSON, when receiving data from a web server, the data should be always in a string format. We use JSON.parse() to parse the data and it becomes a JavaScript object.

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

126. Which Browser Provides Native Json Support?

All modern browsers support native JSON encoding/decoding (Internet Explorer 8+, Firefox 3.1+, Safari 4+, and Chrome 3+). Basically, JSON.parse(str) will parse the JSON string in str and return an object, and JSON.stringify(obj) will return the JSON representation of the object obj.

127. What Are The Properties Of Json?

These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

128. Is Json Is A Language?

JSON is a data format. It could be classified as a language, but not a programming language. Its relationship to JavaScript is that it shares its syntax (more or less) with a subset of JavaScript literals.

129. What Programming Languages Supported By Json?

JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.

130. Json Name/value Pair Is Written As?

JSON name/value pair is written as "name" : "value"

131. Does Whitespace Matter In Json?

Yes, only within strings.

132. Can You Use A Double Quote Inside A Json String?

Yes, if it is escaped like ( " )

133. In Modern Websites What Is The Common Usage For Json?

To send and receive bits of data.

134. What Does Json Stand For?

JavaScript Object Notation.

135. Which Is Proper A Json Array?

{ "letters" : [ "a", "b", "c" ] }

136. Which Is A Benefit Json Has Over Xml?

JSON has less markup requirements and therefore is lighter than XML.

137. What Kind Of Format Is Json, And What Does The Acronym Mean?

A lightweight data-interchange format. JavaScript Object Notation.

138. Which Is A Valid Json String?

{

"meals" : [ "breakfast" , "lunch" , "dinner" ]

}

139. Which Code Will Return A Valid Json Object?

JSON.parse('{"FirstName": "John", "LastName":"Doe"}');

140. Which Is True About Json Namespace?

JSON doesn't have namespaces. Through every object is inherently a namespace.

141. What Is Abstraction In Java?

In java, Abstraction means show functionality and hide complexity or internal details or hide implementation details to the user is known as abstraction in java.

For example:

The best example in the world of abstraction is ATM machine where we can withdraw or transfer money easily but how it happens. We don't know. We don't know internal details or implementation details.

142. How To Achieve Abstraction In Java?

There are two ways in java we can achieve abstraction:

By using abstract class (0 to 100%).

By using interface (100%).

143. What Is Abstract Class In Java?

When we declared any class with "abstract" keyword is known as abstract class. In abstract class we can keep abstract method (without body) and non-abstract method (with body).

For example:

abstract class Demo

{

abstract void show();//abstract method

void show(){}//non-abstract method

}

144. Can We Create Instance Of Abstract Class?

No, we cannot create an instance of an abstract class.

145. Can We Define Abstract Class Without Abstract Method?

Yes, we can define abstract class without abstract method.

 146. Can We Declare Abstract Method In Non-abstract Class?

No, we can't declare abstract method in non-abstract class.

For example:

class Demo

{

abstract void show();

}

Above example will throw compile time error.

147. What Is Interface In Java?

An interface in java is a blueprint of a class that has static constants and abstract method by default.

148. What Is Abstraction?

It refers to the ability to make a class abstract in OOP.

It helps to reduce the complexity and also improves the maintainability of the system.

149. What Is An Abstract Class?

These classes cannot be instantiated and are either partially implemented or not at all implemented.

This class contains one or more abstract methods which are simply method declarations without a body.

150. When Is An Abstract Method Used?