MainMenu

Home Java Overview Maven Tutorials

Important JavaScript Interview Question Answer

JavaScript Interview Question for freshers

:- What are the different actions that are performed using JavaScript?
- JavaScript allows 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 the server to the client machine for retransmission. - It also allows to safe and secure the application from the outside world.



:- How can JavaScript language be separated from objects?
JavaScript treats and creates the 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.



:- 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 the program interoperable.



:- What is the importance of tags. - The example is given as : // End of the scripting language // your code here



:- Why JavaScript is called as Script for all browsers?
JavaScript is written after - This uses the



:- What are the main functions performed by JavaScript Statements?
The 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.



:- 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 the content that is being rendered for the page about to load. It is always a good practice to include the content in



:- 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



:- 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.



:- 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 the 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.



:- What are the 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 : These 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.



:- 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.



:- 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.



:- 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.



:- 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 “];



:- 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: ?
undefined variable



:- How to create an array in JavaScript?
- We can create an array in JavaScript as following ways : - For example : - It will give output : Orange - Another easier way to create an array is as follow : - This will give output : Apple



:- 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 : Output : EmpDetails.asp?
Emp=%C3%A5&mode=edit.



:- 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.



:- 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 "]



:- What is unescape() function?
- The unescape() function is used to decode the encoded string. - Syntax : unescape(string1) - Where string1 is the string to be decoded. - Example : - Output : Questions?
Get from us! 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;



:- 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.



:- 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.



:- 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 : 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.



:- 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"; }



:- How to create an array in Javascript?
- To create an 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)



:- What is decodeURI() function?
- The decodeURI() function is used to decode the URI. - Syntax : decodeURI(uri) Where uri is URI to be decoded - For example : - Output : EmpDetails.asp?
Emp=%C3%A5&mode=edit EmpDetails.asp?
Emp=Ã¥rpit&mode=edit.



:- What is the 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.



:- How to manage exception handling in Javascript?
- Javascript provides 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.



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



:- What is escape() function?
- The 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 : - Output : Questions%3F%20Get%20from%20us%21



:- 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.



1 :- What is JavaScript?

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.



2 :- Name some of the JavaScript features. Following are the features of JavaScript − JavaScript is a lightweight, interpreted programming language. JavaScript is designed for creating network-centric applications. JavaScript is complementary to and integrated with Java. JavaScript is is complementary to and integrated with HTML. JavaScript is open and cross-platform.



3 :- What are the advantages of using JavaScript?

Following are the advantages of using JavaScript − Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server. Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something. Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard. Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.



4 :- What are disadvantages of using JavaScript?

We can not treat JavaScript as a full fledged programming language. It lacks the following important features − Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason. JavaScript can not be used for Networking applications because there is no such support available. JavaScript doesn't have any multithreading or multiprocess capabilities.



5 :- Is JavaScript a case-sensitive language?

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



6 :- How can you create an Object in JavaScript?

JavaScript supports Object concept very well. You can create an object using the object literal as follows − var emp = { name: "Zara", age: 10 };



7 :- How can you read properties of an Object in JavaScript?

You can write and read properties of an object using the dot notation as follows − // Getting object properties emp.name // ==> Zara emp.age // ==> 10 // Setting object properties emp.name = "Daisy" // <== Daisy emp.age = 20 // <== 20



8 :- How can you create an Array in JavaScript?

You can define arrays using the array literal as follows − var x = []; var y = [1, 2, 3, 4, 5];



9 :- How to read elements of an array in JavaScript?

An array has a length property that is useful for iteration. We can read elements of an array as follows − var x = [1, 2, 3, 4, 5]; for (var i = 0; i < x.length; i++) { // Do something with x[i] }



10 :- What is a named function in JavaScript?

How to define a named function?

A named function has a name when it is defined. A named function can be defined using function keyword as follows − function named(){ // do some stuff here }



11 :- How many types of functions JavaScript supports?

A function in JavaScript can be either named or anonymous.



12 :- How to define a anonymous function?

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



13 :- Can you assign a anonymous function to a variable?

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



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

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



15 :- What is arguments object in JavaScript?

JavaScript variable arguments represents the arguments passed to a function.



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

Using typeof operator, we can get the type of arguments passed to a function. For example − function func(x){ console.log(typeof x, arguments.length); } func(); //==> "undefined", 0 func(1); //==> "number", 1 func("1", "2", "3"); //==> "string", 3



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

Using arguments.length property, we can get the total number of arguments passed to a function. For example − function func(x){ console.log(typeof x, arguments.length); } func(); //==> "undefined", 0 func(1); //==> "number", 1 func("1", "2", "3"); //==> "string", 3



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

The arguments object has a callee property, which refers to the function you're inside of. For example − function func() { return arguments.callee; } func(); // ==> func



19 :- What is the purpose of 'this' operator in JavaScript?

JavaScript famous keyword this always refers to the current context.



20 :- What are the valid scopes of a variable in JavaScript?

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes. Global Variables − A global variable has global scope which means it is visible everywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.



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

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



22 :- What is callback?

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



23 :- What is closure?

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



24 :- Give an example of closure?

Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them − function create() { var counter = 0; return { increment: function() { counter++; }, print: function() { console.log(counter); } } } var c = create(); c.increment(); c.print(); // ==> 1



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

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



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

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



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

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



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

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



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

length() method returns the length of the string.



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

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



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

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



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

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



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

sort() method sorts the elements of an array.



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

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



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

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



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

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



37 :- Which built-in method returns the string representation of the number's value?

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



38 :- What are the variable naming conventions in JavaScript?

While naming your variables in JavaScript keep following rules in mind. You should not use any of the JavaScript reserved keyword as variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid. JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123test is an invalid variable name but _123test is a valid one. JavaScript variable names are case sensitive. For example, Name and name are two different variables.



39 :- How typeof operator works?

The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand. The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.



40 :- What typeof returns for a null value?

It returns "object".



41 :- Can you access Cookie using javascript?

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



42 :- How to create a Cookie using JavaScript?

The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this − Syntax − document.cookie = "key1 = value1; key2 = value2; expires = date"; Here expires attribute is option. If you provide this attribute with a valid date or time then cookie will expire at the given date or time and after that cookies' value will not be accessible.



43 :- How to read a Cookie using JavaScript?

Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value. You can use strings' split() function to break the string into key and values.



44 :- How to delete a Cookie using JavaScript?

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



45 :- How to redirect a url using JavaScript?

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



46 :- How to print a web page using javascript?

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



47 :- What is Date object in JavaScript?

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



48 :- What is Number object in JavaScript?

he Number object represents numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class. Syntax − Creating a number object − var val = new Number(number); If the argument cannot be converted into a number, it returns NaN (Not-a-Number).



49 :- How to handle exceptions in JavaScript?

The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions. You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.



50 :- What is purpose of onError event handler in JavaScript?

The onerror event handler was the first feature to facilitate error handling for JavaScript. The error event is fired on the window object whenever an exception occurs on the page. The onerror event handler provides three pieces of information to identify the exact nature of the error − Error message − The same message that the browser would display for the given error. URL − The file in which the error occurred. Line number − The line number in the given URL that caused the error.



Tags : Javascript Interview questions & answers, Important JavaScript interview questions, Javascript Interview Question for freshers







No comments:

Post a Comment