0% found this document useful (0 votes)
63 views14 pages

Top 15 JavaScript Interview Questions

Top 15 JavaScript Interview Questions

Uploaded by

Akash Rawat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
63 views14 pages

Top 15 JavaScript Interview Questions

Top 15 JavaScript Interview Questions

Uploaded by

Akash Rawat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 14

Top 15 JavaScript

Interview Questions
for Web Development
Roles
1. What are the advantages of using JavaScript?
Answer: Lightweight: JavaScript can be executed within the user’s browser
without having to communicate with the server, saving on bandwidth.
Versatile: JavaScript supports multiple programming paradigms—object-
oriented, imperative, and functional programming and can be used on
both front-end and server-side technologies.
Sleek Interactivity: Because tasks can be completed within the browser
without communicating with the server, JavaScript can create a smooth
"desktop-like" experience for the end user.
Rich Interfaces: From drag-and-drop blocks to stylized sliders, there are
numerous ways that JavaScript can be used to enhance a website’s
UI/UX.
Prototypal Inheritance: Objects can inherit from other objects, which
makes JavaScript so simple, powerful, and great for dynamic applications.

2. What are Closures in JavaScript?


Answer: Closures provide a better, and concise way of writing JavaScript
code for the developers and programmers. Closures are created whenever
a variable that is defined outside the current scope is accessed within the
current scope.
function hello(name) {
var message = "hello " + name;
return function hello() {
console.log(message);
};
}
//generate closure
var helloWorld = hello("World");
//use closure
helloWorld();

3. What will the code below output to the console and why?
JavaScript

var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());
}
};
myObject.func();

Answer: The above code will output the following to the console:

JavaScript

outer func: this.foo = bar


outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar

In the outer function, both this and self refer to myObject and therefore both
can properly reference and access foo.
In the inner function, though, this no longer refers to myObject. As a result,
this.foo is undefined in the inner function, whereas the reference to the local
variable self remains in scope and is accessible there.

4. What is the significance, and what are the benefits, of including


'use strict' at the beginning of a JavaScript source file?
Answer The short and most important answer here is that use strict is a way
to voluntarily enforce stricter parsing and error handling on your JavaScript
code at runtime. Code errors that would otherwise have been ignored or
would have failed silently will now generate errors or throw exceptions. In
general, it is a good practice.
Some of the key benefits of strict mode include:
Makes debugging easier. Code errors that would otherwise have been
ignored or would have failed silently will now generate errors or throw
exceptions, alerting you sooner to problems in your code and directing you
more quickly to their source.
Prevents accidental globals. Without strict mode, assigning a value to an
undeclared variable automatically creates a global variable with that name.
This is one of the most common errors in JavaScript. In strict mode,
attempting to do so throws an error.
Eliminates this coercion. Without strict mode, a reference to a this value of
null or undefined is automatically coerced to the global. This can cause
many headfakes and pull-out-your-hair kind of bugs. In strict mode,
referencing a a this value of null or undefined throws an error.
Disallows duplicate parameter values. Strict mode throws an error when it
detects a duplicate named argument for a function (e.g., function foo(val1,
val2, val1){}), thereby catching what is almost certainly a bug in your code
that you might otherwise have wasted lots of time tracking down.
Note: It used to be (in ECMAScript 5) that strict mode would disallow
duplicate property names (e.g. var object = {foo: "bar", foo: "baz"};) but
as of ECMAScript 2015 this is no longer the case.
Makes eval() safer. There are some differences in the way eval() behaves in
strict mode and in non-strict mode. Most significantly, in strict mode,
variables and functions declared inside of an eval() statement are not
created in the containing scope (they are created in the containing scope in
non-strict mode, which can also be a common source of problems).
Throws error on invalid usage of delete. The delete operator (used to
remove properties from objects) cannot be used on non-configurable
properties of the object. Non-strict code will fail silently when an attempt is
made to delete a non-configurable property, whereas strict mode will throw
an error in such a case.
5. Consider the following code snippet:

JavaScript

for (var i = 0; i < 5; i++) {


var btn = document.createElement('button');
btn.appendChild(document.createTextNode('Button ' + i));
btn.addEventListener('click', function(){ console.log(i); });
document.body.appendChild(btn);
}

(a) What gets logged to the console when the user clicks on “Button 4” and
why?
(b) Provide one or more alternate implementations that will work as
expected.

