Technology Digestified - Javascript Interview Questions

August 12, 2017 | Author: techdigest | Category: Java Script, Http Cookie, Html Element, Variable (Computer Science), Scope (Computer Science)
Share Embed Donate


Short Description

Javascript Interview Questions...

Description

Articles of Technology Digestified Javascript Interview Questions 2011-11-12 12:11:14 Jinal Desai

1. What’s relationship between JavaScript and ECMAScript? Ans. ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3. 2. Which types javascript supports? Ans. Number, String, Boolean, Function, Object, Null, Undefined. 3. How do you convert numbers between different bases in JavaScript? Ans. Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt (“3F”, 16); 4. What does isNaN function do? Ans. Return true if the argument is not a number. 5. What is negative infinity? Ans. It’s a number in JavaScript, derived by dividing negative number by zero. 6. What boolean operators does JavaScript support? Ans. &&, || and ! 7. What does “1″+2+4 evaluate to? Ans. Since 1 is a string, everything is a string, so the result is 124. 8. How about 2+5+”8″? Ans. Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result. 9. What looping structures are there in JavaScript? Ans. for, while, do-while loops, but no foreach. 10. How do you create a new object in JavaScript? Ans. var obj = new Object(); or var obj = {}; 11. How do you assign object properties? Ans. obj["age"] = 17 or obj.age = 17. 12. What’s a way to append a value to an array? Ans. arr[arr.length] = value; 13. What is “this” keyword? Ans. It refers to the current object. 14. What is difference between window.onload and onDocumentReady? Ans. The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means there’s a huge delay before any code is executed. That isn’t what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that. 15. What is the difference between == and === ? Ans. The == checks for value equality, but === checks for both type and value. 16. What is the difference between undefined value and null value? Ans. undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value. Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object. Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically. 17. How do you change the style/class on any element? Ans. document.getElementById(“myText”).style.fontSize = “20?; //-ordocument.getElementById(“myText”).className = “anyclass”;

