A list of top frequently asked Javascript interview questions and answers are given below.
JavaScript is a client-side as well as server side scripting language that can be inserted into HTML pages and is understood by web browsers.
Javascript is an object-oriented computer programming language commonly used to create interactive effects within web browsers.It is first used by the Netscape browser, that provides access to the HTML document object model (DOM), provides access to the browser object model (BOM). Javascript syntax looks a lot like java, c or c++ syntax.
A variable in JavaScript can contain any data. A variable can at one moment be a string and later receive a numeric value
Programming languages that allow such things are called “dynamically typed”, meaning that there are data types, but variables are not bound to any of them.
There are seven basic data types in JavaScript. Here we’ll study the basics, and in the next chapters we’ll talk about each of them in detail.
Java is a high-level programming language currently being owned by Oracle. JavaScript is an interpreted language maintained by Mozilla and its trademark is owned by oracle. Both Java and JavaScript refer to the same language OOP (Object-Oriented Programming), they use same control structures, operators etc; and comments of JavaScript are same as Java. Despite these similarities they differ in various aspects. A few of them are listed below)
JAVA | JAVASCRIPT |
---|---|
Java is a programming language that intends to remove those language features that lead to programming errors. | JavaScript is a script language that helps the site authors to develop attractive sites with good content by interacting with HTML source code. |
It makes the language suitable for use on the web with its different features such as generics, I/O, Serialization etc. | It creates interactive effects within the web such as ‘linked-to-page’ appearing in the pop up window |
It has a class-based model (class orientation) where classes of objects are defined to achieve inheritance. | It has a prototype based model where inheritance might vary for single objects. |
Java must be converted into machine language before it is run on the web to make alterations if any. | JavaScript is written to a HTML document and is run through a browser and then alterations are made. |
This programming language is popularly being used for client-server web applications. | This script language is popularly being used for building server-side software, desktop-like web applications etc. |
Java can be installed through executable program file such as IFTW(Install From The Web) | This script language is popularly being used for building server-side software, desktop-like web applications etc. |
This program is executed in 5 steps) Edit- Compile- Load- Verify- Execute. | The execution context in this program includes 2stages) Creation and Activation stage. |
It can be disabled in chrome by finding Java in the program list and uninstalling it. It can also be disabled through Java Control Panel. | It can be disabled simply by following different instructions for various browsers such as Opera, Internet Explorer etc. |
Java program uses more memory (computer) to function properly. | This requires less memory and is therefore used in many web pages. |
JavaScript is faster. JavaScript is a client-side language and thus it does not need the assistance of the web server to execute.
ASP is a server-side language and hence is always slower than JavaScript. Javascript now is also a server side language (nodejs).
Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.
Breaking within a string statement can be done by the use of a backslash, '\', at the end of the first line
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.
var x=1, y=2,
z=
x+y;
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.
<html> <head> <title>t1</title> <script type="text/javascript"> function addNode() {{"{"}} var newP = document.createElement("p"); var textNode = document.createTextNode(" This is a new text node"); newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); {{"}"}} </script> </head> <body> <p id="firstP">firstP<p> </body> </html>
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.
// 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.
The keyword ‘this’ refers to the current instance of the object when used inside a function. But, when used outside a function, it refers to the window object.
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.
// For single line comments and
/* For multiple line comments /* Code comments
multipleline */
'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.
ECMAScript (European Computer Manufacturers Association) Script is a specification for the scripting language standards. It has standardized Javascript which made Javascript the best implementation of ECMAScript.
No. Attributes are something that can give more details on an element like id, type, value etc. Whereas, Property is the value assigned to the property like type="text", value='Name' etc.
HTML element can be accessed in a Javascript code,
(i) getElementById('idname'): Gets an element by its ID name
(ii) getElementsByClass('classname'): Gets all the elements that have the given classname.
(iii) getElementsByTagName('tagname'): Gets all the elements that have the given tag name.
(iv) querySelector(): This function takes css style selector (like #id/.classname/tagname) and returns the first selected element.
(v) querySelectorAll(): Similar to querySelector, this function returns a NodeList of html elements.
The Javascript code can be involved in 3 ways
There are three possible ways of defining a variable in Javascript
let and const is the latest variable and are introduced in ES-2015(ES6 version).
Let and const have a block scope but var has function scope.
Typed Language is in which the values are associated with values and not with variables. It is of two types:
Dynamically: in this, the variable can hold multiple types; like in JS a variable can take number, chars.
Statically: in this, the variable can hold only one type, like in Java a variable declared of string can take only set of characters and nothing else.
The operator typeof gives the type of a variable/data available in it. The typeof operator can be used on Reference data types also.
Type Conversion is to convert from one data type to another data type.
(i) Number to String Conversion.
toString: Other data type to String.
val = (5).toString(); converts integer to string.
val = (true).toString(); converts boolean to string.
Convert from Number/Boolean/Date to String.
Number to String: String(9) converts num to string
Boolean to String: String(true) converts bool to str
Date to String: String(new Date()) date to string
Array to String: String([2,2,2]) Array to string.
(ii) String to Number Conversion.
parseInt: String to Int only (no decimals)
val = parseInt('11'); outputs 100 as number
val = parseFloat('22.22') outputs 22.22 as float
Convert from String/Boolean to Number/Date.
String to Number: Number('9') converts str - num
(9).toFixed(4) gives 9.0000 as the output
Boolean to Number: Number(true) converts to no.
Null to Number: Number(null) converts to no. (0)
Chars to Number: Number('ss') give NaN.
Local Storage will stay until it is manually cleared through settings or program.
Session Storage will leave when the browser is closed.
The keyword var is from the beginning of Javascript; whereas, let is introduced in ES2015/ES6. The keyword let has a block scope; whereas, the keyword var has a functional scope.
The operator '==' compares the value; whereas, the operator '===' compares both value and type.
Operator '=='
Operator '==='
When used the typeof operator on null; i.e., typeof(null), the value is an object. Whereas, when used the typeof operator on undefined; i.e., typeof(undefined), the value would be undefined.
No, Javascript was provided by Netscape; whereas, JScript was provided by Microsoft.
Typescript is not the next version of Javascript but is developed by Microsoft and can be taken as a superset to Javascript; the code written in Typescript is later compiled into Javascript. Typescript adds new features like Interfaces, Generics, etc.
There are many Javascript Frameworks available today, but the most commonly used frameworks are:
The operator typeof is an example of Unary Operators, which is used by placing it before its operand; which can be of any type.
An anonymous function allows a developer to create a function that has no name. In other words, anonymous functions can be used to store a bit of functionality in a variable and pass that piece of functionality around.
Anonymous functions exist only after they are called; whereas, Named functions to exist even if not called.
These functions are executed right after its definition. Also called as Immediately Invoked
Function Expressions (IIFE's). Syntax: (function(){{"{"}} console.log('in iffe'); {{"}"}})()
The callback function is a mechanism to send one function to another function as an argument; i.e., passing func as an argument to another function.
The calling of recursion is possible in two functions, but the call comes to an end after some time.
The inner functions can be called as closure when it has access to the outer function's variables.
The synchronous code is something that should be finished before anything else can happen, or in other words, the synchronous code is blocking. And the Asynchronous code is something in which actions can happen and is not dependent on other actions- in other words, it is non-blocking.
There are three types of pop up boxes
With the latest version of Javascript, exception handling is possible; and this can be achieved using the following keywords try, catch and finally.
The arguments.length property helps in getting the total number of arguments that are passed to a function.
The typeof operator returns a string of what type the operand is. Whereas, the instanceof operator does not work with primitive data types; but works with objects and checks on what type the object is.
DOM (Document Object Model) is an object-oriented representation of the HTML elements. All the elements (or nodes) are part of window.document.
BOM stands for Browser Object Model. Using BOM interaction with a browser is possible. Default object of the browser is a window.
Javascript window is a global object which holds variables, functions, history, location; the document also comes under the window and can be considered as the property of the window.
innerHTML will process an HTML tag if found in a string,
whereas innerText will not. For Example document.querySelector('p').innerHTML='one
two' gives the output one and two in two lines as
in html is a new line. Whereas document.querySelector('p').innerText='one
two' gives the output of the text as it is in one line.
Let us have a paragraph element and a span element in it as a child element.
Let us have a paragraph element and a span element in it as a child element.
<p>some text and a <span style="visibility: hidden">span tag hidden <\span>in it</p>
Now, if the following two steps would result in the following-
console.log(document.querySelector('p').textContent); gives some text and a span tag hidden in it.
console.log(document.querySelector('p').innerText); gives some text and a in it.
The functions querySelectorAll() returns NodeList in which the forEach can be used directly to traverse the elements. Whereas, the getElementsByClassName() or getElementsByTagName() returns an HTMLCollection, which does not have a forEach by default.
he HTMLCollection by default does not have forEach, it needs to be converted into an array (eleName = Array.from(eleName)) and then the traversal is possible using forEach.
A childNode, when used returns a NodeList. Whereas, children, when used; returns an HTMLCollection.
A firstChild when used returns the first node. It could be an HTML element or even a space, or a new line. Whereas, firstElementChild, when used returns the first HTML element only.
To generate an html element dynamically, we need to use two functions:
The remove() function just removes the element. Whereas, the removeChild() returns the deleted element.
There are altogether 9 mouse events -
1. click: A single click
2. dblclick: A double click
3. mousedown: When the mouse button is clicked down.
4. mouseup: When the mouse button is released up.
5. mouseenter: When the mouse cursor enters an external element.
6. mouseleave: When the mouse cursor leaves an external element
7. mouseover: When the mouse cursor enters an internal and external element.
8. mouseout: When the mouse cursor leaves an internal and external element.
9. mousemove: When the mouse cursor is moved.
By using the history object you can change or switch back to history pages or forward from current page to another page.
When an event is fired on an HTML element, the execution starts from that event and goes to its parent element. From there, the execution passes to its parent element and so on till the body element.
The print() function from window object prints the current web page when executed.
The window.location is assigned a value; i.e., a web link. On its execution, the Javascript code can redirect the user to the mentioned web link.
A Cookie is a variable that is stored on a client's/visitors machine. Using Cookies, the servers can identify the client and the client's transactions.
Primitive types in Javascript are passed by value; whereas, object types are passed by reference.
NaN is a short form of Not a Number. When a string or something else is being converted into a number and that cannot be done, then we get to see NaN. A strange thing about NaN is that it is not equal to anything including itself.
There are list of tokens that falsify in JS and they are
A partial invocation of a Javascript function is called Currying. Few arguments of a function are processed and a function is returned. Few more arguments are added by the returning function.
The JSON.stringify() method is used to convert a Javascript data to a string.
Just like push() which inserts elements into an array at the end of it, the unshift() function inserts elements at the beginning of an array.
document.getElementById("myText").style.fontSize = "20?;
or
document.getElementById("myText").className = "anyclass";
EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is used to convert the encoded URL back to normal.
<script> var uri="my test.asp?name=ståle&car=saab"; document.write(encodeURI(uri)+ "<br>"); document.write(decodeURI(uri)); </script>
The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed.
onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.
Closure is a locally declared variable related to a function which stays in memory when the function has returned.
function greet(message) {{"{"}} console.log(message); {{"}"}} function greeter(name, age) {{"{"}} return name + " says howdy!! He is " + age + " years old"; {{"}"}} // Generate the message var message = greeter("James", 23); // Pass it explicitly to greet greet(message); This function can be better represented by using closures function greeter(name, age) {{"{"}} var message = name + " says howdy!! He is " + age + " years old"; return function greet() {{"{"}} console.log(message); {{"}"}}; {{"}"}} // Generate the closure var JamesGreeter = greeter("James", 23); // Use the closure JamesGreeter();
A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration.
var anon = function() {{"{"}} alert('I am anonymous'); }; anon();