Answer: (a) No matter what button the user clicks the number 5 will always be
logged to the console. This is because, at the point that the onclick method is
invoked (for any of the buttons), the for loop has already completed and the
variable i already has a value of 5. (Bonus points for the interviewee if they
know enough to talk about how execution contexts, variable objects,
activation objects, and the internal “scope” property contribute to the closure
behavior.)
(b) The key to making this work is to capture the value of i at each pass
through the for loop by passing it into a newly created function object. Here
are four possible ways to accomplish this:

JavaScript

for (var i = 0; i < 5; i++) {


var btn = document.createElement('button');
btn.appendChild(document.createTextNode('Button ' + i));
btn.addEventListener('click', (function(i) {
return function() { console.log(i); };
})(i));
document.body.appendChild(btn);
}
Alternatively, you could wrap the entire call to btn.addEventListener in the
new anonymous function:

JavaScript

for (var i = 0; i < 5; i++) {


var btn = document.createElement('button');
btn.appendChild(document.createTextNode('Button ' + i));
(function (i) {
btn.addEventListener('click', function() { console.log(i); });
})(i);
document.body.appendChild(btn);
}

Or, we could replace the for loop with a call to the array object’s native
forEach method:

JavaScript

['a', 'b', 'c', 'd', 'e'].forEach(function (value, i) {


var btn = document.createElement('button');
btn.appendChild(document.createTextNode('Button ' + i));
btn.addEventListener('click', function() { console.log(i); });
document.body.appendChild(btn);
});

Lastly, the simplest solution, if you’re in an ES6/ES2015 context, is to use let i


instead of var i:

JavaScript

for (let i = 0; i < 5; i++) {


var btn = document.createElement('button');
btn.appendChild(document.createTextNode('Button ' + i));
btn.addEventListener('click', function(){ console.log(i); });
document.body.appendChild(btn);
}
6. What are the different ways an HTML element can be accessed
in a JavaScript code?
Answer: Here are the ways an HTML element can be accessed in a
JavaScript code:
getElementByClass(‘classname’): Gets all the HTML elements that have
the specified classname.
getElementById(‘idname’): Gets an HTML element by its ID name.
getElementbyTagName(‘tagname’): Gets all the HTML elements that have
the specified tagname.
querySelector(): Takes CSS style selector and returns the first selected
HTML element.

7. What are the arrow functions in JavaScript?


Answer: Arrow functions are used to write functions with a short and concise
syntax. Also, it does not require a function keyword for declaration. An arrow
function can be omitted with curly braces { } when we have one line of code.
syntax of an arrow function:
const helloWorld = () => {
console.log("hello world!");
};
Example:
// Traditional Function Expression
var add = function(a,b)
{
return a+b
}
// Arrow Function Expression
var arrowAdd = (a,b) => a + b;

8. Explain Hoisting in javascript. (with examples)


Answer: Hoisting in javascript is the default process behavior of moving
declaration of all the variables and functions on top of the scope where scope
can be either local or global.
Example 1:
hoistedFunction(); // " Hi There! " is an output that is
declared as function even after it is called
function hoistedFunction(){
console.log(" Hi There! ");
}

Example 2:
hoistedVariable = 5;
console.log(hoistedVariable); // outputs 5 though the
variable is declared after it is initialized
var hoistedVariable;

9. How would you create a cookie and read a cookie?


Answer: The simplest way of creating a cookie using JavaScript is as below:
document.cookie = "key1 = value1; key2 = value2; expires = date";
Reading a cookie using JavaScript is also very simple. We can use the
document.cookie string that contains the cookies that we just created using
that string.
The document.cookie string keeps a list of name-value pairs separated by
semicolons, where ‘name’ is the name of the cookie, and ‘value’ is its value.
We can also use the split() method to break the cookie value into keys and
values.

10. Explain the working of timers in JavaScript?


Answer: Timers are used to execute a bit of code at a set time and repeat
the bit of code in a given interval.
Those working are done by using functions setTimeout, setInterval, clear
interval.
Working of Functions:
The setTimeout(function, delay) function is used to start a timer, which
calls a particular function after the, particularly mentioned delay.
The setInterval(function, delay) function is used to repeatedly execute the
given function in the said delay and only stops when it is cancelled.
The clearInterval(id) function instructs or indicates the timer to stop (for
stopping the given or mentioned function).
The whole timers are operated within a single thread, and for his events
might wait or queue up, they wait for their execution.

11. Explain briefly how you can submit a form using JavaScript?
Answer: In JavaScript, you can use an on click event for submitting a form,
i.e., form.submit() method.
You can perform a submit action by using submit button, By clicking on
Hyperlinks.
For submitting a form using JavaScript use document.form[0].submit();
For Example:

