Skip to content

Latest commit

 

History

History
1287 lines (864 loc) · 52.5 KB

javascript-ques.md

File metadata and controls

1287 lines (864 loc) · 52.5 KB

Source: http://www.careerride.com/Interview-Questions-JavaScript.aspx

1.JavaScript vs. Jscript

Latest answer: Both JavaScript and Jscript are almost similar. Java script was developed by Netscape. Microsoft implemented its own scripting language and named it as Jscript........... Read answer

2.What is the difference between Client side JavaScript and Server side JavaScript.

Latest answer: Client side java script comprises the basic language and predefined objects which are relevant to running java script in a browser. The client side java script is embedded directly by in the HTML pages............. Read answer

3.Where are cookies actually stored on the hard disk?

Latest answer: The storage of cookies on the hard disk depends on OS and the browser. The Netscape navigator on Windows, the file cookies.txt contains all the cookies. The path is :......... Read answer

4.What is the difference between a web-garden and a web-farm?

Latest answer: Web garden is a web hosting system. It is a setup of multi processors in single server.

Web farm is a web hosting system. It is a multi-server scenario........... Read answer

5.What is the difference between SessionState and ViewState?

Latest answer: The values of controls of a particular page of the client browser is persisted by ViewState at the time of post back operation is done. If the user requests another page, the data of previous page is no longer available............ Read answer

6.How to Accessing Elements using javascript?

Latest answer: The elements of JavaScript are accessed by their names. By default the browser is accessed by the element ‘windows’ and the page by ‘document’. The corresponding element has user defined names for forms and its elements............ Read answer

7.What is the difference between undefined value and null value?

Latest answer: Undefined value: A value that is not defined and has no keyword is known as undefined value. For example in the declaration, int number; the number has undefined value.......... Read answer

8.How to set the cursor to wait in JavaScript?

Latest answer: The cursor can set to wait in JavaScript by using the property ‘cursor’ property. The following example illustrates the usage............. Read answer

9.What is decodeURI(), encodeURI() in JavaScript?

Latest answer: To send the characters that can not be specified in a URL should be converted into their equivalent hex encoding. To perform this task the methods encodeURI() and decodeURI() are used........... Read answer

10.Methods GET vs. POST in HTML forms.

Latest answer: Encoding form data into URL is needed by the GET method. The form data is to be appeared within the message body , by the POST method. By specification, GET is used basically for retrieving data where as POST is used for data storing, data updating, ordering a product or even e-mailing............. Read answer

11.What does the EnableViewStateMac setting in an aspx page do?

Latest answer: EnableViewStateMac setting is a security measure in ASP.Net. It ensures the view state for a page not to tamper. To to so “ EnableViewStateMac=true “is used............ Read answer

12.What are windows object and navigator object in JavaScript?

Latest answer: Windows object is top level object in Java script. It contains several other objects such as, document, history, location, name, menu bar etc., in itself. Window object is the global object for Java script that is written at client-side......... Read answer

13.How to detect the operating system on the client machine in JavaScript?

Latest answer: The navigator.appVersion string should be used to find the name of the operating system on the client machine.............. Read answer

14.How to set a HTML document's background color in JavaScript?

Latest answer: Using document object the back ground color can be changed by JavaScript......... Read answer

15.How do you assign object properties in JavaScript?

Latest answer: Java script object properties are assigned like assigning a value to a variable. For example, the title property of document object can be assigned as follows:

document.title="Welcome to the world of Javascripting";............ Read answer

16.What is JavaScript?

Latest answer: JavaScript is a scripting language most often used for client-side web development................... Read answer

17.What boolean operators does JavaScript support?

Latest answer: ==, !=, < , >, <=, >=............. Read answer

18.Is a javascript script faster than an ASP script?

Latest answer: JSP is faster then ASP as the script is run on the client side................... Read answer

19.What is == operator ?

Latest answer: The ‘==’ operator is a boolean comparison operator that returns true if the variables................ Read answer

20.What is negative infinity?

Latest answer: It’s a number that is obtained by dividing a negative number by zero. (in JSP)................... Read answer

21.What’s relationship between JavaScript and ECMAScript?

Latest answer: JavaScript is a scripting language most often used for client-side web development................... Read answer

22.What does isNaN function do?

Latest answer: The isNaN function determines if the value is a number or not and depending upon the result, it returns true or false................. Read answer

23.How to read and write a file using javascript?

Latest answer: There are two ways to do it: 1. Using JavaScript extensions (runs from JavaScript Editor), or 2. Using a web page and ActiveX objects (Internet Explorer only)...................... Read answer

24.How do you create a new object in JavaScript?

Latest answer: In order to generate dynamic content, JSP provides for creating, modifying and interacting with Java objects. The implicit objects like page, config, request, etc are called so because their availability in the in JSP page is automatic..................... Read answer

25.How to create arrays in JavaScript?

Latest answer: Although you can create the arrays using ‘new’ (var myArray = new myArray[10];), it is recommended that you create it in the following way: var myArray = [];.................... Read answer

The components in the ASP.NET 2.0 AJAX packaging