18. What are Javascript closures?When would you use them? Ans. Two one sentence summaries: => A closure is the local variables for a function – kept alive after the function has returned, or => A closure is a stack-frame which is not deallocated when the function returns. A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created. The following code returns a reference to a function: function sayHello2(name) { var text = ‘Hello ‘ + name; // local variable var sayAlert = function() { alert(text); } return sayAlert; } Closures reduce the need to pass state around the application. The inner function has access to the variables in the outer function so there is no need to store the information somewhere that the inner function can get it. This is important when the inner function will be called after the outer function has exited. The most common example of this is when the inner function is being used to handle an event. In this case you get no control over the arguments that are passed to the function so using a closure to keep track of state can be very convenient. 19. What is unobtrusive javascript? How to add behavior to an element using javascript? Ans. Unobtrusive Javascript refers to the argument that the purpose of markup is to describe a document’s structure, not its programmatic behavior and that combining the two negatively impacts a site’s maintainability. Inline event handlers are harder to use and maintain, when one needs to set several events on a single element or when one is using event delegation. Say an input field with the name “date” had to be validated at runtime: document.getElementsByName("date")[0]. addEventListener("change", validateDate, false); function validateDate(){ // Do something when the content of the 'input' element with the name 'date' is changed. } Although there are some browser inconsistencies with the above code, so programmers usually go with a javascript library such as JQuery or YUI to attach behavior to an element like above. 20. What is Javascript namespacing? How and where is it used? Ans. Using global variables in Javascript is evil and a bad practice. That being said, namespacing is used to bundle up all your functionality using a unique name. In JavaScript, a namespace is really just an object that you’ve attached all further methods, properties and objects. It promotes modularity and code reuse in the application. 21. What is the difference between innerHTML and append() in JavaScript? Ans. InnerHTML is not standard, and its a String. The DOM is not, and although innerHTML is faster and less verbose, its better to use the DOM methods like appendChild(), firstChild.nodeValue, etc to alter innerHTML content. 22. When does div.setAttribute(‘###’) not equal div.###? Ans. When you’re trying to set an element’s class attribute, IE has issues. Therefore, it’s better to use .className instead of .setAttribute(). There is also an issue with .setAttribute() and style in IE, so .style should be used. // Don't do this: el.setAttribute('class', 'foobar'); // Do this instead: el.className = 'foobar'; // Don't do this: el.setAttribute('style', 'color: #000');

// Do this instead: el.style.color = '#000'; 23. What’s the difference between these two statements: var x = 3; x = 3; Ans. The first puts the variable in the scope of whatever function it was defined. The second places the variable in global scope. It can potentially cause collision with other variables with the same name. Therefore, the keyword var should always be used when defining variables, and an anonymous function should be used as a closure if need be, encapsulating multiple functions which can share access to the same set of variables. That makes sure the variables stay sandboxed, accessible only by those functions which need them. 24. What’s the difference between: !!(obj1 && obj2); (obj1 && obj2); Ans. The first returns a “real” boolean value, because you first negate what is inside the parenthesis, but then immediately negate it again. So, it’s like saying something is “not not” truth-y, making it true. The second example simply checks for the existence of the obj1 and obj2, but might not necessarily return a “real” boolean value, instead returning something that is either truth-y or false-y. This can be problematic, because false-y can be the number 0, or an empty string, etc. Simple existence can be truth-y. A “real” boolean will only be true or false. 25. Write a one-line piece of JavaScript code that concatenates all strings passed into a function. Ans. function concatenate() { return String.prototype.concat.apply('', arguments); } 26. What do these two examples have in common? Example 1: var obj = document.getElementById('adiv'); document.getElementById('adiv').ptr = obj; Example 2: function assignClick() { var el = document.createElement('div'); function handleClick() { el.innerHTML = 'clicked!'; } el.attachEvent('onclick', handleClick); } Ans. 1. Both create potential memory leaks, especially in Internet Explorer. 2. (Example 1)This is bad practice, because you first assign a DOM element to a variable, but then you assign that same element to a (nonexistent) property of the element itself. This creates a sort of circular logic loop, and will negatively impact performance. 3. (Example 2)This example will only work in Internet Explorer, because it employs the proprietary .attachEvent() method. Granted, .innerHTML is also proprietary (now a standard), but unlike .attachEvent(), .innerHTML is widely supported in all modern browsers. To make this example more cross-browser friendly, the W3C standard .addEventListener() should attempted first, and if it does not exist, then try .attachEvent() as a fallback. 27. What is the result of a.foo(2)? var a = (function(y,x) { var x = null; return { foo: function(x){ return this.bar(x * y); }, bar: function(x){ return x + y; } } })(3,4); Ans. 1. function(3,4) // 4 is not used in this example, y becomes 3 2. foo(2) // x is passed in as param

3. return bar(2 * 3) // y is 3 from initialization 4. bar(6) // x is passed in as param again 5. return 6 + 3 // y is still 3 from init 28. Why ’7′ + 4 gives ’74′ and ’7′ – 4 gives 3? Ans. In first one it takes “+” as concatenation operation and considering ’7′ as string it concatenates the two value. In second one since considering “-” as minus arithmatic operators converts string ’7′ into number and performs arithmatic operation and calculates the value. 29. How can JavaScript make a Web site easier to use? That is, are there certain JavaScript techniques that make it easier for people to use a Web site? Ans. JavaScript’s greatest potential gift to a Web site is that scripts can make the page more immediately interactive, that is, interactive without having to submit every little thing to the server for a server program to re-render the page and send it back to the client. For example, consider a top-level navigation panel that has, say, six primary image map links into subsections of the Web site. With only a little bit of scripting, each map area can be instructed to pop up a more detailed list of links to the contents within a subsection whenever the user rolls the cursor atop a map area. With the help of that popup list of links, the user with a scriptable browser can bypass one intermediate menu page. The user without a scriptable browser (or who has disabled JavaScript) will have to drill down through a more traditional and time-consuming path to the desired content. 30. What’s a way to append a value to an array? Ans. arr[arr.length] = value; 31. How do you assign object properties? Ans. obj["age"] = 17 or obj.age = 17. 32. What is two different ways to create a new object in JavaScript? Ans. var obj = new Object(); or var obj = {}; 33. What does the delete operator do? Ans. The delete operator is used to delete all the variables and objects used in the program ,but it does not delete variables declared with var keyword. 34. Does javascript have the concept level scope? Ans. No. Javascript does not have block level scope,all the variables declared inside a function possess the same level of scope unlike c,c++,java. 35. What is variable typing in javascript? Ans. It is perfectly legal to assign a number to a variable and then assign a string to the same variable as follows example i = 10; i = "string"; This is called variable typing. 36. What are undefined and undeclared variables? Ans. Undeclared variables are those that are not declared in the program (do not exist at all),trying to read their values gives runtime error.But if undeclared variables are assigned then implicit declaration is done. Undefined variables are those that are not assigned any value but are declared in the program.Trying to read such variables gives special value called undefined value. 37. How to read and write a file using javascript? Ans. I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java applet that reads files for the script. 38. How to detect the operating system on the client machine? Ans. In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used. 39. How do you submit a form using Javascript? Ans. Use document.forms[0].submit();

(0 refers to the index of the form – if you have more than one form in a page, then the first one has the index 0, second has index 1 and so on). 40. How do you target a specific frame from a hyperlink? Ans. Include the name of the frame in the target attribute of the hyperlink. 41. What is a fixed-width table and its advantages? Ans. Fixed width tables are rendered by the browser based on the widths of the columns in the first row, resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table. If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables. 42. Where are cookies actually stored on the hard disk? Ans. This depends on the user’s browser and OS. In the case of Netscape with Windows OS,all the cookies are stored in a single file called cookies.txt c:\Program Files\Netscape\Users\username\cookies.txt In the case of IE,each cookie is stored in a separate file namely [email protected] c:\Windows\Cookies\[email protected] 43. What can javascript programs do? Ans. Generation of HTML pages on-the-fly without accessing the Web server. The user can be given control over the browser like User input validation Simple computations can be performed on the client’s machine The user’s browser, OS, screen size, etc. can be detected Date and Time Handling. 44. How to set a HTML document’s background color? Ans. document.bgcolor property can be set to any appropriate color. 45. In a pop-up browser window, how do you refer to the main browser window that opened it? Ans. Use window.opener to refer to the main window from pop-ups. 46. What is the data type of variables in JavaScript? Ans. All variables are of object type in JavaScript. 47. Methods GET and POST in HTML forms – what’s the difference? Ans. GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about 2kb. POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair. 48. How to embed javascript in a web page? Ans.javascript code can be embedded in a web page between tags. 49. How to get the contents of an input box using Javascript? Ans. Use the “value” property. var myValue = window.document.getElementById("MyTextBox").value; 50. How to determine the state of a checkbox using Javascript? Ans. var checkedStatus = window.document.getElementById("myCheckBox").checked; 51. How to set the focus in an element using Javascript? Ans. function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } 52. How to access an external javascript file that is stored externally and not embedded? Ans. This can be achieved by using the following tag between head tags or between body tags.

