We’ve listed down the top 30 JavaScript interview questions and answers for web developers. After a thorough analysis, we came up with this list. And there is a high probability that you might face similar types of questions during interviews.
JavaScript is a cutting edge technology and remain in high demand. It not only used for creating high-end web applications but also powers many web development frameworks like Angular and Node.js.
In our previous posts, we’d covered a wide range interviews for web developers especially on HTML5, CSS, JavaScript, Angular, and Node.js. It is worth checking out them if you plan to become a MEAN stack or a full stack web developer.
1. Read 50 Interview Questions on AngularJS.
2. Read 30 Interview Questions on Node.js.
Top 30 JavaScript Interview Questions.
What’s an object in JavaScrpt and how do we create them?
What is scope in JavaScript?
What is <this> in JavaScript?
What is prototype property in JavaScript?
What is Closure in JavaScript?
Why is “self” needed instead of “this” in JavaScript?
What is an anonymous function and when should you use it?
What is the difference between “==” and “===”?
What are JavaScript data types?
What is prototypal inheritance in JavaScript?
What is an asynchronous programming? Why is it important in JavaScript?
What is variable typing in JavaScript?
What are the different ways to create an array in JavaScript?
What are JavaScript Cookies?
Which built-in method adds one or more elements to the end of an array and returns the new length of the array?
What is the naming conventions for the variables in JavaScript?
How will you create a Cookie using JavaScript?
How to read a Cookie using JavaScript?
How to delete a Cookie using JavaScript?
How do you submit a form using JavaScript?
Why should you not prefer to use global variables in JavaScript and how can you prevent it?
What are the different objects used in JavaScript?
What do we achieve by deferring the loading of JavaScript?
What is Strict Mode in JavaScript?
What are event handlers in JavaScript and how to use them?
What does a JavaScript function result when it has no return statement?
What is encodeURI() function?
How does the <Array()> differ from <[]> while creating a JavaScript array?
How does variable hoisting take place in JavaScript?
How will you replace all occurrences of a string in JavaScript?
Find Answers For JavaScript Interview Questions.
Q.1- What’s An Object In JavaScrpt And How Do We Create Them?
Answer.
A JavaScript object is an entity having state and behavior (properties and method). Since JavaScript is an object-based language, it treats everything as an object.
JavaScript is a template-based language not class based. It supports to create the object directly, there is no need to define a class for this.
JavaScript supports following three ways to create objects.
1. By Object Literal.
The syntax of creating an object using object literal is as follows.
object={property1:value1, property2:value2.....propertyN:valueN}
Here, property and value are separated by “:”.
Let’s take an example of creating an object using object literal technique.
<script>
std={id:1114, name:"Ram Bajaj", subject:"Physics"}
document.write(std.id+" "+std.name+" "+std.subject);
</script>
2. By Creating An Instance Of The Object (Using New Keyword).
The syntax of creating an object directly is as follows.
var objectname=new Object();
Here, the new keyword is used to create the object.
Let’s take an example of creating an object directly.
<script>
var std=new Object();
std.id=1114;
std.name="Ram Bajaj";
std.subject="Physics";
document.write(std.id+" "+std.name+" "+std.subject);
</script>
3. By Using An Object Constructor.
In this method, we create a function with arguments. The value of each of these arguments can be assigned to the current object by using this keyword.
This keyword refers to the current object.
Let’s take an example of creating an object using object constructor technique.
<script>
function std(id,name,subject){
this.id=id;
this.name=name;
this.subject=subject;
}
s=new std(1114,"Ram Bajaj","Physics");
document.write(s.id+" "+s.name+" "+s.subject);
</script>
Q-2. What Is Scope In JavaScript?
Answer.
The scope determines the accessibility of variables, objects, and functions in particular part of your code.
In JavaScript, the scope is of two types.
1. Global Scope.
A variable defined outside a function comes under the Global scope. Variables defined inside the Global scope are accessible from any part of the code. Let’s see an example.
var name = 'TechBeamers';
console.log(name); // logs 'TechBeamers'
function logName() {
console.log(name); // 'name' is accessible here and everywhere else
}
logName(); // logs 'TechBeamers'
2. Local Scope.
Variables defined inside a function comes under the Local scope. Different functions can use a variable with the same name. It is because these variables are strictly bound to the function that defines it (each having different scopes) and is not accessible in other functions. Let’s see an example.
// Global Scope
function sampleFunction() {
// Local Scope #1
function sample2Function() {
// Local Scope #2
}
}
// Global Scope
function sample3Function() {
// Local Scope #3
}
// Global Scope
Q-3. What Is <This> In JavaScript?
Answer.
All the prime languages use ‘this’ keyword to refer to an object that is currently instantiated by the class. However, in JavaScript, ‘this’ refers to an object which ‘owns’ the method. Though this varies, with how a function call happens.
Global Scope.
If no object is currently available, then ‘this’ represents the global object. In a web browser, ‘window’ is the top-level object which represents the document, location, history and a few other useful properties and methods. Let’s take a sample code.
window.Obj= "I represent the window object";
alert(window.Obj);
alert(this.Obj); // I'm the window object
alert(window === this); // true
The Scenario Of A Function Call.
In the case of a function call, ‘this’ refers to the global object.
window.Obj = "I represent the window object";
function TestFunction() {
alert(this.Obj); // I'm the window object
alert(window === this); // true
}
TestFunction();
Call Object Methods.
When an object constructor or any of its methods gets called, ‘this’ refers to an instance of an object. It is similar to any class-based language.
window.Obj = "I'm the window object";
function TestFunction() {
this.Obj = "I'm the Test object";
this.Verify1 = function() {
alert(this.Obj); // I'm the Test object
};
}
TestFunction.prototype.Verify2 = function() {
alert(this.Obj); // I'm the Test object
};
var tf= new TestFunction();
tf.Verify1();
tf.Verify2();
Q-4. What Is Prototype Property In JavaScript?
Answer.
Every JavaScript function has a prototype property (by default this property is null), that is mainly used for implementing inheritance. We add methods and properties to a function’s prototype so that it becomes available to instances of that function. Let’s take an example that calculates the perimeter of a rectangle.
function Rectangle(x, y) {
this.x = x;
this.y = y;
}
Rectangle.prototype.perimeter = function() {
return 2 * (this.x + this.y);
}
var rect = new Rectangle(4, 2);
console.log(rect.perimeter()); // outputs '12'
Q-5. What Is Closure In JavaScript?
Answer.
A closure is a JavaScript function defined inside another function. And that’s why it gets a special privilege to access three types of scope which are as follows.
Internal Scope i.e. the variables defined between its curly brackets.
Outer Function Scope i.e. the variables of the enclosing function.
Global Scope i.e. variables defined as globals.
Please note that a closure can not only access the outer function variables but also see its parameters. But it can’t call the outer function’s arguments object. However, it can directly call the outer function’s parameters.
Here is a code example describing closure by adding a function inside another function.
function outerFunc(arg1, arg2) {
var param = "I'm closure. ";
// Inner function accessing outer function variables and parameters
function innerFunc() {
return arg1 + arg2 + " " + param;
}
return innerFunc();
}
outerFunc("arg1", "arg2");
Q-6. Why Is “Self” Needed Instead Of “This” In JavaScript?
Answer.
Inner functions in JavaScript have access to all of the variables defined in the outer function. However, “this” variable is an exception. Since the nested function is just a regular function and not an object method, it’s “this” refers to the global namespace. To make it more clear, let’s look at the following example.
var aProperty = 'global';
var myObject = {
outerFun: function() {
this.aProperty = 'local';
setTimeout(function() {
console.log(this.aProperty); // outputs 'global'
}, 1);
}
};
Thus, we see that inside “setTimeout” function, “this” refers to the global object. We need a way to get a reference to the object, that is available inside the nested function. We assign the object from “this”, to another(non-special) variable, “self”. It is not a special variable and hence cannot be overwritten by other functions(like “this”). Thus on using “self” inside the inner function, we can refer to the local object. Following is the sample code.
var myObject = {
outerFun: function() {
var self = this;
this.aProperty = 'local';
setTimeout(function() {
console.log(self.aProperty); // outputs 'local'
}, 1);
}
};
Q-7. What Is An Anonymous Function And When Should You Use It?
Answer.
Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they don’t have a name like normal functions.
We use function operator to declare an anonymous function, instead of the function declaration. Also, function operator can be used to create a new function, wherever it’s valid to put an expression. For example, we declare a new function to be supplied as an argument to a function call or to assign a property of another object.
Here’s a typical example of a named function.
function testFunction()
{
alert("Welcome!!");
}
testFunction();
Here’s the same example created as an anonymous function.
var testFunction= function()
{
alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
Following are the key usage of anonymous functions.
Code brevity.
Use them in
Callbacks, and
Event handlers.
Scope management.
They are useful in the following scenario.
To create temporary/private scope.
In Closures and Recursions.
Q-8. What Is The Difference Between “==” And “===”?
Answer.
These are the operators provided by JavaScript – strict equality and Type converting equality.
Strict equality (===) returns true if the values which it is going to compare have the same data type. Taking an example, “2” will not be equal to 2 i.e. (“2″===2) will return false.
Secondly, Type converting equality (==), automatically converts the variable to value irrespective of the data type. Taking an example, here “2” will be equal to 2 i.e. (“2″===2) will return true.
Summarizing it, double equal (==) is an autotype converting equality operator while three equals (===) is a strict equality operator, i.e. it will not convert values automatically.
Q-9. What Are JavaScript Data Types?
Answer.
JavaScript supports three Primary, two Composite and two Special data types. Next, we list down the data types in each of the categories.
Primary Data Types.
String
Number
Boolean
Composite Data Types.
Object
Array
Special Data Types.
Null
Undefined
Q-10. What Is Prototypal Inheritance In JavaScript?
Answer.
Most of the Object Oriented languages support classes and objects. Here, Classes inherit from other classes.
In JavaScript, the inheritance is prototype-based. This means that there are no classes. Instead, there is an object that inherits from another object.
JavaScript provides three different types of Prototypal Inheritance.
1. Delegation (I.E. The Prototype Chain).
A delegate prototype is an object that serves as a base for another object. When you inherit from a delegate prototype, the new object gets a reference to the prototype.
When we try to access any property, it first checks in the properties owned by the object. If that property does not exist there, it checks in the ‘[[Prototype]]’ and so on. If that property does not exist there, it checks in the ‘[[Prototype]]’ and so on. Gradually, it moves up the prototype chain, until it reaches the <Object.prototype> i.e. the root delegate for most of the objects.
2. Concatenative Inheritance (I.E. Mixins, Object.Assign()).
It is the process of inheriting the features of one object to another by copying the source objects properties. JavaScript calls these source prototypes by the name mixins. This process makes use of the JavaScript method Object.assign(). However, before ES6, the <.extend()> method was used.
3. Functional (Not To Be Confused With Functional Programming).
In JavaScript, a function can create an object. It’s not necessary to be a constructor(or a class). It is called a factory function. Functional inheritance produces an object from a factory and also extends it, by assigning properties.
Every type of Prototypal Inheritance supports a separate set of use-cases, applicable to it. All of them are equally useful in their ability to enable composition. It provides has-a, uses-a, or can-do relationship as compared to the is-a relationship created with class inheritance.
Q-11. What Is An Asynchronous Programming? Why Is It Important In JavaScript?
Answer.
In Asynchronous programming, the engine runs in an event loop. On encountering a blocking operation, a request gets fired and the code keeps running without blocking for the result. When its execution completes, and the response is ready, it fires an interrupt, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations in an asynchronous programming.
The user interface is asynchronous by nature and spends most of the time, waiting for user input to interrupt the event loop and trigger event handlers. Node is asynchronous by default. It means that the server works by waiting for a network request in a loop. Thus, it accepts more incoming requests, while the first one is getting handled.
It is important in JavaScript because it’s suitable for user interface code and beneficial for maintaining the performance on the server.
Q-12. What Is Variable Typing In JavaScript?
Answer.
JavaScript is very loosely typed language. It means that the variables are declared without a type. Its type is determined once a value is assigned to it. It can change as the variable appears in different contexts.
It’s in contrast to the strongly typed languages that require type declarations.
Consider the following examples.
/* JavaScript Example (loose typing) */
var a = 13; // Number declaration
var b = "thirteen"; // String declaration
/* Java Example (strong typing) */
int a = 13; // int declaration
String b = "thirteen"; // String declaration
Variable type in JavaScript is determined internally. In the above example, var ‘a’ will be of type ‘Number’ and var ‘b’ will be of type ‘String’.
Q-13. What Are The Different Ways To Create An Array In JavaScript?
Answer.
There are two main ways to create an array in JavaScript.
1. Using An Array Initializer (Array Literal).
The array initializer (array literal) syntax is simple. It is a comma-separated list of values in square brackets.
Let’s see some examples.
var myArray1 = [1,2,3,4,5] // an array with 5 elements
var myArray2 = [5] // an array with 1 element
var myArray3 = [true,'Hi',[7]] // element types need not be the same.
2. Using The Array Constructor.
The Array constructor method has three different syntaxes. If we call the constructor with two or more arguments, it declares an array with array elements also initialized. If we provide only one argument to the Array constructor, it refers to the length of the new array with, elements not initialized. Lastly, the constructor without any argument creates an array with its length set to zero with elements not initialized.
Let’s see some examples.
var myArray4 = new Array(1,2,3,4,5) // an array with 5 elements
var myArray5 = new Array(20) // an empty array of length 20
var myArray6 = new Array() // an empty array of length 0
Q-14. What Are JavaScript Cookies?
Answer.
A cookie is a piece of data which is sent from a website (that owns the requested web page) and gets stored locally by the browser at the user end. Cookies are needed because HTTP protocol which arranges for the transfer of web pages to your browser, is stateless. It means that HTTP has no way to keep track of the activities performed by the user at an earlier point in time. One way to resolve this issue is by using cookies. It contains following data.
A name-value pair containing the actual data.
An expiry date after which the cookie is no longer valid.
The domain and path of the server it should be sent to.
When a request arrives at the server for a web page that maintains a cookie, the server appends the cookie to the HTTP header to send it across. Server side programs can then read out the information included in it and decide that you have the right to view the page or not and other user preferences.
Thus, every time you visit the site that maintains the cookies, your information is available there.
Q-15. Which Built-In Method Adds One Or More Elements To The End Of An Array And Returns The New Length Of The Array?
Answer.
The push() method adds one or more elements to the end of an array and returns the new length of the array.
Q-16. What Is The Naming Conventions For The Variables In JavaScript?
Answer.
We have to follow the below rules while naming the variables in JavaScript.
Do not use any of the JavaScript reserved keywords as a name for your variable. For example, “break” or “boolean” are JavaScript keywords, and if used as variable names, it’s invalid.
JavaScript variable names should not start with a numeral (0-9). It must begin with a letter or the underscore character. For example, 123var is an invalid variable name, but _123var is a valid one.
Also, JavaScript variable names are case sensitive. For example, test and Test are two different variables.
Q-17. How Will You Create A Cookie Using JavaScript?
Answer.
The simplest way to create a cookie is to assign a string value to the <document.cookie> object.
Its syntax is as follows.
document.cookie = "key1 = value1; key2 = value2; expires = date";
Here, “expires” attribute is optional. We have to provide a date or time value for this attribute.
If we provide a valid value for the date or time, then the cookie will expire at the given date or time and it will not be accessible after that.
Q-18. How To Read A Cookie Using JavaScript?
Answer.
To read a Cookie, we have to access the value of the <document.cookie> object. This <document.cookie> string maintains a list of <name = value> pairs that is separated with semicolons.
Where,
"name" is the name of a cookie and
"value" is its string value.
We use String <split()> function to break the <document.cookie> object to sub-strings. Each of these sub-strings contains a key-value pair which represents the information related to a Cookie.
Q-19. How To Delete A Cookie Using JavaScript?
Answer.
To delete a Cookie, we have to set its expiry date to a time that occurred in the past. If attempts are made to read a deleted Cookie then, nothing is returned.
Q-20. How Do You Submit A Form Using JavaScript?
Answer.
We use the following in the web page code to submit a form.
document.forms[0].submit();
Here <0> refers to the index of the form. If we have more than one forms on a web page, then the index for the first one will be “0”, for the second form, its value will be “1” and so on.
Q-21. Why Should You Not Prefer To Use Global Variables In JavaScript And How Can You Prevent It?
Answer.
The principal issue in using a global variable is that someone else can create another variable with the same name. And you may not know it until the duplicate could overwrite the value of your variable.
To avoid using globals, follow any of the following approaches.
1. Create a single global variable that holds all your other variables.
var myGlobalList = {};
myGlobalList.first = "test";
2. Enclose all of your code in a self-executing method/function so that any variable declared inside remain in the function scope.
(function(){
var test = "myvar";
})();
Q-22. What Are The Different Objects Used In JavaScript?
Answer.
JavaScript uses a hierarchical structure, applicable to all the objects created in a document. Following are the objects, used in JavaScript that shows the relationship of one object to another.
Window Object.
It is the topmost object in the hierarchy. It refers to the content area of the browser window that consists of HTML documents. Each frame is also a window that has some actions inside it.
Document Object.
A Document object represents the HTML document that the window will display. It has various properties that refer to other objects, which allow access to and modification of content in the document.
Form Object.
A form object is used to take user data as input for processing. It corresponds to an HTML input form constructed with the <FORM>…</FORM> tag.
Q-23. What Do We Achieve By Deferring The Loading Of JavaScript?
Answer.
During page load operation, by default, the parsing of the HTML code remains paused until the execution of the script has not stopped.
Now, if the script is heavy or the server is slow, then this will result in a delay in displaying the web page.
By deferring the loading of JavaScript, we instruct the browser to load the script, only after the loading of the web page(DOM) has finished. It reduces the loading time of the webpage, and it gets displayed faster.
In this way, it makes the page load quicker, without the average user even realizing that some JavaScript load after the DOM has loaded.
Let’s see an example.
<script>
// this piece of code runs first
</script>
<script defer="defer">
//do stuff, but defer it (runs last)
</script>
<script>
//do more stuff (runs second)
</script>
Here the middle block will execute once the page has loaded even though it appears before the last block.
Q-24. What Is Strict Mode In JavaScript?
Answer.
Strict Mode imposes a layer of constraint on JavaScript. It provides following enhancements.
JavaScript will throw an error if we try to use the elements of a deprecated language.
To use a variable, it has become mandatory to declare it.
It disallows duplicate property and parameter names.
The eval() method is safer to use, but still considered evil in some cases.
It deprecates the “with” statement.
JavaScript will throw an error if we try to assign a value to a read-only property.
It decreases the global namespace pollution.
To enable strict mode, we have to add, “use strict” directive to the code. The physical location of the “strict” directive determines its scope. If used at the beginning of the js file, its scope is global. However, if we declare strict mode at the first line in the function block, its scope restricts to that function only.
Q.25- What Are Event Handlers In JavaScript And How To Use Them?
Answer.
JavaScript event handlers are functions that bind to a specific HTML DOM event. And events are the part of HTML document object model (DOM). An event can take place in one of the following cases.
Due to user actions on a web page.
<onclick()>, <onmouseover()>, <onkeydown()>
Some events are callbacks triggered by the browser when a page changes its state.
<onload()>, <onunload()>, <onresize()>
Whenever the DOM receives an event, it calls the JavaScript event handler function bind to the event. To use a handler function, we can assign it to the desired event as an attribute of the target HTML element. Please follow the below example.
<HTML>
<BODY>
<FORM>
<INPUT TYPE=”button” VALUE=”Test” onClick=”window.alert ('Event Handler')”>
</FORM>
</BODY>
</HTML>
Q-26. What Does A JavaScript Function Result When It Has No Return Statement?
Answer.
If a function doesn’t use the return statement, then it returns undefined as the return value.
However, the browser won’t print anything in its console as it ignores if the expression returns an undefined value. But if we explicitly call such a function inside the console.log() method, then it’ll print exact value.
function test(){}
console.log(test()); // will print 'undefined'
Q-27. What Is EncodeURI() Function?
Answer.
The encodeURI() function is used to encode a URI. This function encodes all special characters, except these < , / ? : @ & = + $ #>.
Let’s See An Example.
var uri="http://www.techbeamers.com/how to make a website using javaScript";
var encodedURI = encodeURI(uri);
console.log(encodedURI);
Output.
http://www.somedomain.com/how%20to%20make%20a%20website%20using%20javaScript
We see that JavaScript encodes the space between the words in the <uri> variable as <%20>. Thus, the encodeURI function is used to encode special reserved characters and other non-ASCII characters in the URI.
Q-28. How Does The <Array()> Differ From <[]> While Creating A JavaScript Array?
Answer.
Both the <Array()> and <[]> works almost the same in JavaScript.
If we use them as is (i.e. without any argument) to create an array object, then they will result in an array object of zero length. Also, if we pass a string or a list of strings as arguments, even then result will be similar.
However, they differ when the input argument is of integer type. In that case, the <Array(n)> statement will create an uninitialized array of size of n. Whereas, the <[n]> statement will create an array of size <1> and assign <n> as value to the first element.
Q-29. How Does Variable Hoisting Take Place In JavaScript?
Answer.
In JavaScript, variable declarations are the first piece of code that executes irrespective of their location. Hence, it doesn’t matter whether we declare a variable at the top or anywhere else. This functionality which moves the declaration to the top either inside a function or in the global code is known as hoisting.
out = 2;
var out;
function myfunc() {
var in = "inside"
// some code
}
// ...
JavaScript will interpret the above in the following manner.
var out;
out = 2;
function myfunc() {
var in;
// some code
in = "inside";
}
Q-30. How Will You Replace All Occurrences Of A String In JavaScript?
Answer.
We can use String’s <replace()> method to substitute any string. There are following two ways to use this method.
Pass The Input String As A Regular Expression.
str = "ghktestlllltest-sdds"
str = str.replace(/test/g, '');
alert(str)
Use RegExp Class To Create A Regular Expression And Pass It.
String.prototype.replaceAll = function(find, replace) {
var target = this;
return target.replace(new RegExp(find, 'g'), replace);
};
str = "ghktestlllltest-sdds"
str = str.replaceAll('test', '');
alert(str)
Summary – Top 30 JavaScript Interview Questions.
Web development market is growing from last many years. And with the inception of new technologies like AngularJS/Node.js, it shall grow further. And we are sure that JavaScript would keep its place as the leading skill for web developers.
Also, we wish you can use the above JavaScript interview questions as a quick reference to brush up your skills.
JavaScript is a cutting edge technology and remain in high demand. It not only used for creating high-end web applications but also powers many web development frameworks like Angular and Node.js.
In our previous posts, we’d covered a wide range interviews for web developers especially on HTML5, CSS, JavaScript, Angular, and Node.js. It is worth checking out them if you plan to become a MEAN stack or a full stack web developer.
1. Read 50 Interview Questions on AngularJS.
2. Read 30 Interview Questions on Node.js.
Top 30 JavaScript Interview Questions.
What’s an object in JavaScrpt and how do we create them?
What is scope in JavaScript?
What is <this> in JavaScript?
What is prototype property in JavaScript?
What is Closure in JavaScript?
Why is “self” needed instead of “this” in JavaScript?
What is an anonymous function and when should you use it?
What is the difference between “==” and “===”?
What are JavaScript data types?
What is prototypal inheritance in JavaScript?
What is an asynchronous programming? Why is it important in JavaScript?
What is variable typing in JavaScript?
What are the different ways to create an array in JavaScript?
What are JavaScript Cookies?
Which built-in method adds one or more elements to the end of an array and returns the new length of the array?
What is the naming conventions for the variables in JavaScript?
How will you create a Cookie using JavaScript?
How to read a Cookie using JavaScript?
How to delete a Cookie using JavaScript?
How do you submit a form using JavaScript?
Why should you not prefer to use global variables in JavaScript and how can you prevent it?
What are the different objects used in JavaScript?
What do we achieve by deferring the loading of JavaScript?
What is Strict Mode in JavaScript?
What are event handlers in JavaScript and how to use them?
What does a JavaScript function result when it has no return statement?
What is encodeURI() function?
How does the <Array()> differ from <[]> while creating a JavaScript array?
How does variable hoisting take place in JavaScript?
How will you replace all occurrences of a string in JavaScript?
Find Answers For JavaScript Interview Questions.
Q.1- What’s An Object In JavaScrpt And How Do We Create Them?
Answer.
A JavaScript object is an entity having state and behavior (properties and method). Since JavaScript is an object-based language, it treats everything as an object.
JavaScript is a template-based language not class based. It supports to create the object directly, there is no need to define a class for this.
JavaScript supports following three ways to create objects.
1. By Object Literal.
The syntax of creating an object using object literal is as follows.
object={property1:value1, property2:value2.....propertyN:valueN}
Here, property and value are separated by “:”.
Let’s take an example of creating an object using object literal technique.
<script>
std={id:1114, name:"Ram Bajaj", subject:"Physics"}
document.write(std.id+" "+std.name+" "+std.subject);
</script>
2. By Creating An Instance Of The Object (Using New Keyword).
The syntax of creating an object directly is as follows.
var objectname=new Object();
Here, the new keyword is used to create the object.
Let’s take an example of creating an object directly.
<script>
var std=new Object();
std.id=1114;
std.name="Ram Bajaj";
std.subject="Physics";
document.write(std.id+" "+std.name+" "+std.subject);
</script>
3. By Using An Object Constructor.
In this method, we create a function with arguments. The value of each of these arguments can be assigned to the current object by using this keyword.
This keyword refers to the current object.
Let’s take an example of creating an object using object constructor technique.
<script>
function std(id,name,subject){
this.id=id;
this.name=name;
this.subject=subject;
}
s=new std(1114,"Ram Bajaj","Physics");
document.write(s.id+" "+s.name+" "+s.subject);
</script>
Q-2. What Is Scope In JavaScript?
Answer.
The scope determines the accessibility of variables, objects, and functions in particular part of your code.
In JavaScript, the scope is of two types.
1. Global Scope.
A variable defined outside a function comes under the Global scope. Variables defined inside the Global scope are accessible from any part of the code. Let’s see an example.
var name = 'TechBeamers';
console.log(name); // logs 'TechBeamers'
function logName() {
console.log(name); // 'name' is accessible here and everywhere else
}
logName(); // logs 'TechBeamers'
2. Local Scope.
Variables defined inside a function comes under the Local scope. Different functions can use a variable with the same name. It is because these variables are strictly bound to the function that defines it (each having different scopes) and is not accessible in other functions. Let’s see an example.
// Global Scope
function sampleFunction() {
// Local Scope #1
function sample2Function() {
// Local Scope #2
}
}
// Global Scope
function sample3Function() {
// Local Scope #3
}
// Global Scope
Q-3. What Is <This> In JavaScript?
Answer.
All the prime languages use ‘this’ keyword to refer to an object that is currently instantiated by the class. However, in JavaScript, ‘this’ refers to an object which ‘owns’ the method. Though this varies, with how a function call happens.
Global Scope.
If no object is currently available, then ‘this’ represents the global object. In a web browser, ‘window’ is the top-level object which represents the document, location, history and a few other useful properties and methods. Let’s take a sample code.
window.Obj= "I represent the window object";
alert(window.Obj);
alert(this.Obj); // I'm the window object
alert(window === this); // true
The Scenario Of A Function Call.
In the case of a function call, ‘this’ refers to the global object.
window.Obj = "I represent the window object";
function TestFunction() {
alert(this.Obj); // I'm the window object
alert(window === this); // true
}
TestFunction();
Call Object Methods.
When an object constructor or any of its methods gets called, ‘this’ refers to an instance of an object. It is similar to any class-based language.
window.Obj = "I'm the window object";
function TestFunction() {
this.Obj = "I'm the Test object";
this.Verify1 = function() {
alert(this.Obj); // I'm the Test object
};
}
TestFunction.prototype.Verify2 = function() {
alert(this.Obj); // I'm the Test object
};
var tf= new TestFunction();
tf.Verify1();
tf.Verify2();
Q-4. What Is Prototype Property In JavaScript?
Answer.
Every JavaScript function has a prototype property (by default this property is null), that is mainly used for implementing inheritance. We add methods and properties to a function’s prototype so that it becomes available to instances of that function. Let’s take an example that calculates the perimeter of a rectangle.
function Rectangle(x, y) {
this.x = x;
this.y = y;
}
Rectangle.prototype.perimeter = function() {
return 2 * (this.x + this.y);
}
var rect = new Rectangle(4, 2);
console.log(rect.perimeter()); // outputs '12'
Q-5. What Is Closure In JavaScript?
Answer.
A closure is a JavaScript function defined inside another function. And that’s why it gets a special privilege to access three types of scope which are as follows.
Internal Scope i.e. the variables defined between its curly brackets.
Outer Function Scope i.e. the variables of the enclosing function.
Global Scope i.e. variables defined as globals.
Please note that a closure can not only access the outer function variables but also see its parameters. But it can’t call the outer function’s arguments object. However, it can directly call the outer function’s parameters.
Here is a code example describing closure by adding a function inside another function.
function outerFunc(arg1, arg2) {
var param = "I'm closure. ";
// Inner function accessing outer function variables and parameters
function innerFunc() {
return arg1 + arg2 + " " + param;
}
return innerFunc();
}
outerFunc("arg1", "arg2");
Q-6. Why Is “Self” Needed Instead Of “This” In JavaScript?
Answer.
Inner functions in JavaScript have access to all of the variables defined in the outer function. However, “this” variable is an exception. Since the nested function is just a regular function and not an object method, it’s “this” refers to the global namespace. To make it more clear, let’s look at the following example.
var aProperty = 'global';
var myObject = {
outerFun: function() {
this.aProperty = 'local';
setTimeout(function() {
console.log(this.aProperty); // outputs 'global'
}, 1);
}
};
Thus, we see that inside “setTimeout” function, “this” refers to the global object. We need a way to get a reference to the object, that is available inside the nested function. We assign the object from “this”, to another(non-special) variable, “self”. It is not a special variable and hence cannot be overwritten by other functions(like “this”). Thus on using “self” inside the inner function, we can refer to the local object. Following is the sample code.
var myObject = {
outerFun: function() {
var self = this;
this.aProperty = 'local';
setTimeout(function() {
console.log(self.aProperty); // outputs 'local'
}, 1);
}
};
Q-7. What Is An Anonymous Function And When Should You Use It?
Answer.
Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they don’t have a name like normal functions.
We use function operator to declare an anonymous function, instead of the function declaration. Also, function operator can be used to create a new function, wherever it’s valid to put an expression. For example, we declare a new function to be supplied as an argument to a function call or to assign a property of another object.
Here’s a typical example of a named function.
function testFunction()
{
alert("Welcome!!");
}
testFunction();
Here’s the same example created as an anonymous function.
var testFunction= function()
{
alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
Following are the key usage of anonymous functions.
Code brevity.
Use them in
Callbacks, and
Event handlers.
Scope management.
They are useful in the following scenario.
To create temporary/private scope.
In Closures and Recursions.
Q-8. What Is The Difference Between “==” And “===”?
Answer.
These are the operators provided by JavaScript – strict equality and Type converting equality.
Strict equality (===) returns true if the values which it is going to compare have the same data type. Taking an example, “2” will not be equal to 2 i.e. (“2″===2) will return false.
Secondly, Type converting equality (==), automatically converts the variable to value irrespective of the data type. Taking an example, here “2” will be equal to 2 i.e. (“2″===2) will return true.
Summarizing it, double equal (==) is an autotype converting equality operator while three equals (===) is a strict equality operator, i.e. it will not convert values automatically.
Q-9. What Are JavaScript Data Types?
Answer.
JavaScript supports three Primary, two Composite and two Special data types. Next, we list down the data types in each of the categories.
Primary Data Types.
String
Number
Boolean
Composite Data Types.
Object
Array
Special Data Types.
Null
Undefined
Q-10. What Is Prototypal Inheritance In JavaScript?
Answer.
Most of the Object Oriented languages support classes and objects. Here, Classes inherit from other classes.
In JavaScript, the inheritance is prototype-based. This means that there are no classes. Instead, there is an object that inherits from another object.
JavaScript provides three different types of Prototypal Inheritance.
1. Delegation (I.E. The Prototype Chain).
A delegate prototype is an object that serves as a base for another object. When you inherit from a delegate prototype, the new object gets a reference to the prototype.
When we try to access any property, it first checks in the properties owned by the object. If that property does not exist there, it checks in the ‘[[Prototype]]’ and so on. If that property does not exist there, it checks in the ‘[[Prototype]]’ and so on. Gradually, it moves up the prototype chain, until it reaches the <Object.prototype> i.e. the root delegate for most of the objects.
2. Concatenative Inheritance (I.E. Mixins, Object.Assign()).
It is the process of inheriting the features of one object to another by copying the source objects properties. JavaScript calls these source prototypes by the name mixins. This process makes use of the JavaScript method Object.assign(). However, before ES6, the <.extend()> method was used.
3. Functional (Not To Be Confused With Functional Programming).
In JavaScript, a function can create an object. It’s not necessary to be a constructor(or a class). It is called a factory function. Functional inheritance produces an object from a factory and also extends it, by assigning properties.
Every type of Prototypal Inheritance supports a separate set of use-cases, applicable to it. All of them are equally useful in their ability to enable composition. It provides has-a, uses-a, or can-do relationship as compared to the is-a relationship created with class inheritance.
Q-11. What Is An Asynchronous Programming? Why Is It Important In JavaScript?
Answer.
In Asynchronous programming, the engine runs in an event loop. On encountering a blocking operation, a request gets fired and the code keeps running without blocking for the result. When its execution completes, and the response is ready, it fires an interrupt, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations in an asynchronous programming.
The user interface is asynchronous by nature and spends most of the time, waiting for user input to interrupt the event loop and trigger event handlers. Node is asynchronous by default. It means that the server works by waiting for a network request in a loop. Thus, it accepts more incoming requests, while the first one is getting handled.
It is important in JavaScript because it’s suitable for user interface code and beneficial for maintaining the performance on the server.
Q-12. What Is Variable Typing In JavaScript?
Answer.
JavaScript is very loosely typed language. It means that the variables are declared without a type. Its type is determined once a value is assigned to it. It can change as the variable appears in different contexts.
It’s in contrast to the strongly typed languages that require type declarations.
Consider the following examples.
/* JavaScript Example (loose typing) */
var a = 13; // Number declaration
var b = "thirteen"; // String declaration
/* Java Example (strong typing) */
int a = 13; // int declaration
String b = "thirteen"; // String declaration
Variable type in JavaScript is determined internally. In the above example, var ‘a’ will be of type ‘Number’ and var ‘b’ will be of type ‘String’.
Q-13. What Are The Different Ways To Create An Array In JavaScript?
Answer.
There are two main ways to create an array in JavaScript.
1. Using An Array Initializer (Array Literal).
The array initializer (array literal) syntax is simple. It is a comma-separated list of values in square brackets.
Let’s see some examples.
var myArray1 = [1,2,3,4,5] // an array with 5 elements
var myArray2 = [5] // an array with 1 element
var myArray3 = [true,'Hi',[7]] // element types need not be the same.
2. Using The Array Constructor.
The Array constructor method has three different syntaxes. If we call the constructor with two or more arguments, it declares an array with array elements also initialized. If we provide only one argument to the Array constructor, it refers to the length of the new array with, elements not initialized. Lastly, the constructor without any argument creates an array with its length set to zero with elements not initialized.
Let’s see some examples.
var myArray4 = new Array(1,2,3,4,5) // an array with 5 elements
var myArray5 = new Array(20) // an empty array of length 20
var myArray6 = new Array() // an empty array of length 0
Q-14. What Are JavaScript Cookies?
Answer.
A cookie is a piece of data which is sent from a website (that owns the requested web page) and gets stored locally by the browser at the user end. Cookies are needed because HTTP protocol which arranges for the transfer of web pages to your browser, is stateless. It means that HTTP has no way to keep track of the activities performed by the user at an earlier point in time. One way to resolve this issue is by using cookies. It contains following data.
A name-value pair containing the actual data.
An expiry date after which the cookie is no longer valid.
The domain and path of the server it should be sent to.
When a request arrives at the server for a web page that maintains a cookie, the server appends the cookie to the HTTP header to send it across. Server side programs can then read out the information included in it and decide that you have the right to view the page or not and other user preferences.
Thus, every time you visit the site that maintains the cookies, your information is available there.
Q-15. Which Built-In Method Adds One Or More Elements To The End Of An Array And Returns The New Length Of The Array?
Answer.
The push() method adds one or more elements to the end of an array and returns the new length of the array.
Q-16. What Is The Naming Conventions For The Variables In JavaScript?
Answer.
We have to follow the below rules while naming the variables in JavaScript.
Do not use any of the JavaScript reserved keywords as a name for your variable. For example, “break” or “boolean” are JavaScript keywords, and if used as variable names, it’s invalid.
JavaScript variable names should not start with a numeral (0-9). It must begin with a letter or the underscore character. For example, 123var is an invalid variable name, but _123var is a valid one.
Also, JavaScript variable names are case sensitive. For example, test and Test are two different variables.
Q-17. How Will You Create A Cookie Using JavaScript?
Answer.
The simplest way to create a cookie is to assign a string value to the <document.cookie> object.
Its syntax is as follows.
document.cookie = "key1 = value1; key2 = value2; expires = date";
Here, “expires” attribute is optional. We have to provide a date or time value for this attribute.
If we provide a valid value for the date or time, then the cookie will expire at the given date or time and it will not be accessible after that.
Q-18. How To Read A Cookie Using JavaScript?
Answer.
To read a Cookie, we have to access the value of the <document.cookie> object. This <document.cookie> string maintains a list of <name = value> pairs that is separated with semicolons.
Where,
"name" is the name of a cookie and
"value" is its string value.
We use String <split()> function to break the <document.cookie> object to sub-strings. Each of these sub-strings contains a key-value pair which represents the information related to a Cookie.
Q-19. How To Delete A Cookie Using JavaScript?
Answer.
To delete a Cookie, we have to set its expiry date to a time that occurred in the past. If attempts are made to read a deleted Cookie then, nothing is returned.
Q-20. How Do You Submit A Form Using JavaScript?
Answer.
We use the following in the web page code to submit a form.
document.forms[0].submit();
Here <0> refers to the index of the form. If we have more than one forms on a web page, then the index for the first one will be “0”, for the second form, its value will be “1” and so on.
Q-21. Why Should You Not Prefer To Use Global Variables In JavaScript And How Can You Prevent It?
Answer.
The principal issue in using a global variable is that someone else can create another variable with the same name. And you may not know it until the duplicate could overwrite the value of your variable.
To avoid using globals, follow any of the following approaches.
1. Create a single global variable that holds all your other variables.
var myGlobalList = {};
myGlobalList.first = "test";
2. Enclose all of your code in a self-executing method/function so that any variable declared inside remain in the function scope.
(function(){
var test = "myvar";
})();
Q-22. What Are The Different Objects Used In JavaScript?
Answer.
JavaScript uses a hierarchical structure, applicable to all the objects created in a document. Following are the objects, used in JavaScript that shows the relationship of one object to another.
Window Object.
It is the topmost object in the hierarchy. It refers to the content area of the browser window that consists of HTML documents. Each frame is also a window that has some actions inside it.
Document Object.
A Document object represents the HTML document that the window will display. It has various properties that refer to other objects, which allow access to and modification of content in the document.
Form Object.
A form object is used to take user data as input for processing. It corresponds to an HTML input form constructed with the <FORM>…</FORM> tag.
Q-23. What Do We Achieve By Deferring The Loading Of JavaScript?
Answer.
During page load operation, by default, the parsing of the HTML code remains paused until the execution of the script has not stopped.
Now, if the script is heavy or the server is slow, then this will result in a delay in displaying the web page.
By deferring the loading of JavaScript, we instruct the browser to load the script, only after the loading of the web page(DOM) has finished. It reduces the loading time of the webpage, and it gets displayed faster.
In this way, it makes the page load quicker, without the average user even realizing that some JavaScript load after the DOM has loaded.
Let’s see an example.
<script>
// this piece of code runs first
</script>
<script defer="defer">
//do stuff, but defer it (runs last)
</script>
<script>
//do more stuff (runs second)
</script>
Here the middle block will execute once the page has loaded even though it appears before the last block.
Q-24. What Is Strict Mode In JavaScript?
Answer.
Strict Mode imposes a layer of constraint on JavaScript. It provides following enhancements.
JavaScript will throw an error if we try to use the elements of a deprecated language.
To use a variable, it has become mandatory to declare it.
It disallows duplicate property and parameter names.
The eval() method is safer to use, but still considered evil in some cases.
It deprecates the “with” statement.
JavaScript will throw an error if we try to assign a value to a read-only property.
It decreases the global namespace pollution.
To enable strict mode, we have to add, “use strict” directive to the code. The physical location of the “strict” directive determines its scope. If used at the beginning of the js file, its scope is global. However, if we declare strict mode at the first line in the function block, its scope restricts to that function only.
Q.25- What Are Event Handlers In JavaScript And How To Use Them?
Answer.
JavaScript event handlers are functions that bind to a specific HTML DOM event. And events are the part of HTML document object model (DOM). An event can take place in one of the following cases.
Due to user actions on a web page.
<onclick()>, <onmouseover()>, <onkeydown()>
Some events are callbacks triggered by the browser when a page changes its state.
<onload()>, <onunload()>, <onresize()>
Whenever the DOM receives an event, it calls the JavaScript event handler function bind to the event. To use a handler function, we can assign it to the desired event as an attribute of the target HTML element. Please follow the below example.
<HTML>
<BODY>
<FORM>
<INPUT TYPE=”button” VALUE=”Test” onClick=”window.alert ('Event Handler')”>
</FORM>
</BODY>
</HTML>
Q-26. What Does A JavaScript Function Result When It Has No Return Statement?
Answer.
If a function doesn’t use the return statement, then it returns undefined as the return value.
However, the browser won’t print anything in its console as it ignores if the expression returns an undefined value. But if we explicitly call such a function inside the console.log() method, then it’ll print exact value.
function test(){}
console.log(test()); // will print 'undefined'
Q-27. What Is EncodeURI() Function?
Answer.
The encodeURI() function is used to encode a URI. This function encodes all special characters, except these < , / ? : @ & = + $ #>.
Let’s See An Example.
var uri="http://www.techbeamers.com/how to make a website using javaScript";
var encodedURI = encodeURI(uri);
console.log(encodedURI);
Output.
http://www.somedomain.com/how%20to%20make%20a%20website%20using%20javaScript
We see that JavaScript encodes the space between the words in the <uri> variable as <%20>. Thus, the encodeURI function is used to encode special reserved characters and other non-ASCII characters in the URI.
Q-28. How Does The <Array()> Differ From <[]> While Creating A JavaScript Array?
Answer.
Both the <Array()> and <[]> works almost the same in JavaScript.
If we use them as is (i.e. without any argument) to create an array object, then they will result in an array object of zero length. Also, if we pass a string or a list of strings as arguments, even then result will be similar.
However, they differ when the input argument is of integer type. In that case, the <Array(n)> statement will create an uninitialized array of size of n. Whereas, the <[n]> statement will create an array of size <1> and assign <n> as value to the first element.
Q-29. How Does Variable Hoisting Take Place In JavaScript?
Answer.
In JavaScript, variable declarations are the first piece of code that executes irrespective of their location. Hence, it doesn’t matter whether we declare a variable at the top or anywhere else. This functionality which moves the declaration to the top either inside a function or in the global code is known as hoisting.
out = 2;
var out;
function myfunc() {
var in = "inside"
// some code
}
// ...
JavaScript will interpret the above in the following manner.
var out;
out = 2;
function myfunc() {
var in;
// some code
in = "inside";
}
Q-30. How Will You Replace All Occurrences Of A String In JavaScript?
Answer.
We can use String’s <replace()> method to substitute any string. There are following two ways to use this method.
Pass The Input String As A Regular Expression.
str = "ghktestlllltest-sdds"
str = str.replace(/test/g, '');
alert(str)
Use RegExp Class To Create A Regular Expression And Pass It.
String.prototype.replaceAll = function(find, replace) {
var target = this;
return target.replace(new RegExp(find, 'g'), replace);
};
str = "ghktestlllltest-sdds"
str = str.replaceAll('test', '');
alert(str)
Summary – Top 30 JavaScript Interview Questions.
Web development market is growing from last many years. And with the inception of new technologies like AngularJS/Node.js, it shall grow further. And we are sure that JavaScript would keep its place as the leading skill for web developers.
Also, we wish you can use the above JavaScript interview questions as a quick reference to brush up your skills.
No comments:
Post a Comment
Hello all, if you have any doubt feel free comment