ASP.NET AJAX Futures Community Technology Preview (CTP) — The ASP.NET 2.0 AJAX framework contains a set of functionality that is experimental in nature. This functionality will eventually become integrated with the RTM/Core code.

Potential benefits of using Ajax

AJAX makes it possible to create better and more responsive websites and web applications...............

Potential problems with AJAX

Search engines may not be able to index all portions of your AJAX application site.........

Who Benefits from AJAX?

AJAX is employed to improve the user’s experience. A request is made for the initial page rendering. After that, asynchronous requests to the server are made. An asynchronous request is a background request to send or receive data in an entirely nonvisual manner

26. What are the different actions that are performed using JavaScript?

JavaScript allow the computer to be more secure by putting the privacy policies and disable the unauthorized access to the files. It allows many actions to be performed like Setting the browser's preferences and receiving the request from the servers for the client computer. The settings that are used gets saved on the client side on the features like actions buttons, appearance and printing. It allows easy launching of an application on the client computer with interactive data to be communicated between the server and the client. It allows reading and writing of files or directories on the client or server side. It allows easy capturing of the data that is live streamed from server to the client machine for retransmission. It also allows to safe and secure the application from the outside world.

27. How can JavaScript language be separated from objects?

JavaScript treats and creates applications for the scripting to make the browser's compatible for use. The language is separated from the objects as it allows the syntax to change the environment. It is a language that keeps the page element in the HTML document. JavaScript allows the elements of the page to remain in sync with the document objects. The language is used to create objects that are connected to page elements and other elements in a language. The separation allows the concept of development and effort to be shared with each factor. The JavaScript language allows dynamic data to be presented using the weakly typed language. It also support any action to be taken to support user interface and graphics.

28. What is the use of DOM?

DOM is also known as Document Object Model which is used to develop a model with documents or web pages containing objects like elements, links, etc. These objects can be manipulated or certain actions like add, delete or change of an element can be performed using this document object model. Through this change in attributes can be done to get all the list of all the elements in the document. The DOM model responds to API calls that result in documented level of DOM recommendation. It is used to support additional behavior on the web page and use of API give an extensible advantage over other models existing. DOM codes are reused to meet the requirement of the real world and to make all program interoperable.

29. What is the importance of <SCRIPT> tag?

JavaScript is used inside <SCRIPT> tag in HTML document. The tags that are provided provides the necessary information like alret to the browser for the program to begin interpreting all the text between the tags. The <script> tag uses JavaScript interpreter to handle the libraries that are written or the code of the program. JavaScript is a case sensitive language and the tags are used to tell the browser that if it is JavaScript enabled to use the text written in between the <Script> and

</Script> tags. The example is given as:
<HTML>
<HEAD>
<!-- 
<SCRIPT> // Starting of the scripting language
//Your code here
</SCRIPT> --> // End of the scripting language
</HEAD>
<BODY>
// your code here
</BODY>
</HTML>
30. Why JavaScript is called as Script for all browsers?

JavaScript is written after <SCRIPT> tag and it is surrounded in between the tags this is also known as comment tag. JavaScript interpreter treats the tag such that it treats all the lines in the comments as script lines. The JavaScript comment starts with // inside the <SCRIPT> tag. The script is contained inside tag that contains a comment tag. The browser that is non-compatible with JavaScripts ignore the lines and move on, but compatible browsers always treats it as a script and execute it. The browser treat the written lines between the comment tag as normal lines and just thinking of the comment ignores it. Some browsers just treat the as a comment only and ignores whatever is written inside it.

31. What are the requirements of Web application using JavaScript?

There are lots of application that require certain things when the user uses a JavaScript like Data entry validation: this tell that if the field of the form is filled out then during the processing of the server the client side can interact with it. Serverless CGIs: this describes the processes that are not used with JavaScript but programmed as CGI on server, it gives low performace due to more interaction between the applicatioin and the user. Dynamic HTML interactivity: it allows dynamic position of the data without using any other scripting language. CGI prototyping: allows more reduction of time to access the user interface before implementing the application of the CGI.

32. What are the different objects used in JavaScripts?

JavaScripts uses a hierarchical structure that applies to the objects in a document. There are some objects that show the relationship of one object to another using the language. Window object: this is the topmost object in the hierarchy. It represent the content area of browser window that consists of HTML documents. Each frame is also a window that has some actions inside it. Document object: This object gets loaded in a window and consists of objects of different kind in the model. It consists of the content that will be written in the script. Form object: Form objects are used for more interaction with the users. It represents the form elements inside

... tag.

33. Why is object naming important to use in JavaScript?

Object naming is used to create script references to objects while assigning names to every scriptable object in the HTML code. The browsers that are script compatible looks for the optional tags and attributes that enables the assigning of a unique name to each object. The example is:

The names act as a nametags through which the elements can be easily identified and easily located by the browsers. The references made for each object includes the object hierarchy from the top down. References are used to include names of each object that are coming in the window object. The object naming conventions are easy way to loacte the objects and the linking between them can be done more comfortably.
34. What are the methods involved in JavaScript?

