Saturday 28 March 2015

Javascript interview questions and answers

 What is JavaScript?

JavaScript is a client-side scripting language that can be inserted into HTML pages and is understood by web browsers.
 What are JavaScript types?

Following are the JavaScript types:
  • Number
  • String
  • Boolean
  • Function
  • Object
  • Null
  • Undefined
 What is the use of isNaN function?

isNan function returns true if the argument is not a number otherwise it is false.

 Enumerate the differences between Java and JavaScript?

Java is a complete programming language. In contrast, JavaScript is a coded program that can be introduced to HTML pages. These two languages are not at all inter-dependent and are designed for the different intent.  Java is an object – oriented programming (OOPS) or structured programming language like C++ or C whereas JavaScript is a client-side scripting language and it is said to be unstructured programming.


 What is negative infinity?

Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.

 Is it possible to break JavaScript Code into several lines?

Breaking within a string statement can be done by the use of a backslash, ‘\’, at the end of the first line
Example:
And if you change to a new line when not within a string statement, then javaScript ignores break in line.
Example:
The above code is perfectly fine, though not advisable as it hampers debugging.

 Which company developed JavaScript?

Netscape is the software company who developed JavaScript.

What are undeclared and undefined variables?

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.
Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

Write the code for adding new elements dynamically?
 What are global variables? How are these variable declared and what are the problems associated with using them?

Global variables are those that are available throughout the length of the code, that is, these have no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared.
Example:
// Declare a global globalVariable = “Test”;
The problems that are faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.

 What is a prompt box?

A prompt box is a box which allows the user to enter input by providing a text box.  Label and box will be provided to enter the text or number.

 What is ‘this’ keyword in JavaScript?

‘This’ keyword is used to point at the current object in the code. For instance: If the code is presently at an object created by the help of the ‘new’ keyword, then ‘this’ keyword will point to the object being created.

 Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer, if any?

Timers are used to execute a piece of code at a set time or also to repeat the code in a given interval of time. This is done by using the functions setTimeout, setInterval and clearInterval.
The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay. The setInterval(function, delay) function is used to repeatedly execute the given function in the mentioned delay and only halts when cancelled. The clearInterval(id) function instructs the timer to stop.
Timers are operated within a single thread, and thus events might queue up, waiting to be executed.

 Which symbol is used for comments in Javascript?

// for Single line comments and
/*   Multi
Line
Comment
*/

 What is the difference between ViewState and SessionState?

‘ViewState’ is specific to a page in a session.
‘SessionState’ is specific to user specific data that can be accessed across all pages in the web application.

 What is === operator?

