JavaScript Interview Questions for Freshers
JavaScript Interview Questions for Freshers
1. What is JavaScript?
JavaScript is a simple, interpreted programming language with object-oriented features that enables
you to add interactivity to HTML pages that would otherwise be static. The language's general-purpose
core has been integrated into Netscape, Internet Explorer, and other web browsers.
• Undefine
• Null
• Boolea
• String
• Symbol
• Number
• Object
Java JavaScript
Java creates applications that run on a browser or virtual Its code is run on a browser only.
machine.
Here the code needs to be compiled. Its code is all in the form of text.
• Interpreted Language- the browser executes Javascript code, and no compilation is needed.
• Cross Platform- means that Javascript is platform-independent and runs the same on all
platforms irrespective of the operating system.
• Object-Oriented Scripting Language- The programming style and technique are based upon
objects to represent data and code.
• Asynchronous Processing- Javascript has an async-await function and promises feature, which
makes it possible to do asynchronous programming.
5. What are the key differences between Java and Javascript?
The key difference between Java and Javascript is that Java is an object-oriented based programming
language, while Javascript is a scripting language that is based on the use of objects for data
manipulation and representation. The browser on the client side interprets Javascript code, while Java
code is executed on the server before its execution on the client side.
Superior Interaction: JavaScript makes other static web pages interactive and allows them to respond
to user input.
Quick Response: When JavaScript is used, a web page does not need to reload. Consider the validation
of form input.
Rich User Interface: Web apps' user interface (UI) can look and feel significantly better thanks to
JavaScript.
Frameworks: JavaScript includes many frameworks and libraries widely used to create various games
and web applications.
Yes, the language of JavaScript takes the case into account. Consistent letter capitalization is required
when typing the language's keywords, variables, function names, and other identifiers.
Using the object literal, you can create an object like seen below:
var emp = {
name: "John",
age: 19
};
var a = [ ];
Yes! A variable may be given an anonymous function. It may also be passed to another function as an
argument.
12. Differentiate between “ == “ and “ === “ operators.
Both operate on comparisons. The distinction between the two operators is that while "==" compares
values, " === compares both values and types.
var a = 7;
var b = "7";
(a === b) // Returns false since the typeof a is "number" and typeof b is "string"
The 'var' keyword has been used in JavaScript programming since the beginning, whereas the 'let'
keyword was just introduced in 2015.
"Var" is a keyword with function scope. The variable stated with the var keyword is available
throughout the function, while in "let," the scope of a variable declared with this keyword is restricted
to the block in which it is declared.
The area of your program where a variable is defined is its scope. There will only be two scopes for a
JavaScript variable.
Global Variables: A global variable is visible throughout your JavaScript code since it has a global scope.
Local Variables: Local variables are only accessible within the function in which they are defined. The
parameters of a function are always specific to that function.
15. List a few of the built-in methods along with the values they return.
indexOf() Returns the index in the calling String object of the first occurence of the specified value.
pop() It removes the last element from the array and returns that element.
Build-in Method Values
push() Adds one or more elements at the end of an array and returns that element.
• Any special word that is reserved by JavaScript are keywords and shouldn't be used as variable
names. Break or boolean variable names, for instance, are invalid.
• Variable names in JavaScript shouldn't begin with a number (0-9). They must either start with
a letter or an underscore. For instance, name123 or _123name are acceptable variable names,
whereas 123name is not.
• Case matters in JavaScript variable names. As an illustration, Test, and test are two distinct
variables.
To determine the data type of its operand, use the typeof operator. A literal or a data structure, such
as a variable, function, or object, can serve as the operand. Before its sole operand, which can be of
any type, it is a unary operator. Its value is a string that specifies the operand's data type.
Undeclared variables are not declared and don't exist in a program. A runtime error occurs if the
software tries to read the value of an undefined variable.
Variables declared in the program but do not have a value are considered undefined variables. An
undefined value is returned if the software tries to read the value of an undefined variable.
When working with special characters like ampersands (&), apostrophes ('), double quotes (" "), and
single quotes (' '), JavaScript uses escape characters, often backslash (\ \). JavaScript displays any
characters that are contained within the escape.
• \n – Newline
• \r – Carriage return
• \t – Horizontal tabulator
• \v – Vertical tabulator
• \b – Backspace
• \f – Form feed
20. Define prompt box.
A prompt box is a box that offers a text box for the user to enter information. There will be a label and
box where the text or number can be entered.
Slice Splice
Returns the subset of the original array. Its returns the deleted elements as an array.
It is used to pick the element from the array. It is used to insert or delete elements from an array.
The creation of an error object is the responsibility of the Error constructor. Runtime errors result in
instances of the error objects being thrown. Additionally, user-defined exceptions can use the Error
object as their base object.
JS supports seven error constructors along with the generic error constructor-
• EvalError – Produces an instance of an error relating to the global function eval ().
• RangeError- A numeric variable or parameter that is outside of its valid range will result in a
RangeError instance being created.
• SyntaxError- When parsing code in eval, it creates an instance of an error relating to a syntax
error ().
• TypeError- Creates a TypeError instance when a parameter or variable's type isn't valid.
• URLError- When invalid parameters are supplied to the decode URI() or encodeURI
functions, an error instance is created.
By pressing the appropriate key, typically the F12 key, all contemporary web browsers, including
Chrome, Firefox, and others, feature an integrated debugger that can be used anytime. The debugging
tools provide users with a number of functions.
The code editor we use to create JavaScript applications, such as Visual Studio Code, Atom, Sublime
Text, etc., also allows us to debug JavaScript code.
24. Differentiate between Windows & documents in JavaScript?
Windows Document
The window of Javascript is a global object which holds This also comes under the window and can be
variables, functions, locations, and history. understood as the property of the window.
It is the representation of the user’s browser window and It is the representation of any HTML document that is
represents the content of the webpage. loaded on the browser
Global objects, functions, and variables of JavaScript are The HTML tags, elements, and their attributes are
part of the window object. members of the Document.
JavaScript functions are written using arrow functions, which are clear and concise. An arrow function's
general syntax is as follows:
};
The development of online applications involves a variety of frameworks, many of which are available
for JavaScript. Several well-known frameworks include:
In the HTML DOM API, there are 2 approaches for handling event propagation and the sequence in
which events are received. Event Bubbling and Event Capturing are these. In the former, the event is
aimed at its intended target; in the latter, it is directed toward a different element.
Event capturing: Also referred to as trickling, it is hardly used. The event is initially captured by the
outermost element, which then propagates it to the innermost element.
Event Bubbling: This method involves handling the event in the innermost element before propagating
it to the outermost element.
x.length = 0;
x = [];
x.pop();
x.splice(0, x.length);
return 13;
};
typeof Fun();
Given that a function definition can only have one name for a reference variable, the result would be
a reference error.
• Filter method:
Three arguments are specified to call the filter() function. These are the array, element in use, and
element index.
• For loop:
/* Multi
Line
Comment
*/
A variable can be given a number by using variable type. A string can be given the same variable.
i = 13;
i = "coding ninjas";
When a user accesses a website to store information they need, small test files called cookies are
created and kept in the user's computer. Examples include user name specifics and previous visit
shopping cart data.
35. Give the disadvantages of using innerHTML in Javascript.
• The old content gets replaced with html even if you use += like "innerHTML = innerHTML +
'html' ".
• The full innerHTML document is parsed again and broken down into components. It is
therefore slower.
• Since the innerHTML does not validate, we may introduce legitimate but flawed HTML and
cause the document to malfunction.
External JavaScript is JavaScript code (script) created in a different file with the extension.js. This file is
linked inside the <head> or body> element of the HTML file, depending on where the code is to be
inserted. External Javascript has some benefits, including
• It makes it possible for web developers and designers to work together on HTML and javascript
files.
• The code is reusable.
• In external javascript, code readability is simple.\
Events are the outcomes of activities, like the user clicking a link or completing a form. An event
handler is needed to ensure that each of these events is carried out correctly. Event handlers are an
additional object attribute. The name of the event and the course of action if the event occurs are
included in it.
The var keyword is used to declare. The scope of this keyword is “function-scope,” which means that
if a variable is declared using the var keyword, it could be accessed anywhere in the entire function or
a program.
The ‘let ‘variable is also used to declare a new variable, but its scope is limited to a block, which means
variables declared using the let keywords have block scope.
The following examples take variables from the loop and display the result accordingly.
for (var a = 0; a < 5; a++) {
console.log(a);
console.log(a);
Output :
As the loop ended, we could still access the variable, and hence we can see 5 as the output in this
scenario.
console.log(a);
console.log(a);
Output :
file.js:4
console.log(a);
at Object.<anonymous> (HelloWorld.js:4:13)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11
The above code will result in an error saying that the variable was not defined, as the variable’s scope
was just in the loop. While we were trying to access it after the loop ended, the variable had to be
defined again.
The declarations of variables or functions are by default moved at the top of the entire code, making
sure they are accessible everywhere in the program. The assignment of the variables happens only
when they are declared. This property is known as Hoisting.
For example –
The first important step is to declare a variable using let/var. The second is to initialize it or assign any
value to the variable, and the last is the final step to use the variable.
console.log(a);
var a = 5;
As the declaration and assignment are made after using the variable, we would get an Output as
undefined.
Output :
undefined
But if we would have had the variable declared and assigned first,
var a = 5;
console.log(a);
Output :
We would get five as the Output because we made the declaration before using the variable.
41. What is the key difference between “==” and “===” in Javascript?
== (Equality Operator)
It converts the variable value to the same type before performing the comparison.
It follows type coercion.
It is less preferred than the Identical operator as it might give us unexpected results at times.
For example: “1” == true or “0” == false will give you true as the final answer.
console.log(123==123);
console.log(123===123);
Output :
true
true
In the above example, both operators were true as the final Output as it involved no type conversion.
Hence, a simple equality condition has been checked for both of the cases. But let’s see if we try to
compare a string value and an integer value now,
console.log(123=="123");
console.log(123==="123");
Output :
true
false
The above example shows that the double equals do not consider the change in data type and simply
compare the variable’s value. In contrast, the triple equals compare the deals of the same data type.
The double equals perform a type conversion and then compare the values.
In Javascript, NaN stands for Not a Number. This property is used to check if the entered value is a valid
number or not. NaN value gets generated when the value cannot be computed, or type conversion of
the non-numeric value to the number is not a valid numeric.
For example, when we try to divide a 0 by 0. For any arithmetic operation in which one of the values
is undefined Javascript returns NaN.
console.log(cn);
Output :
NaN
Javascript treats NaN like an actual number, which can be used to perform any number type
operations.
Asynchronous programming allows it to express waiting for long-running actions without freezing the
program during these actions. JavaScript environments typically implement this programming style
using callbacks, which are called when the actions are complete.
An event loop schedules such callbacks to be called when appropriate, one after the other, so their
execution does not overlap.
Arrays
Strings
Maps
Sets
In Javascript,
So the final output will be the concatenation of both of these numbers leading the answer to be 73.
Yes, Javascript is a case-sensitive language. This means that the keywords,function-name, variable
name all should be typed with a consistent capitalization of letters. The word let and LET will have
different meanings in JS.So while using any variable or keyword, we should keep the case of the letters
in mind.
ans.length = 0;
const applies only to the keywords and does not allow re-assigning a value to a const variable.
Const variables cannot be redeclared or reassigned. The scope of a const variable is limited to block-
scope. This means we cannot use a const variable declared in a block outside it.
For example :
const Pi = 3.14;
console.log(Pi);
// outside block
console.log(Pi); // error
Output :
3.14
Object.freeze() : It is applied to the objects in Javascript. It freezes the objects, which does not allow
any new properties to be rendered in them. It also prevents any modifications to the existing
properties, attributes and values.
For example :
let ans ={
Pi = 3.14
};
Object.freeze(ans);
ans.Pi = 3.145;
Output :
3.14
A promise is an object which represents the eventual completion of either completion or failure of an
asynchronous function.
There are three states of the Promise object :
• Pending: which is the initial state (before the promise succeeds or fails
• Resolved: When a promise is successfully completed
• Rejected: When a promise is rejected(failed)
});
Currying is a process in functional programming in which we can transform a function with multiple
arguments into a sequence of nesting functions. It returns a new function that expects the next
argument inline. It helps to avoid passing the same variable again and again, also in creating high order
functions.
function addcn(a, b, c) {
return a + b + c;
return a + b + c
console.log(res);
console.log(res2);
console.log(res3);
Output :
Document Object Module (DOM) is not a part of Javascript, but it is a web API used to build websites.
Using DOM, developers can create documents, navigate through them and modify, add accordingly to
the document.
Event delegation allows us to attach a single event listener to a parent element, which will work for all
descendants matching a selector, whether those descendants exist now or are added in the future.
There are various methods to do so. Let’s discuss each one of them.
Method 1:
The above method assigns a new array to the variable a, deleting its previous values.
Method 2:
We are aware of the JS array.length function, this function deletes the values of the array within a
defined value.
a.length = 0;
Method 3:
We can use a pop() method to delete all the elements of the array till the array.length is true.
while(a.length)
a.pop()
Method 4:
The splice method in array.splice(cuts) the array from a defined initial value till the final value.
a.splice(0,a.length);
Cookies are data stored on your system and were invented so that the browser can remember a few
details about the user.
We can not only create but read, delete cookies using this document. cookie property.
• Angular
• React
• Vue.Js
• ember.Js
• Meteor
It is a stricter or secured version of ordinary javascript language that produces errors for those mistakes
handled silently otherwise. It was introduced in ECMAScript 5.
For example :
a=10;
console.log(a);
We will not get an error as the compiler would by default consider ‘a’ as a ‘var’ data type.
But if we use strict Js, we would get an error if we try to run the above code stating a is not defined.
57. What is the difference between a null, undefined, and undeclared variable in Javascript?
A variable is said to be undeclared when it is not assigned any data type. When a variable is not even
declared and used, the compiler will give us an error stating that the variable is not defined.
For example:
var b;
Output:
null
undefined
HelloWorld.js:5
at Object.<anonymous> (HelloWorld.js:5:13)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11
1) The slice() method copies a given part of the array and returns it. It does not modify the original
array.
array.slice(inital,final)
2) Array.splice method is used to remove the items of the selected array and does not form another
array. This method modifies the original array. Array.splice can be used to add or remove elements
from the array.
delete courses[2];
console.log(courses.length);
The delete function does not affect the array’s length as the operator deletes only the value present
at the given position.
We will have an empty value in the ‘C’ course in the array courses.
Immediately Invoked Function Expressions are also called Self Executing Anonymous Functions,
executed immediately after their definition.
The first is the anonymous function in the given scope enclosed within ‘()’
The second part is the immediately invoked function expression through which the Js interpreter will
directly interpret the function.
ArrayBuffers is a data type used to store a generic, fixed-length binary data buffer. We cannot directly
modify the contents of an ArrayBuffer, but we can create a typed view or a DataView, that is used to
read or write the contents of the buffer.
Callback hell is also known as the Pyramid of Doom. It is an anti-pattern of multiple nested callbacks,
making it difficult to read or debug the code. It is a slang term used to define multiply nested if
statements or functions.
async1(function() {
async2(function() {
async3(function() {
async4(function() {
....
});
});
});
});
The window is the first thing that gets loaded into the browser. This window object has most properties
like length, innerWidth, innerHeight, name if it has been closed, its parents, and more. The window
object refers to the browser window.
The document object is your HTML, ASPX, PHP, or another document that will load into the browser.
The document gets loaded inside the window object and has properties like title, URL, cookie, etc.
Arrow Functions are a new concept of ES, as they allow us to create smaller and cleaner functions.
For example :
let a = function(a,b){
return a +b ;
In a WeakMap, the keys are objects instead of primitive values. It is known as a directory where all the
keys are weak. Weak maps provide a way to extend objects without interfering with garbage collection.
Due to security reasons, every web browser provides an option to disable javascript.
It is not engine-friendly.