JAVASCRIPT INTERVIEW QUESTIONS ANSWERS

JavaScript is a scripting language. It is different from Java language. It is object-based, lightweight, cross-platform translated language. It is widely used for client-side validation. The JavaScript Translator (embedded in the browser) is responsible for translating the JavaScript code for the web browser

Both var and let are used for variable/ method declaration in javascript but the main difference between let and var is that var is function scoped whereas let is block scoped.

In modern javascript let & const are different ways of creating variables.Earlier in javascript, we use the var keyword for creating variables. let & const keyword is introduced in version ES6 with the vision of creating two different types of variables in javascript one is immutable and other is mutable.
const: It is used to create an immutable variable. Immutable variables are variables whose value is never changed in the complete life cycle of the program.
let: let is used to create a mutable variable. Mutable variables are normal variables like var that can be changed any number of time.

  • Some of the features of JavaScript are:

    • Lightweight
    • Interpreted programming language
    • Good for the applications which are network-centric
    • Complementary to Java
    • Complementary to HTML
    • Open source
    • Cross-platform

Following are the JavaScript Data types:

  • Number
  • String
  • Boolean
  • Object
  • Undefined

Some of the disadvantages of JavaScript are:

  • No support for multithreading
  • No support for multiprocessing
  • Reading and writing of files is not allowed
  • No support for networking applications.

Breaking within a string statement can be done by the use of a backslash, ‘\’, at the end of the first line

Example:

document.write("This is \a program");

And if you change to a new line when not within a string statement, then javaScript ignores break in line.

Example:

var x=1, y=2,
z=
x+y;

The above code is perfectly fine, though not advisable as it hampers debugging.

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.

  1. function msg()  
  2. {  
  3.   document.writeln(“Named Function”);  
  4. }  
  5. msg(); 

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.

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.

Yes, JavaScript is a case sensitive language. For example:

  1. Var msg = “JavaScript is a case-sensitive language”; //Here, var should be used to declare a variable  
  2. function display()   
  3. {  
  4. document.writeln(msg); // It will not display the result.  
  5. }   
  6. display();  

‘This’ keyword refers to the object from where it was called.

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.

BOM stands for Browser Object Model. It provides interaction with the browser. The default object of a browser is a window. So, you can call all the functions of the window by specifying the window or directly. The window object provides various properties like document, history, screen, navigator, location, inner Height, inner Width

// for Single line comments and

/* Multi

Line

Comment

*/

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

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

document.form[0].submit();

HTML DOM mouse events

  • onclick
  • ondblclick
  • mousemove
  • mousedown
  • mouseover
  • mouseout
  • mouseup

A primitive is a basic data type that’s not built out of other data types. It can only represent one single value. All primitives are built-in data types by necessity, (the compiler has to know about them,) but not all built-in data types are primitives.

In JavaScript there are 5 primitive data types are available they are undefinednullbooleanstring and number are available.Everything else in Javascript is an object.

The window object is created automatically by the browser that represents a window of a browser. It is not an object of JavaScript. It is a browser object.

The window object is used to display the popup dialog box. Let’s see with description.

METHODDESCRIPTION
alert()displays the alert box containing the message with ok button.
confirm()displays the confirm dialog box containing the message with ok and cancel button.
prompt()displays a dialog box to get input from the user.
open()opens the new window.
close()closes the current window.
setTimeout()performs the action after specified time like calling function, evaluating expressions.

Following are looping structures in Javascript:

  • For
  • While
  • do-while loops

“==” 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.

The history object of a browser can be used to switch to history pages such as back and forward from the current page or another page. There are three methods of history object.

  1. history.back() – It loads the previous page.
  2. history.forward() – It loads the next page.
  3. history.go(number) – The number may be positive for forward, negative for backward. It loads the given page number.

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.

In Javascript there are 3 types of Popup Boxes are available, they are

  • Alert
  • Confirm
  • Prompt

There are 3 different ways to create an array in Javascript. They are

  • By array literal
    usage:
     var myArray=[value1,value2...valueN];
  • By creating instance of Array
    usage:
    var myArray=new Array();
  • By using an Array constructor
    usage:
    var myArray=new Array('value1','value2',...,'valueN');

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.

The pop() method is similar as the shift() method but the difference is that the Shift method works at the start 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.

Example:

var cloths = ["Shirt", "Pant", "TShirt"];
cloths.pop();

//Now cloth becomes Shirt,Pant

Strict Mode adds certain compulsions to JavaScript. Under the strict mode, JavaScript shows errors for a piece of codes, which did not show an error before, but might be problematic and potentially unsafe. Strict mode also solves some mistakes that hamper the JavaScript engines to work efficiently.

Strict mode can be enabled by adding the string literal “use strict” above the file. This can be illustrated by the given example:

function myfunction() {
    "use strict";
    var v = "This is a strict mode function";
}

The function .call() and .apply() are very similar in their usage except a little difference. .call() is used when the number of the function’s arguments are known to the programmer, as they have to be mentioned as arguments in the call statement. On the other hand, .apply() is used when the number is not known. The function .apply() expects the argument to be an array.

The basic difference between .call() and .apply() is in the way arguments are passed to the function. Their usage can be illustrated by the given example.

var someObject = {
myProperty : 'Foo',

myMethod : function(prefix, postfix) {

	alert(prefix + this.myProperty + postfix);
}
};
someObject.myMethod('<', '>'); // alerts '<Foo>'
var someOtherObject  = {

	myProperty : 'Bar'

};
someObject.myMethod.call(someOtherObject, '<', '>'); // alerts '<Bar>'

someObject.myMethod.apply(someOtherObject, ['<', '>']); // alerts '<Bar>'

This method is functional at the starting of the array, unlike the push(). It adds the desired number of elements to the top of an array. For example –

var name = [ "john" ];
name.unshift( "charlie" );
name.unshift( "joseph", "Jane" );
console.log(name);

The output is shown below:

[" joseph "," Jane ", " charlie ", " john "]
  • <script>  
  • function validateform(){  
  • var name=document.myform.name.value;  
  • var password=document.myform.password.value;  
  •   
  • if (name==null || name==””){  
  •   alert(“Name can’t be blank”);  
  •   return false;  
  • }else if(password.length<6){  
  •   alert(“Password must be at least 6 characters long.”);  
  •   return false;  
  •   }  
  • }  
  • </script>  
  • <body>  
  • <form name=“myform” method=“post” action=“abc.jsp” onsubmit=“return validateform()” >  
  • Name: <input type=“text” name=“name”><br/>  
  • Password: <input type=“password” name=“password”><br/>  
  • <input type=“submit” value=“register”>  
  • </form>  
  •  

The JavaScript date object can be used to get a year, month and day. You can display a timer on the webpage by the help of JavaScript date object.

 
  1. function display()  
  2. {  
  3.   var date=new Date();    
  4. var day=date.getDate();    
  5. var month=date.getMonth()+1;    
  6. var year=date.getFullYear();    
  7. document.write(“<br>Date is: “+day+”/”+month+”/”+year);    
  8. }  
  9. display();

Leave a Reply