Method is an informative that gets performed over an action that is related to the object. Method either performs on some object or affect any part of the the script or a document. Object can have as many number of methods that have associations with other objects. There is a method that is used by the JavaScript statement that includes a reference to an object this is given as:

document.orderForm.submit() document.orderForm.entry.select()

These are the functions which perform the dynamic interaction with the user. The first statement execute the element when pressed submit button to send a form to a server. These two statements are related to only the form. The scripts that are invoked will have the write of the document as well and will be written as:

document.write(“Give the version “ + navigator.appVersion) document.write(“ of ” + navigator.appName + “.”)

35. Explain with an example the use of event handlers in JavaScript.

The events in JavaScript are the actions in a document that result from user activity. The actions are like clicking on a button or typing typing a character in the form. JavaScript object in a document that receives events of different kinds. To handle the events that are taking place requires an even handler that can handle the execution of the events. Event acts like an added attribute that is entered in object’s HTML. The attribute is consisting of event name, sign like (=), instructions. The following code shows the event handler as:

36. How are tag positions used in JavaScript?

The tag can be inserted in a document wherever there is a requirement for a tag to be put. Nested tags are also possible within a ... tag. There are many other ways to use the tag like inside ... section. The tags can be placed inside <SCRIPT> tag also. The position of a particular tag is not fixed and it can be placed anywhere in the HTML document. Head is a used to place the tags that consists of noncontent settings. The example will show the position of <SCRIPT> tag:

<TITLE>Tag position</TITLE> <SCRIPT LANGUAGE=”Text/JavaScript”> // your script statement(s) here </SCRIPT>

This uses the <SCRIPT> tag inside the HEAD section. There is one more code that will show the positon of <SCRIPT> in body section and it is as:

<TITLE>Tag position</TITLE> <SCRIPT LANGUAGE=”Text/JavaScript”> // your script statement(s) here </SCRIPT>
37. What are the main functions performed by JavaScript Statements?

The <SCRIPT> Script statement(s) </SCRIPT> tag consists of JavaScript statement. Just to be compatible with all the browsers it is been written in comments and it also accepts a semicolon at the end of every statement. JavaScript also uses the carriage return at the end of a statement. Every statement has a purpose like Define or initialize a variable that will be used in an object when executing the script Assign a value to a property or variable so that user inputs can be taken according to the values that are defined in it. Change the value of a property or variable to give more flexibility to the use of a scripting language. Invoke an object’s method to allow faster processing of the system Invoke a function routine to allow the function to perform various activities so that the application can run at faster speed.

38. Explain with an explain the process of document loading.

When a document loads that means it is getting ready for the execution on the system. The document loads in the browser when there is a running of a document on the system. The applicaiton allows the JavaScript to look for all the properties that is given to the object and include all the property values that are used in content that is being rendered for the page about to load. It is always a good practice to include the content in <SCRIPT> tags and statements in the Body portion of the document. This way the application gets loaded immediately.

<TITLE>Immediate loading</TITLE>

JavaScript used


<SCRIPT LANGUAGE=”Text/JavaScript”> </SCRIPT>
39. What is the function of Deferred scripts?

Deferred scripts are the scripts whose statements run as grouped together statements as a function. Function provides a definition of a block that a script statement consists of to run the statements that are in the <SCRIPT> tags after all the statements loaded in browser. Functions allow to see the user clearly the visiblity inside the <SCRIPT> tag. In this tag each function starts with function() and function name is written after it including the parentheses. Once a function is loaded it becomes ready to run whenever there is a use of it. It is useful when a function gets used immediately after a page load. The Window object uses an event handler that triggers the response to the user actions and the handler is onLoad.

40. Write a program to exaplain the deferred scripts using event handlers in JavaScript.

Event handler allows a trigger to be generated when a user action takes place like clicking a button, clicking on images, etc. OnLoad is an event handlers that handles all of the page’s components that includes images, Java applets, and embedded multimedia to laod it in browser. The event handlers are mostly used in tag. Event handler is also used to run several internal script statements such that it is better to use statements in a function definition and event handler invoking the function. The code below shows onLoad event handler triggers the done() function. The function consists of an alert box that gets displayed

<TITLE>Event_handler</TITLE> <SCRIPT LANGUAGE=”Text/JavaScript”> </SCRIPT>
41. What is the difference between Scripting and Programming?

Scripting is easier to write than programming. As programming requires more hands on to the code and a language specification to write. Scripting consists of lots of tools to easily create an object model and run it using any browser, wheras programming doesn't have many tools to create an object model and it is not easy to use browser compatibility. Scripts work with more than just objects, each statement of the JavaScript does something means perform some actions, whereas programming becomes different as each and every action takes time to execute. Scriptting doesn't require lots of knowledge to be provided with and can be easily learnt, but to learn a programming language it requires lots of knowledge.

42. What does dynamic component in JavaScript contain?

Dynamic component is a model that consists of many other sub-components that are based on dynamic theory only like: Dynamic typing: these are associated with values and not having any association with the variables. JavaScript support the use of many types that can be used as an object. object based: JavaScript is an object-oriented language and it deals with the objects that are associated arrays used with prototypes. The properties of the object based component can be modified, removed or added at run-time. The properties are using built in functions that helps to keep the property of dynamicity of the application. run-time evaluation: JavaScript provides a run time evaluation using the eval() that takes some arguments provided during run time. This evaluation is used to make the scripting language more widely used as run time evaluation slows down the system but JavaScript uses the libraries to take less space.