JavaScript

document.form[0].submit();

12. How should we change the style/class of an element?


Answer: First of all, we can use the className to assign a value directly to
the class. If any such classes are already present on the element, then this will
override them.
For getting the value of class on the element, we can add multiple spaces
using className.
Given the following way, we can change the class of an element:

JavaScript

document.getElementById("myText").style.fontSize = "20";

or,

JavaScript

document.getElementById ("myText").className = "any class";


13. List the disadvantages of using innerHTML in javascript.
Answer: The innerHTML property is a part of the DOM and is used to set or
return the HTML content of an element. The return value represents the text
content of the HTML element. It allows JavaScript code to make changes to a
website being rendered.
The disadvantages of using innerHTML are:
1. Appending to innerHTML is not supported without reparsing the whole
innerHTML.
2. As reparsing is required for innerHTML the processing is slow and takes
more time.
3. The event handlers do not attach automatically to the newly created
elements by setting innerHTML. One must keep track of the event
handler and attach the new element manually.
4. By using innerHTML if you add, append, delete or modify contents on a
webpage all contents are replaced, also all the DOM nodes inside that
element are reparsed and recreated.
5. No proper validation is provided by innerHTML, hence any valid HTML
code can be used. This may break the document of JavaScript.

14. What are the unescape() and escape() functions in javascript?


Answer: The escape() function in JavaScript is used for encoding (the
process of converting plaintext to ciphertext) a string.
Syntax:
1
escape(string to be encoded)
The unescape() function is used to decode(decrypt) that string encoded by
the escape() function.
Syntax:
1
unescape(string to be decoded)

15. Define the use of Void(0) in JavaScript?


Answer: The Void(0) is used to prevent/precautionary steps to prevent the
page from refreshing, and the passing parameter “zero” is passed
while/during calls.
After passing the parameter and calling, Void(0) is used to call another
method without refreshing the page.

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


Answer: The following code could be chosen to get desired output:

JavaScript

<script language="JavaScript" type="text/JavaScript" >


<!-- location.href="http://newhost/newpath/newfile.html";
//--></script>

17. What is the HTML DOM model?


Answer: Simply, we can say that an HTML DOM is nothing but a defining
standard for how to get, change, delete, add HTML elements.
The HTML DOM is a standard object model and programming interface for HTML.

18. What do you mean by blur function in JavaScript?


Answer: The blur event occurs when the element losses its focus or blurriness.
The primary use of the Blur function in a program is to removing focus from a
specified object.
Syntax:

In HTML:
1
<element onblur=”HTML”>
In JavaScript:
1
object.onblur= function(){JavaScript};

19. How can you convert the string of any base to integer in
JavaScript?
Answer: The parseInt() function is used to convert numbers between different
bases. It takes the string to be converted as its first parameter, and the
second parameter is the base of the given string.
For example-
1
parseInt("4F", 16)

20. What are the two sides of a JavaScript, and how would you
differentiate between them?
Answer: JavaScript has two sides, namely the server-side JavaScript and the
client-side JavaScript. A developer is called a full stack JavaScript developer if
he can develop both sides.
The Client side JavaScript refers to the part of the code that runs on the client
machine. The client-side JavaScript incorporates simple, predefined
programming language and objects that are necessary for successfully running
the codes in a browser. The client-side JavaScript is interpreted by the
browsers at runtime, and it is directly embedded into the HTML pages.
The Server side JavaScript refers to the part of the code that is run on the main
server that is providing the web pages. Deployment of the server-side
JavaScript is performed after complete compilation. Node.js – in simple words
– is server-side JavaScript. The developer can use Node.js to provide server-
side functionality to your JavaScript-based projects.

21. What are escape characters?


Answer: 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:
document. write "I m a "good" boy."
document. write "I m a \"good\" boy."
22. What a pop()method in JavaScript is?
Answer: The pop() method is similar to the shift() method, but the difference is
that the Shift method works at the array’s start. The pop() method takes the last
element off of the given array and returns it. The array on which it is called is
then altered.
Example:
var cloths = ["Shirt", "Pant", "TShirt"];
cloths.pop();
//Now cloth becomes Shirt,Pant
IAF's
Emerging
Become a Edtech Company
2023
Web Developer
in 6 months
Placement Assurance
Average Salary - INR 8 LPA
1 on 1 Mentorship & Career Guidance
Access to all Live Lectures
On-the-go Doubt Resolution

Get Started Now


Limited seats only!

For more details:


admissions@almabetter.com
080 - 46008400

You might also like