53. What is the difference between an alert box and a confirmation box? Ans. An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel. 54. What is a prompt box? Ans. A prompt box allows the user to enter input by providing a text box. 55. Can javascript code be broken in different lines? Ans. Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement. that is , document.write("Hello \ world"); is possible but not document.write \ ("hello world"); 56. How you put a “close window” link on a page ? Ans. Close 57. How to hide javascript code from old browsers that dont run it? Ans.Use the below specified style of comments // or Use the some html code tags and code the display html statements between these and this will appear on the page if the browser does not support javascript. 58. Name the numeric constants representing max,min values. Ans. Number.MAX_VALUE Number.MIN_VALUE 59. How to write messages to the screen without using “document.write()” ? Ans. Changing the contents of an element is a much better solution. When the method showStatus is invoked it will change the content of the span. function showStatus(message) { var element = document.getElementById("mystatus"); element.textContent = message; //for Firefox element.innerHTML = message; //for IE (why can't we all just get along?) return true; } Test. 60. How to change style on an element? Ans. Between CSS and javascript is a weird symmetry. CSS style rules are layed on top of the DOM. The CSS property names like “font-weight” are transliterated into “myElement.style.fontWeight”. The class of an element can be swapped out. For example: document.getElementById("myText").style.color = "green"; document.getElementById("myText").style.fontSize = "20"; //or document.getElementById("myText").className = "regular"; 61. How to remove the event listener: ? Ans. document.getElementById("hitme4").removeEventListener("click", hitme4, false);

62. How to make elements invisible ? Ans. Change the “visibility” attribute of the style object associated with your element. Remember that a hidden element still takes up space, use “display” to make the space disappear as well. if ( x == y) { myElement.style.visibility = 'visible'; } else { myElement.style.visibility = 'hidden'; } 63. How to set the cursor to wait ? Ans. In theory, we should cache the current state of the cursor and then put it back to its original state. document.body.style.cursor = 'wait'; //do something interesting and time consuming document.body.style.cursor = 'auto'; 64. How to reload the current page ? Ans. window.location.reload(true); 65. how to force a page to go to another page using JavaScript ? Ans. location.href="http://newhost/newpath/newfile.html"; 66. How to create a function using function constructor? Ans. The following example creates a function called square with argument x and returns x multiplied by itself. var square = new Function ("x","return x*x"); 67. Have you heard of Douglas Crockford? Ans. Yes he is the “inventor” of JSON. 68. What debugging tools do you use? Ans. Firebug in Firefox (console.log(); method) and Visual Studio in IE (‘debug’ command inserted in javascript file). Blog this! Bookmark on Delicious Digg this post Recommend on Facebook Share on FriendFeed Buzz it up Share on Linkedin Share on Orkut share via Reddit Share with Stumblers Share on technorati Tweet about it Subscribe to the comments on this post

View more...

Comments

Copyright ©2017 KUPDF Inc.