43. What are different functional component in JavaScript?

The different components that are required in the functional model is: First-class functions: Fuctions that are first class will have some objects whose properties and methods are given by using the methods like length() and call(). These methods can be given different varibles and passed by an argumnent. nested functions: are the functions that are used in another function. It is created each time the outer function is invoked. If a function is used inside another then any constants, local variables and argument values, become part of the function object. Closures: JavaScript allows the function to be created with nested functionality. It usually try to find the combination of code that can be used to execute the application.

44. What is the difference between script type and the script language attributes?

The script type specifies the type of content that is used to show the language used by the browsers like “language=text/javascript”. This defines the MIME type that is also known as Multipurpose Internet Mail Extensions (MIME). Text in this defines a plain text format and script defines the language that will be used. The script language attribute on the other hand specify a particular version of JavaScript language that is required to run the script and to provide a mechanism to fall back if any browser doesn't support it. Script type is used to define the type through which the browser can understand the language and all the compatible browsers can execute the type according to themselves, whereas the script language attribute defines the content and its attributes that are used.

45. What are the different types of errors supported by JavaScript?

There are many errors that can occur in a system. JavaScript provides a message for all the errors at run time and dynamically generate the error code. The errors that are present: Load-time errors: these are the errors that come when loading a web page like using of improper syntax and the errors gets detected the moment user loads a page. Run-time errors: These are the errors that comes due to misuse of the language commands used inside the HTML document. This shows that it has loaded but the functionality is not properly integrated. Logic errors: these are the errors that comes due to bad logic performed on a function that is having different operation but it is made to have logic differently.

46. What are Math Constants and Functions using JavaScript?

Math object has two constant : Math.PI and Math.E Math object has following functions: Math.abs(val1);

It will give absolute value of val1.

Math.max(val1,val2);

This fuction will return maximum value from val1 and val2.

Math.random();

This function will return a random number between 0 and 1.

Math.floor(val1)

This function will returns decimal value of val1

47. What is Pop() method in JavaScript?

The pop() method is similar as the shift() method but the difference is that Shift method works at the end of the array. The pop() method take the last element off of the given array and returns it. The array on which is called is then altered. For example