=== is called as strict equality operator which returns true when the two operands are having the same value without any type conversion.

     What are all the looping structures in JavaScript?

    Following are looping structures in Javascript:
    • For
    • While
    • do-while loops
     What is called Variable typing in Javascript?

    Variable typing is used to assign a number to a variable and the same variable can be assigned to a string.
    Example

    This is called variable typing.

     How can you convert the string of any base to integer in JavaScript?

    The parseInt() function is used to convert numbers between different bases. parseInt() takes the string to be converted as its first parameter, and the second parameter is the base of the given string.
    In order to convert 4F (of base 16) to integer, the code used will be –
     Explain the difference between “==” and “===”?

    “==” checks only for equality in value whereas “===” is a stricter equality test and returns false if either the value or the type of the two variables are different.

     What would be the result of 3+2+”7″?

    Since 3 and 2 are integers, they will be added numerically. And since 7 is a string, its concatenation will be done. So the result would be 57.

     Explain how to detect the operating system on the client machine?

    In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used.

     What do mean by NULL in Javascript?

    The NULL value is used to represent no value or no object.  It implies no object or null string, no valid boolean value, no number and no array object.

     What is the function of delete operator?

    The functionality of delete operator is used to delete all variables and objects in a program but it cannot delete variables declared with VAR keyword.

    Between JavaScript and an ASP script, which is faster?

    JavaScript is faster. JavaScript is a client-side language and thus it does not need the assistance of the web server to execute. On the other hand, ASP is a server-side language and hence is always slower than JavaScript.


    javascript-code-snippet


     What is an undefined value in JavaScript?


    Undefined value means the
    • Variable used in the code doesn’t exist
    • Variable is not assigned to any value
    • Property doesn’t exist
     What are all the types of Pop up boxes available in JavaScript?
    • Alert
    • Confirm and
    • Prompt
    What is the use of Void(0)?

    Void(0) is used to prevent the page from refreshing and parameter “zero” is passed while calling.
    Void(0) is used to call another method without refreshing the page.

     How can a page be forced to load another page in JavaScript?

    The following code has to be inserted to achieve the desired effect:
     What is the data type of variables of in JavaScript?

    All variables in the JavaScript are object data types.

     What is the difference between an alert box and a confirmation box?

    An alert box displays only one button which is the OK button.
    But a Confirmation box displays two buttons namely OK and cancel.

    What are escape characters?

    Escape characters (Backslash) is used when working with special characters like single quotes, double quotes, apostrophes and ampersands. Place backslash before the characters to make it display.
    Example:
     What are JavaScript Cookies?

    Cookies are the small test files stored in a computer and it gets created when the user visits the websites to store information that they need. Example could be User Name details and shopping cart information from the previous visits.

     Explain what is pop()method in JavaScript?

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

    Whether JavaScript has concept level scope?

    No. JavaScript does not have concept level scope. The variable declared inside the function has scope inside the function.

    Explain how can you submit a form using JavaScript?

    To submit a form using JavaScript use document.form[0].submit();

    document.form[0].submit();

     Does JavaScript support automatic type conversion?

    Yes JavaScript does support automatic type conversion, it is the common way of type conversion used by JavaScript developers

    How can the style/class of an element be changed?

    It can be done in the following way:
    or
     Explain how to read and write a file using JavaScript?

    There are two ways to read and write a file using JavaScript
    • Using JavaScript extensions
    • Using a web page and Active X objects
     Mention what is the disadvantage of using innerHTML in JavaScript?

    If you use innerHTML in JavaScript the disadvantage is
    • Content is replaced everywhere
    • We cannot use like “appending to innerHTML”
    • Even if you use +=like “innerHTML = innerHTML + ‘html’” still the old content is replaced by html
    • The entire innerHTML content is re-parsed and build into elements, therefore its much slower
    • The innerHTML does not provide validation and therefore we can potentially insert valid and broken HTML in the document and break it
     What is break and continue statements?

    Break statement exits from the current loop.
    Continue statement continues with next statement of the loop.


    Consider the following statements and tell what would be the output of the logs statements?

    var price1 = 10;
    var price2 = 10;
    var price3 = new Number('10'); // A complex numeric object because new was used.
    console.log(price1 === price2); 
    console.log(price1 === price3);


    Ans:-
    console.log(price1 === price2); // Logs true.
    console.log(price1 === price3); /* Logs false because price3 contains a complex number object and price 1
    is a primitive value. */



    What would be the output of the following statements?


    var object1 = { same: 'same' };
    var object2 = { same: 'same' };
    console.log(object1 === object2);


    Ans:- 

    // Logs false, JavaScipt does not care that they are identical and of the same object type.
    When comparing complex objects, they are equal only when they reference the same
    object (i.e. have the same address). Two variables containing identical objects are not
    equal to each other since they do not actually point at the same object.




    What is the use of Math Object in Javascript?


    The math object provides you properties and methods for mathematical constants and functions.
    ex:-

    Code:
    var x = Math.PI; // Returns PI
    var y = Math.sqrt(16); // Returns the square root of 16
    var z = Math.sin(90);    Returns the sine of 90

     What do you understand by this keyword in javascript? 


    Ans:-In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most context that is placed on the stack. The following gives two different results (in the browser, where by-default the window object is the 0-level context):

    Code:
    var obj = { outerWidth : 20 };

    function say() {
        alert(this.outerWidth);
    }
    say();//will alert window.outerWidth
    say.apply(obj);//will alert obj.outerWidth

    What does "1"+2+4 evaluate to? 


    Ans:-Since 1 is a string, everything is a string, so the result is 124. 


    What does 3+4+"7" evaluate to?


    Ans:-Since 3 and 4 are integers, this is number arithmetic, since 7 is a string, it’s concatenation, so 77 is the result.


    How do you change the style/class on any element using javascript?


    Ans:-

    Code:
    document.getElementById(“myText”).style.fontSize = “10";
    -or-
    document.getElementById(“myText”).className = “anyclass”;


    What looping structures are there in JavaScript?
     
    Ans:-for, while, do-while loops


    what is an object in JavaScript, give an example?


    Ans:-
    An object is just a container for a collection of named values

    // Create the man object

    Code:
    var man = new Object();
    man.name = 'Vikas Ahlawat';
    man.living = true;
    man.age = 27;


    How you will add function as a property in a JavaScript object? Give example.


    Ans:-

    Code:
    var man = new Object();
    man.name = 'Vikas Ahlawat';
    man.living = true;
    man.age = 27;

    man.getName = function() { return man.name;}
    console.log(man.getName()); // Logs 'Vikas Ahlawat'.




    What is the similarity between 1st and 2nd statement?

    1st:- var myString = new String('male'); // An object.
    2nd:- var myStringLiteral = 'male'; // Primitive string value, not an object.


    Ans:- Both will call String() constructor function
    you can confirm it by run the following statement
    console.log(myString.constructor, myStringLiteral.constructor);


    What will be the output of the following statements?


    Code:
    var myString = 'Vikas' // Create a primitive string object.
    var myStringCopy = myString; // Copy its value into a new variable.
    var myString = null; // Manipulate the value
    console.log(myString, myStringCopy);
    Ans:- // Logs 'null Vikas'


     What is a closure in JavaScript?
    JavaScript allows you to declare a function within another function, and the local variables still can be accessible even after returning from the function you called.
    In other words, a closure is the local variables for a function which is kept alive after the function has returned.
    An example :
    function goodMorning(name) {
    var text = ‘Good Morning ‘ + name; // local variable
    var goodMorningAlert = function() { alert(text); }
    return sayAlert;
    }
    var goodMorningAlert2 = goodMorning(‘Bob’);
    goodMorningAlert2();
    In the example above, when goodMorningAlert2() will be executed, you will see output as an alert with “Good Morning Bob”.
     Difference between window.onload and onDocumentReady?
    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 isnt 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.
     What is the difference between == and === ?
    The == checks for value equality, but === checks for both type and value.
     What does “1”+2+4 evaluate to? What about 5 + 4 + “3”?
    Since 1 is a string, everything is a string, so the result is 124. In the second case, its 93.
     What is the difference between undefined value and null value?
    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.
     What are Javascript closures?When would you use them?
    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.
     What is unobtrusive javascript? How to add behavior to an element using javascript?
    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.
    1
    <input type="text" name="date" />
    Say an input field with the name “date” had to be validated at runtime:
    1
    2
    3
    4
    5
    6
    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.
     What is Javascript namespacing? How and where is it used?
    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.
     What datatypes are supported in Javascript?
    Number, String, Undefined, null, Boolean
     What is the difference between innerHTML and append() in JavaScript?
    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.

    No comments:

    Post a Comment