var fruits = ["apple ", "banana ", "mango"]; console.log(fruits.pop() ); console.log(fruits); we get the following console output: mango ["apple ", "banana “];

48. What is difference between undefined variable and undeclared variable?

The variable which are declared in the program but not assigned any value yet is called undefined variable while the variable which are not declared in the program is called undeclared variable.

For Example:

undeclared variable:

<script> var p; alert(p); // This will give error because p is undeclared variable. </script>

? undefined variable

<script> alert(p); //This will give error because p is undefined. </script>
49. How to create an array in JavaScript?

We can create an array in JavaScript as following ways.

For example

<script> var fruits = new Array[]; fruits[0] = “Apple”; fruits[1] = “Orange”; fruits[2] = “Banana”; alert(fruits[1]); </script>

It will give output : Orange

Another easier way to create an array is as follow

<script> var fruits = [“Apple”,”Orange”,”Banana”]; alert(fruits[0]); </script>

This will give output : Apple

50. What is encodeURI() function?

encodeURI() function is used to encode the URI. This function does not encode following special characters: = , ? : $ @ / & # + Syntax: encodeURI(uri) Where uri is URI to be encoded. For example:

<script> var uri = “EmpDetails.asp?Emp=årpit&mode=edit”; document.write(encodeURI(uri) + “
”); </script>

Output: EmpDetails.asp?Emp=%C3%A5&mode=edit.

51. Can you explain about Screen object?

The screen object can be used to retrieve the information about the visitor’s screen. There are following properties of Screen objects avalHeight: This property returns the height of the screen excluding the windows taskbar. availWidth: This property returns the width of the screen excluding the windows taskbar. colorDepth: This property returns the bit depth of the color palette to display images. height: This property returns the total height of the screen pixelDepth: This property returns the color resolution of the screen in bits per pixel. width: This property returns the total width of the screen 52. What is unshift() method in Javascript?

The unshift() method is like the push() method, only it works at the beginning of the array. The unshift() method can prepend one or more elements to the beginning of an array. This alters the array on which the method was called.

For example

var fruits = [ "apple" ]; fruits.unshift( "banana" ); fruits.unshift( "mango", "strawberry" ); console.log(fruits);

we get the following console output: ["mango ", " strawberry ", " banana ", " apple "]

  1. What is unescape() function?

unescape() function is used to decode the encoded string

Syntax: unescape(string1)

Where string1 is the string to be decoded.

Example:

<script> document.write(unescape(“Questions%3F%20Get%20from%20us%21”)); </script>

Output: Questions? Get from us!

  1. How to get height and width of different browser in Javascript?

Following examples illustrate the different ways to get height and width of different browser.

For Non-IE var Width; var Height; Width = window.innerWidth; Height = window.innerHeight;

For IE 6+ in standards compliant mode

Width = document.documentElement.clientWidth; Height = document.documentElement.clientHeight;

For IE 4 compatible

Width = document.body.clientWidth; Height = document.body.clientHeight;

  1. What is the disadvantages using innerHTML in JavaScript?

If you use innerHTML the content is replaced everytime. We cannot use like 'appending to innerHTML'. Even if we use += like "innerHTML = innerHTML + ‘html’" then also the old content is replaced by html. If we use innerHTML then the entire innerHTML content is re-parsed and build into elements. Therefore it’s much slower. The innerHTML doesn't provide validation and therefore we can potentially insert invalid and broken HTML in the document and break it.

  1. What is Push() method in JavaScript?

The push() method is used to append one or more elements to the end of an array.

For example

var fruits = [ "apple" ]; fruits.push( "banana" ); fruits.push( "mango", "strawberry” ); console.log(fruits);

we get the following console output:

["apple ", "banana ", "mango ", "strawberry "]

Using Push() method we can also append multiple elements by passing multiple arguments. The elements will be appended in the order of they are inserted i.e. left to right.

  1. Explain JavaScript closures by example

-The closure is a local variable of a function which remains alive after the function has returned. -Closure combines a function with a local variable available at the time of creating closure.

For example consider following example.

function wish(msg) { console.log(msg); }

function greeting(name, occasion) { return name + ", Happy " + occasion; }

var message = greeting ("Arpit", “Birthday”);

// Pass it explicitly to wish wish(message);

By using closure we can simplify above code.

function greeting (name, occasion) { var msg = name + ", Happy " + occasion; return function wish() { console.log(msg); }; }

// create the closure var wisharpit = greeting ("Arpit", “Birthday”);

// use the closure wisharpit ();

Here wish function is nested within the greeting, so closure can access the local variable of greeting which are name, occasion and msg.

  1. What is Strict Mode in JavaScript?

-The fifth edition of ECMAScript specification has introduced Script Mode. -Strict Mode applies a layer of constraint on JavaScript. -It throws errors for actions that are problematic and didn’t throw an error before. -It throws errors for the actions which are potentially unsafe. -It shut downs the functions which are poorly thought out. -Strict mode solves mistakes that are responsible for the difficulty of JavaScript engines to perform optimizations. -To enable the strict mode we have to add the string literal “use strict” on the top of file or function as follow

function myfunction() { “use strict"; var v = “I am a strict mode function"; }

  1. How to create array in Javascript?

To create a array in Javascript we have declare the array variable.

For example

var fruits = new Array()

We can add elements in this array as below:

fruits[0] = “banana”’ fruits[1] = “apple” fruits[2] = “mango”

We can get each elements of fruit array with the index number of element where index number starts from 0.

If we want to get the second element of fruit array then we have to use index number 1 as below. document.write(fruits[1])

We also can create an array as below

var mynos = new Array(1,2,3,4,5)

  1. What is decodeURI() function?

decodeURI() function is used to decode the URI.

Syntax: decodeURI(uri)

Where uri is URI to be decoded.

For example:

<script> var uri = “EmpDetails.asp?Emp=årpit&mode=edit”; document.write(encodeURI(uri) + “
”); document.write(decodeURI(uri) + “
”); </script>

Output: EmpDetails.asp?Emp=%C3%A5&mode=edit EmpDetails.asp?Emp=årpit&mode=edit.

  1. What is difference between window.onload and onDocumentReady?

The difference is that onDocumentReady is called after the DOM is loaded without waiting for all the contents to get loaded. While window.onload() function waits until the contents of page is loaded.

Suppose there is very large image on a page, at that time onDocumentReady will wait until that image is loaded totally.

So while using the window.onlaod() function the execution will be slow, but the onDocumentReady will not wait until the image is loaded.

  1. How to manage exception handling in Javascript?

Javascript provide the features of exception handling using try..catch..finally blocks which is much similar to the C# exception handling blocks.

We have to write the suspected code in try block and all the exceptions that occur in the try block will be caught in catch block.

For example:

window.onload = function() { try { var v1=30; var v2 =v1/v3; } catch(ex) { document.write(ex.name + “ : ” +ex.message); } Finally { document.write(‘this is finally block’); } } This code snippet will cause an error: TypeError : ‘v3’ is undefined.

  1. How to change style on an element?

If we want to change only a single property of an element’s style, we can change the CSS of element using the element's style property:

var myelement = document.getElementById("mydiv"); myelement.style.width = "200px";

If we want to change value of more than one properties, we can use the element’s setAttribute method:

myelement.setAttribute("style","width: 200px; background-color: blue;");

If the CSS property contains a hyphen, for example” font-family” or “background-color”, we have to use CamelCase notation as follows:

myelement.style.fontFamily = "Arial"; myelement.style.backgroundColor = "rgb(255,222,12)";

We can also use the element’s setAttribute method to set the style property:

myelement.setAttribute("style","font-family: Arial; background-color: green");

  1. What is escape() function?

-escape() function is used to encode the string to convert it as portable string so that it can be sent across any network to any computer which supports ASCII characters. -This function encodes special characters, with the exception of @ * + - / . _

Syntax: escape(string1)

Where string1 is the string to be encoded.

Example:

<script> document.write(escape(“Questions? Get from us!”)); </script>

Output: Questions%3F%20Get%20from%20us%21

  1. What is Shift() method in Javascript?

-The shift() method is similar as the pop() method but the difference is that Shift method works at the beginning of the array. -The shift() method take the first element off of the given array and returns it. The array on which is called is then altered.

For example var myarray = ["apple ", "banana ", "mango "]; console.log(myarray.shift()); console.log(myarray); we get the following console output: apple ["banana ", "mango "];

When we call shift() on an empty array, it will return an undefined value.

=================================================================================

Source: http://tonyfreed.com/blog/top_javascript_interview_question_2015

What is the difference between call and apply?

While the syntax of those functions are almost identical. The fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments. somefun.apply(valueForThis, arrayOfArgs) somefun.call(valueForThis, arg, arg, arg)

What is the difference between == and === ?

Double equals == is used to compare the value of two operands. While triple equals === is used to compare the value AND type of two operands. Double equals uses type coercion. So "1" == 1 will be true as well as [] == 0. While triple equals will return false in both cases. Type coercion has complex rules and can have surprising results.

What is the difference between null and undefined?

Undefined means that a variable has been declared but has no value yet. Since there is no value for a variable, it has no type assigned as well. So the type will be "undefined". If you call this variable, it will return undefined. Null is an object reference meaning "no object" and it returns null.

How can you declare a class in Javascript?

In JavaScript there is no classes like in Java or PHP. In JavaScript we creates a function that simulating a class behaviour.

What is JavaScript Prototype?

In JavaScript objects are pairs of keys and values. Every JavaScript object has an internal property called [[Prototype]]. Objects in JavaScript inherits all properties from Object.prototype, while you can override them. So, prototype can be used to inherit functionality.

What is event bubbling?

Event bubbling occurs when a user interacts with a nested element and the event propagates up ("bubbles") through all of the ancestor elements.

In order to stop event bubbling we can use event.stopPropagation();

What is a "closure" in JavaScript and how to use it?

A closure is an inner function that has access to the variables in the outer function's scope chain. The most famous example of using closures is:

for (var i = 0; i < 3; i++) {
    setTimeout(function() { console.log(i); }, i * 1000 );
}

The problem is that each function executed within the loop will be executed after the entire loop has been completed. That's why console.log() will display 3,3,3. It can be prevented by creating unique scope for each iteration.

var someFunction = function(i) {
        return function() { console.log(i); };
};
for (var i = 0; i < 3; i++) {
    setTimeout(someFunction(i), i * 1000, i);
}

Closures can also be used to resolve issues with the this keyword, which is unique to each scope

==============================================================================

Source: http://www.code-sample.com/2015/04/javascript-interview-questions-answers.html

Is JavaScript case sensitive?

Yes! JavaScript is a case sensitive because a function str is not equal to Str.

What is the Type of JavaScript?

There are different of Type as given below. String, Number, Boolean, Function, Object, Null, Undefined etc

What types of Boolean operators in JavaScript?

There are three types of Boolean operators as given below. AND (&&) operator, OR (||) operator and NOT (!) Operator

What is the difference between “==” and “===”?

The double equal “==” is an auto-type conversion. It’s used to check the value and type of its variable.

The three equal “===” is not auto-type conversion. It’s used to check only value of its variable.

The real example as given below:

if(1 == ”1”) // Its returns true because it's an auto-type conversion and it check value and type both.

if(1 === ”1”) // Its returns false because it's not auto-type conversion and it check only value not  type.

If(1=== parseInt(”1”)) // Its returns true.
What is an Object?

The object is a collection of properties and the each property associated with the name-value pairs. The object can contain any data types (numbers, arrays, object etc.)

The example as given below

Var myObject= {empId : “001”, empCode :”X0091”};

In the above example, here are two properties one is empId and other is empCode and its values are “001” and “X0091”.

The properties name can me string or number. If a property name is number i.e.

Var numObject= {1 : “001”, 2 :”X0091”};

Console.log(numObject.1); //This line throw an error.

Console.log(numObject[“1”]); // will access to this line not get any error.

As per my thought, the number property name should be avoided.

Types of creating an object

Object literals Object constructor

Object Literals: This is the most common way to create the object with object literal and the example as given below.

The empty object initialized using object literal i.e.

var emptyObj= {};

This is an object with 4 items using object literal i.e.

var emptyObj ={
  empId:”Red”,
  empCode: “X0091”,
 empDetail : function(){
    alert(“Hi”);
};
};

Object Constructor: The second way to create object using object constructor and the constructor is a function used to initialize new object.

The example as given below

Var obj = new Object();
Obj.empId=”001”;
Obj.empCode=”X0091”;
Obj.empAddressDetai = function(){
       Console.log(“Hi, I Anil”);
};
What is scope variable in JavaScript?

The scope is set of objects, variables and function and the JavaScript can have global scope variable and local scope variable.

The global scope is a window object and its used out of function and within the functions. The local scope is a function object and its used within the functions.

The example for global scope variable

var gblVar = "Anil Singh";

function getDetail() {
    console.log(gblVar);
}

and other example for global

function demoTest() {
    x = 15;
};
console.log(x); //out put is 15

The example for local scope variable

function getDetail() {
    var gblVar = "Anil Singh";
    console.log(gblVar);
}

and other example for local

function demoText() {
    var x = 15;
};
console.log(x); //undefined
What is associative arrays in JavaScript?

What is array? Array is a collection of index items and it is a number indexes.

Some of programming language support array as named indexes and the JavaScript not support the array as name indexes and its provide only number indexes but provide this feature using the associative array.

The array with name indexes are called associative array and the associative array is provide a ways to store the information.

The number index array example as given below

var users = new Object();
users["Name1"] = "Anil 1";
users["Name2"] = "Anil 2";
users["Age"] = 33;
alert(Object.keys(users).length); //output is 3.
var length = Object.keys(users).length;  // 3

The name index array example as given below

var users = [];
users["Name1"] = "Anil 1";
users["Name2"] = "Anil 2";
users["Age"] = 33;
var length = users.length;         // users.length will return 0
var detail = users[0];             // users[0] will return undefined
Where to use the associate array?

I am going to explain the associate array over the database table columns. A table have some columns and its type. i.e.

The empName as text type, empAge as number type and enpDOB as date type.

If we need to find the type of a column that time we can create the associate array. i.e.

var empDetailType = new Array();

empDetailType["empName"] = "ANil"; empDetailType["empAge"] = 30; empDetailType["empDOB"] = "10/03/1984";

console.log("Find the emp age type :" + empDetailType["empAge"]);

How to achieve inheritance in JavaScript?

In the JavaScript, we can implement the inheritance using the some alternative ways and we cannot define a class keyword but we create a constructor function and using new keyword achieve it.

The some alternative ways as given below. Pseudo classical inheritance Prototype inheritance Pseudo classical inheritance is the most popular way. In this way, create a constructor function using the new operator and add the members function with the help for constructor function prototype.

The prototype based programming is a technique of object oriented programming. In this mechanism we can reuse the exiting objects as prototypes. The prototype inheritance also know as prototypal, classless or instance based inheritances.

The Inheritance example for prototype based as given below

// Create a helper function. if (typeof Object.create !== 'function') {

    Object.create = function (obj) {
        function fun() { };
        fun.prototype = obj;
        return new fun();
    };
}

//This is a parent class.
var parent = {
    sayHi: function () {
        alert('Hi, I am parent!');
    },
    sayHiToWalk: function () {
        alert('Hi, I am parent! and going to walk!');
    }
};

//This is child class and the parent class is inherited in the child class.
var child = Object.create(parent);

child.sayHi = function () {
    alert('Hi, I am a child!');
};

click to oops

The output is : Hi, I am a child!

What is typeof operator?

The typeof operator is used to find the type of variables.

The example as given below.

typeof "Anil Singh" // Returns string typeof 3.33 // Returns number typeof true // Returns Boolean typeof { name: 'Anil', age: 30 } // Returns object

typeof [10, 20, 30, 40] // Returns object

What is public, private and static variables in JavaScript? I am going to explain like strongly type object oriented language (OOPs) like(C#,C++ and java etc.).

Fist I am creating a conductor class and trying to achieve to declare the public, private and static variables and detail as given below.

function myEmpConsepts() { // This myEmpConsepts is a constructor function.

var empId = "00201"; //This is a private variable.
this.empName = "Anil Singh"; //This is a public variable.
this.getEmpSalary = function () {  //This is a public method
    console.log("The getEmpSalary method is a public method")
}

}

//This is a instace method and its call at the only one time when the call is instanciate. myEmpConsepts.prototype.empPublicDetail = function () { console.log("I am calling public vaiable in the istance method :" + this.empName); }

//This is a static vaiable and its shared by all instace. myEmpConsepts.empStaticVaiable = "Department";

var instanciateToClass = new myEmpConsepts();

Who to create the namespace in JavaScript? Please see the below example for how to create the namespace in JavaScript.

//Create the namespace. var nameSpace = nameSpace || {};

nameSpace.myEmpConsepts = function () {

var empId = "00201"; //This is a private variable.
this.empName = "Anil Singh"; //This is a public variable.
//This is public function
this.getEmp = function () {
    return "Anil Singh"
}

//This is private function
var getEmp = function () {
      return "Anil Singh"
}

return {
    getEmp: getEmp,// work as public
    getEmp: getEmp // work as public
}

}();

How to add/remove properties to object in run-time in JavaScript? I am going to explain by example for add and remove properties from JavaScript objects as give below.

This example for delete property.

//This is the JSON object. var objectJSON = { id: 1, name: "Anil Singh", dept: "IT" };

//This is the process to delete delete objectJSON.dept;

//Delete property by the array collection MyArrayColection.prototype.remove = function (index) { this.splice(index, 3); }

This example for add property

//This is used to add the property. objectJSON.age = 30;

console.log(objectJSON.age); //The result is 30;

//This is the JSON object. var objectJSON = { id: 1, name: "Anil Singh", dept: "IT", age :30

};

How to extending built-in objects in JavaScript? JavaScript support built-in objects which use to develop the flexibility of JavaScript. The built in object are date, string, math, array and object. It's very similar to other languages and its available in the window content and wok independently when brewers are loaded.

Example as give below

var date = new Date(); //This is date built-in object. var math = Math.abs(10); // this is math built-in object.

var string = "my string" // this is string built-in object.

Why never use new Array in JavaScript? We have some fundamental issues with new Array() the example in detail for array constructor function as given below.

When array have more the one integer?

var newArray = new Array(10, 20, 30, 40, 50);

console.log(newArray[0]); //returns 10. console.log(newArray.length); //returns 5.

When array have only one integer?

var newArray = new Array(10);

console.log(newArray[0]); //returns undefined console.log(newArray.length); //returns 10 because its has an error "array index out of bound";

//This is the fundamental deference to need to avoid the new array();

What is eval() and floor() functions in JavaScript? The eval() function used in execute an argument as expression or we can say that evaluate a string as expression and it used to parse the JSON.

The example over eval() function as given below.

var x = 14; eval('x + 10'); //The output is 24.

Another over eval() function example

eval('var myEval = 10'); console.log(myEval); // The output is 10.

The floor() function is a static method of Math and we can write as Math.floor() and used to round the number of downwards. i.e.

Math.floor(1.6);//The output is 1.

What is join() and isNaN() functions in JavaScript? The is join() function used to join the separator in the array.

Syntax: myArray.join(mySeparator);

The example as given below.

var alfabets = ["A", "B", "C", "D"];

//Join without seperator var result1 = alfabets.join();//The output is A B C D.

//Join with seperator. var result2 = alfabets.join(','); //The output is A, B, C, D.

The isNaN() function is used to check the value is not-a-number.

The example as given below

var var1 = isNaN(-1.23);//The output is false. var var2 = isNaN(3);//The output is false. var var3 = isNaN(0);//The output is false.

var var3 = isNaN("10/03/1984"); //The output is true.

What is closure in JavaScript?

While you create the JavaScript function within another function and the inner function freely access all the variable of outer function. i.e.

function ourterFun(i) { var var1 = 3;

function innerFun(j) {
    console.log(i + j + (++var1)); // It will return the 16.
}
innerFun(10);

}

ourterFun(2); // Pass an argument 2

The output will get 16 because innerFun() function can access to the argument "i" & variable "var1" but both are define in the outerFun() function that is closure.

That means simply accessing variable outside of your scope create a closure.

// OR Other WAYS

function ourterFun(i) { var var1 = 3;

return function (j) {
    console.log(i + j + (++var1)); // It will return the 16.
}

}

var innerFun = ourterFun(2); // innerFun() function is now a closure. innerFun(10);

What is JavaScript Hoisted?

In the JavaScript, the variables can be used before declared, this kinds of mechanism is called Hoisted. It's a default behavior of JavaScript.

You can easily understanding in the below example in detail.

//The variable declaration look like. var emp;

//The variable initialization look like. emp = "Anil Singh";

var emp; //The declaration of emp is hoisted but the value of emp is undefined. emp = 10; //The Assignment still occurs where we intended (The value of emp is 10)

function getEmp() { var emp; //The declaration of a different variable name emp is hoisted but the value of emp is undefined.

console.log(emp); //The output is undefined
emp = 20; //The assignment values is 20.
console.log(emp); //The output is 20.

}

getEmp(); console.log(emp); //The variable named emp in the outer scope still contains 10.

What is function overloading in JavaScript?

There is no real function overloading in JavaScript and it allows to pass any number of parameters of any type.

You have to check inside the function how many arguments have been passed and what is the type arguments using typeof.

The example for function overloading not supporting in JavaScript as give below.

function sum(a, b) { alert(a + b); }

function sum(c) { alert(c); }

sum(3);//The output is 3. sum(2, 4);//The output is 2.

In the JavaScript, when we write more than one functions with same name that time JavaScript consider the last define function and override the previous functions. You can see the above example output for the same.

We can achieve using the several different techniques as give below You can check the declared argument name value is undefined. We can check the total arguments with arguments.length. Checking the type of passing arguments. Using number of arguments Using optional arguments like x=x || 'default' Using different name in the first place We can use the arguments array to access any given argument by using arguments[i] What is prototype in JavaScript?

The prototype is a fundamental concept of JavaScript and its must to known JavaScript developers.

All the JavaScript objects has an object and its property called prototype and its used to add and the custom functions and property.

The example without prototype as given below.

var employee = function () { //This is a constructor function. }

//Crate the instance of above constructor function and assign in a variable var empInstance = new employee(); empInstance.deportment = "IT";

console.log(empInstance.deportment);//The output of above is IT. The example with prototype as given below. var employee = function () { //This is a constructor function.}

employee.prototype.deportment = "IT";//Now, for every instance employee will have a deportment.

//Crate the instance of above constructor function and assign in a variable var empInstance = new employee(); empInstance.deportment = "HR";

console.log(empInstance.deportment);//The output of above is IT not HR.