JavaScript Intview Experiance
JavaScript Intview Experiance
Java JavaScript
Java is an OOP programming language. JavaScript is an OOP scripting language.
It creates applications that run in a virtual machine or browser. The code is
run on a browser only.
Java code needs to be compiled. JavaScript code are all in the form of text.
Q2. What is JavaScript?
JavaScript is a lightweight, interpreted programming language with object-oriented
capabilities that allows you to build interactivity into otherwise static HTML
pages. The general-purpose core of the language has been embedded in Netscape,
Internet Explorer, and other web browsers.
Undefined
Null
Boolean
String
Symbol
Number
Object
Data types - JavaScript interview questions
Course Curriculum
Java Certification Training Course
Instructor-led SessionsReal-life Case StudiesAssignmentsLifetime Access
Q6. What are the advantages of JavaScript?
JavaScript advantages - JavaScript interview questionsFollowing are the advantages
of using JavaScript −
Less server interaction − You can validate user input before sending the page off
to the server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don’t have to wait for a page reload to
see if they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
Q7. How can you create an object in JavaScript?
JavaScript supports Object concept very well. You can create an object using the
object literal as follows −
var emp = {
name: "Daniel",
age: 23
};
Q8. How can you create an Array in JavaScript?
You can define arrays using the array literal as follows-
var x = [];
var y = [1, 2, 3, 4, 5];
Q9. What is a name function in JavaScript & how to define it?
A named function declares a name as soon as it is defined. It can be defined using
function keyword as :
function named(){
// write code here
}
Q10. Can you assign an anonymous function to a variable and pass it as an argument
to another function?
Yes! An anonymous function can be assigned to a variable. It can also be passed as
an argument to another function.
In case you are facing any challenges with these JavaScript Interview Questions,
please comment on your problems in the section below.
Q11. What is argument objects in JavaScript & how to get the type of arguments
passed to a function?
JavaScript variable arguments represents the arguments that are passed to a
function. Using type of operator, we can get the type of arguments passed to a
function. For example −
function func(x){
console.log(typeof x, arguments.length);
}
func(); //==> "undefined", 0
func(7); //==> "number", 1
func("1", "2", "3"); //==> "string", 3
Q12. What are the scopes of a variable in JavaScript?
The scope of a variable is the region of your program in which it is defined.
JavaScript variable will have only two scopes.
• Global Variables − A global variable has global scope which means it is visible
everywhere in your JavaScript code.
• Local Variables − A local variable will be visible only within a function where
it is defined. Function parameters are always local to that function.
CallBack - Edureka
Q15. What is Closure? Give an example.
Closures are created whenever a variable that is defined outside the current scope
is accessed from within some inner scope. It gives you access to an outer
function’s scope from an inner function. In JavaScript, closures are created every
time a function is created. To use a closure, simply define a function inside
another function and expose it.
Q16. Name some of the built-in methods and the values returned by them.
Built-in Method Values
CharAt() It returns the character at the specified index.
Concat() It joins two or more strings.
forEach() It calls a function for each element in the array.
indexOf() It returns the index within the calling String object of the first
occurrence of the specified value.
length() It returns the length of the string.
pop() It removes the last element from an array and returns that element.
push() It adds one or more elements to the end of an array and returns the new
length of the array.
reverse() It reverses the order of the elements of an array.
In case you are facing any challenges with these JavaScript Interview Questions,
please comment on your problems in the section below.
You should not use any of the JavaScript reserved keyword as variable name. For
example, break or boolean variable names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must begin
with a letter or the underscore character. For example, 123name is an invalid
variable name but _123name or name123 is a valid one.
JavaScript variable names are case sensitive. For example, Test and test are two
different variables.
Q18. How does Type Of Operator work?
The type of operator is used to get the data type of its operand. The operand can
be either a literal or a data structure such as a variable, a function, or an
object. It is a unary operator that is placed before its single operand, which can
be of any type. Its value is a string indicating the data type of the operand.
Syntax :
1
document.cookie = "key1 = value1; key2 = value2; expires = date";
Q20. How to read a cookie using JavaScript?
Reading a cookie is just as simple as writing one, because the value of the
document.cookie object is the cookie. So you can use this string whenever you want
to access the cookie.
The document.cookie string will keep a list of name = value pairs separated by
semicolons, where name is the name of a cookie and value is its string value.
You can use strings’ split() function to break the string into key and values.
Course Curriculum
Java Certification Training Course
Weekday / Weekend Batches
Q21. How to delete a cookie using JavaScript?
If you want to delete a cookie so that subsequent attempts to read the cookie in
JavaScript return nothing, you just need to set the expiration date to a time in
the past. You should define the cookie path to ensure that you delete the right
cookie. Some browsers will not let you delete a cookie if you don’t specify the
path.
Want to upskill yourself to get ahead in your career? Check out this video
Q23. List out the different ways an HTML element can be accessed in a JavaScript
code.
Here are the list of ways an 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 and returns the first
selected element.
Q24. In how many ways a JavaScript code can be involved in an HTML file?
There are 3 different ways in which a JavaScript code can be involved in an HTML
file:
Inline
Internal
External
An inline function is a JavaScript function, which is assigned to a variable
created at runtime. You can differentiate between Inline Functions and Anonymous
since an inline function is assigned to a variable and can be easily reused. When
you need a JavaScript for a function, you can either have the script integrated in
the page you are working on, or you can have it placed in a separate file that you
call, when needed. This is the difference between an internal script and an
external script.
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.
Q27. What is the difference between Local storage & Session storage?
Storage - Edureka
Local Storage – The data is not sent back to the server for every HTTP request
(HTML, images, JavaScript, CSS, etc) – reducing the amount of traffic between
client and server. It will stay until it is manually cleared through settings or
program.
Session Storage – It is similar to local storage; the only difference is while data
stored in local storage has no expiration time, data stored in session storage gets
cleared when the page session ends. Session Storage will leave when the browser is
closed.
In case you are facing any challenges with these JavaScript Interview Questions,
please comment on your problems in the section below.
Q28. What is the difference between the operators ‘==‘ & ‘===‘?
The main difference between “==” and “===” operator is that formerly compares
variable by making type correction e.g. if you compare a number with a string with
numeric literal, == allows that, but === doesn’t allow that, because it not only
checks the value but also type of two variable, if two variables are not of the
same type “===” return false, while “==” return true.
Angular
React
Vue
Q32. What is the difference between window & document in JavaScript?
Window Document
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.
Q33. What is the difference between innerHTML & innerText?
innerHTML – It will process an HTML tag if found in a string
In case you are facing any challenges with these JavaScript Interview Questions,
please comment on your problems in the section below.
By Value means creating a COPY of the original. Picture it like twins: they are
born exactly the same, but the first twin doesn’t lose a leg when the second twin
loses his in the war.
By Reference means creating an ALIAS to the original. When your Mom calls you
“Pumpkin Pie” although your name is Margaret, this doesn’t suddenly give birth to a
clone of yourself: you are still one, but you can be called by these two very
different names.
Q37. How can you convert the string of any base to integer in JavaScript?
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)
Q38. What would be the result of 2+5+”3″?
Since 2 and 5 are integers, they will be added numerically. And since 3 is a
string, its concatenation will be done. So the result would be 73. The ” ” makes
all the difference here and represents 3 as a string and not a number.
When you use strict mode, you cannot use implicitly declared variables, or assign a
value to a read-only property, or add a property to an object that is not
extensible.
You can enable strict mode by adding “use strict” at the beginning of a file, a
program, or a function.
Q41. What is a prompt box in JavaScript?
A prompt box is a box which allows the user to enter input by providing a text box.
The prompt() method displays a dialog box that prompts the visitor for input. A
prompt box is often used if you want the user to input a value before entering a
page. When a prompt box pops up, the user will have to click either “OK” or
“Cancel” to proceed after entering an input value.
var Y = 1;
if (function F(){})
{
y += Typeof F;</span>
}
console.log(y);
The output would be 1undefined. The if condition statement evaluates using eval, so
eval(function f(){}) returns function f(){} (which is true). Therefore, inside the
if statement, executing typeof f returns undefined because the if statement code
executes at run time, and the statement inside the if condition is evaluated during
run time.
Syntax-
Syntax-
fun.apply(thisArg, [argsArray])
Q44. How to empty an Array in JavaScript?
There are a number of methods you can use to empty an array:
Method 1 –
arrayList = []
Above code will set the variable arrayList to a new empty array. This is
recommended if you don’t have references to the original array arrayList anywhere
else, because it will actually create a new, empty array. You should be careful
with this method of emptying the array, because if you have referenced this array
from another variable, then the original reference array will remain unchanged.
Method 2 –
arrayList.length = 0;
The code above will clear the existing array by setting its length to 0. This way
of emptying the array also updates all the reference variables that point to the
original array. Therefore, this method is useful when you want to update all
reference variables pointing to arrayList.
Method 3 –
arrayList.splice(0, arrayList.length);
The implementation above will also work perfectly. This way of emptying the array
will also update all the references to the original array.
Method 4 –
while(arrayList.length)
{
arrayList.pop();
}
The implementation above can also empty arrays, but it is usually not recommended
to use this method often.
In case you are facing any challenges with these JavaScript Interview Questions,
please comment on your problems in the section below.
var Employee =
{
company: 'xyz'
}
var Emp1 = Object.create(employee);
delete Emp1.company Console.log(emp1.company);
The output would be xyz. Here, emp1 object has company as its prototype property.
The delete operator doesn’t delete prototype property. emp1 object doesn’t have
company as its own property. However, we can delete the company property directly
from the Employee object using delete Employee.company.
Q49. What is the reason for wrapping the entire content of a JavaScript source file
in a function book?
This is an increasingly common practice, employed by many popular JavaScript
libraries. This technique creates a closure around the entire contents of the file
which, perhaps most importantly, creates a private namespace and thereby helps
avoid potential name clashes between different JavaScript modules and libraries.
Another feature of this technique is to allow for an easy alias for a global
variable. This is often used in jQuery plugins.
For example-
1. Primitive types
Example :
var a = 2;
var b = 3;
var c = 2;
(a == b) // returns false
(a == c) //returns true
Undefined - When a variable is declared but not assigned, it has the value of
undefined and it’s type is also undefined.
Example :
var z = null;
Symbol - It is a new data type introduced in the ES6 version of javascript. It is
used to store an anonymous and unique value.
Example :
Primitive data types can store only a single value. To store multiple and complex
values, non-primitive data types are used.
Object - Used to store collection of data.
Example:
// Collection of data in key-value pairs
var obj1 = {
x: 43,
y: "Hello world!",
z: function(){
return this.x;
}
}
This means that irrespective of where the variables and functions are declared,
they are moved on top of the scope. The scope can be both local and global.
Example 1:
hoistedVariable = 3;
console.log(hoistedVariable); // outputs 3 even when the variable is declared after
it is initialized
var hoistedVariable;
Example 2:
hoistedFunction(); // Outputs " Hello world! " even when the function is declared
after calling
function hoistedFunction(){
console.log(" Hello world! ");
}
Example 3:
Note - Variable initializations are not hoisted, only variable declarations are
hoisted:
var x;
console.log(x); // Outputs "undefined" since the initialization of "x" is not
hoisted
x = 23;
Note - To avoid hoisting, you can run javascript in strict mode by using “use
strict” on top of the code:
"use strict";
x = 23; // Gives an error since 'x' is not declared
var x;
3. Why do we use the word “debugger” in javascript?
The debugger for the browser must be activated in order to debug the code. Built-in
debuggers may be switched on and off, requiring the user to report faults. The
remaining section of the code should stop execution before moving on to the next
line while debugging.
Download PDF
Example:
var x = 2;
var y = "2";
(x == y) // Returns true since the value of both x and y is the same
(x === y) // Returns false since the typeof x is "number" and typeof y is "string"
5. Difference between var and let keyword in javascript.
Some differences are
From the very beginning, the 'var' keyword was used in JavaScript programming
whereas the keyword 'let' was just added in 2015.
The keyword 'Var' has a function scope. Anywhere in the function, the variable
specified using var is accessible but in ‘let’ the scope of a variable declared
with the 'let' keyword is limited to the block in which it is declared. Let's start
with a Block Scope.
In ECMAScript 2015, let and const are hoisted but not initialized. Referencing the
variable in the block before the variable declaration results in a ReferenceError
because the variable is in a "temporal dead zone" from the start of the block until
the declaration is processed.
logo
Practice Problems
Solve these problems to ace this concept
var vs let vs const
Easy
13.20 Mins
Solve
String coercion
String coercion takes place while using the ‘ + ‘ operator. When a number is added
to a string, the number type is always converted to the string type.
Example 1:
var x = 3;
var y = "3";
x + y // Returns "33"
Example 2:
var x = 24;
var y = "Hello";
x + y // Returns "24Hello";
Note - ‘ + ‘ operator when used to add two numbers, outputs a number. The same ‘ +
‘ operator when used to add two strings, outputs the concatenated string:
var name = "Vivek";
var surname = " Bisht";
name + surname // Returns "Vivek Bisht"
Let’s understand both the examples where we have added a number to a string,
When JavaScript sees that the operands of the expression x + y are of different
types ( one being a number type and the other being a string type ), it converts
the number type to the string type and then performs the operation. Since after
conversion, both the variables are of string type, the ‘ + ‘ operator outputs the
concatenated string “33” in the first example and “24Hello” in the second example.
Note - Type coercion also takes place when using the ‘ - ‘ operator, but the
difference while using ‘ - ‘ operator is that, a string is converted to a number
and then subtraction takes place.
var x = 3;
Var y = "3";
x - y //Returns 0 since the variable y (string type) is converted to a number
type
Boolean Coercion
Boolean coercion takes place when using logical operators, ternary operators, if
statements, and loop checks. To understand boolean coercion in if statements and
operators, we need to understand truthy and falsy values.
Truthy values are those which will be converted (coerced) to true. Falsy values are
those which will be converted to false.
All values except false, 0, 0n, -0, “”, null, undefined, and NaN are truthy values.
If statements:
Example:
var x = 0;
var y = 23;
if(x) { console.log(x) } // The code inside this block will not run since the
value of x is 0(Falsy)
if(y) { console.log(y) } // The code inside this block will run since the value
of y is 23 (Truthy)
Logical operators:
Logical operators in javascript, unlike operators in other programming languages,
do not return true or false. They always return one of the operands.
AND ( && ) operator - If both the values are truthy, always the second value is
returned. If the first value is falsy then the first value is returned or if the
second value is falsy then the second value is returned.
Example:
var x = 220;
var y = "Hello";
var z = undefined;
if( x && y ){
console.log("Code runs" ); // This block runs because x && y returns "Hello"
(Truthy)
}
if( x || z ){
console.log("Code runs"); // This block runs because x || y returns 220(Truthy)
}
Equality Coercion
Equality coercion takes place when using ‘ == ‘ operator. As we have stated before
While the above statement is a simple way to explain == operator, it’s not
completely true
The reality is that while using the ‘==’ operator, coercion takes place.
The ‘==’ operator, converts both the operands to the same type and then compares
them.
Example:
var a = 12;
var b = "12";
a == b // Returns true because both 'a' and 'b' are converted to the same type and
then compared. Hence the operands are equal.
Coercion does not take place when using the ‘===’ operator. Both operands are not
converted to the same type in the case of ‘===’ operator.
Example:
var a = 226;
var b = "226";
a === b // Returns false because coercion does not take place and the operands are
of different types. Hence they are not equal.
7. Is javascript a statically typed or a dynamically typed language?
JavaScript is a dynamically typed language. In a dynamically typed language, the
type of a variable is checked during run-time in contrast to a statically typed
language, where the type of a variable is checked during compile-time.
For example, a variable that is assigned a number type can be converted to a string
type:
var a = 23;
var a = "Hello World!";
8. What is NaN property in JavaScript?
NaN property represents the “Not-a-Number” value. It indicates a value that is not
a legal number.
Note- isNaN() function converts the given value to a Number type, and then equates
to NaN.
isNaN("Hello") // Returns true
isNaN(345) // Returns false
isNaN('1') // Returns false, since '1' is converted to Number type which results
in 0 ( a number)
isNaN(true) // Returns false, since true converted to Number type results in 1 ( a
number)
isNaN(false) // Returns false
isNaN(undefined) // Returns true
9. Explain passed by value and passed by reference.
In JavaScript, primitive data types are passed by value and non-primitive data
types are passed by reference.
var x = 2;
In the above example, we created a variable x and assigned it a value of “2”. In
the background, the “=” (assign operator) allocates some space in the memory,
stores the value “2” and returns the location of the allocated memory space.
Therefore, the variable x in the above code points to the location of the memory
space instead of pointing to the value 2 directly.
Assign operator behaves differently when dealing with primitive and non-primitive
data types,
var y = 234;
var z = y;
In the above example, the assign operator knows that the value assigned to y is a
primitive type (number type in this case), so when the second line code executes,
where the value of y is assigned to z, the assign operator takes the value of y
(234) and allocates a new space in the memory and returns the address. Therefore,
variable z is not pointing to the location of variable y, instead, it is pointing
to a new location in the memory.
var z = y;
var obj = #8711; // obj pointing to address of { name: "Vivek", surname: "Bisht" }
var obj2 = obj;
obj1.name = "Akki";
console.log(obj2);
Syntax of IIFE :
(function(){
// Do something;
})();
To understand IIFE, we need to understand the two sets of parentheses that are
added while creating an IIFE :
(function (){
//Do something;
})
While executing javascript code, whenever the compiler sees the word “function”, it
assumes that we are declaring a function in the code. Therefore, if we do not use
the first set of parentheses, the compiler throws an error because it thinks we are
declaring a function, and by the syntax of declaring a function, a function should
always have a name.
function() {
//Do something;
}
// Compiler gives an error since the syntax of declaring a function is wrong in the
code above.
To remove this error, we add the first set of parenthesis that tells the compiler
that the function is not a function declaration, instead, it’s a function
expression.
(function (){
// Do something;
})
11. What do you mean by strict mode in javascript and characteristics of javascript
strict-mode?
In ECMAScript 5, a new feature called JavaScript Strict Mode allows you to write a
code or a function in a "strict" operational environment. In most cases, this
language is 'not particularly severe' when it comes to throwing errors. In 'Strict
mode,' however, all forms of errors, including silent errors, will be thrown. As a
result, debugging becomes a lot simpler. Thus programmer's chances of making an
error are lowered.
function higherOrder(fn) {
fn();
}
The value of the “this” keyword will always depend on the object that is invoking
the function.\
Confused? Let’s understand the above statements by examples:
function doSomething() {
console.log(this);
}
doSomething();
What do you think the output of the above code will be?
The “this” keyword refers to the object that the function is a property of.
In the above code, the function is a property of which object?
Since the function is invoked in the global context, the function is a property of
the global object.
Therefore, the output of the above code will be the global object. Since we ran the
above code inside the browser, the global object is the window object.
Example 2:
var obj = {
name: "vivek",
getName: function(){
console.log(this.name);
}
}
obj.getName();
In the above code, at the time of invocation, the getName function is a property of
the object obj , therefore, this keyword will refer to the object obj, and hence
the output will be “vivek”.
Example 3:
var obj = {
name: "vivek",
getName: function(){
console.log(this.name);
}
Although the getName function is declared inside the object obj, at the time of
invocation, getName() is a property of obj2, therefore the “this” keyword will
refer to obj2.
The silly way to understand the “this” keyword is, whenever the function is
invoked, check the object before the dot. The value of this . keyword will always
be the object before the dot.
If there is no object before the dot-like in example1, the value of this keyword
will be the global object.
Example 4:
var obj1 = {
address : "Mumbai,India",
getAddress: function(){
console.log(this.address);
}
}
Although in the code above, this keyword refers to the object obj2, obj2 does not
have the property “address”‘, hence the getAddress function throws an error.
Normally, we declare a function and call it, however, anonymous functions may be
used to run a function automatically when it is described and will not be called
again. And there is no name for these kinds of functions.
sayHello.call(obj);
The apply method is similar to the call() method. The only difference is that,
call() method takes arguments separately whereas, apply() method takes arguments as
an array.
function saySomething(message){
return this.name + " is " + message;
}
var person4 = {name: "John"};
saySomething.apply(person4, ["awesome"]);
2. bind():
This method returns a new function, where the value of “this” keyword will be bound
to the owner object, which is provided as a parameter.
Example with arguments:
var bikeDetails = {
displayDetails: function(registrationNumber,brandName){
return this.name+ " , "+ "bike details: "+ registrationNumber + " , " +
brandName;
}
}
detailsOfPerson1();
//Returns Vivek, bike details: TS0122, Bullet
16. What is the difference between exec () and test () methods in javascript?
test () and exec () are RegExp expression methods used in javascript.
We'll use exec () to search a string for a specific pattern, and if it finds it,
it'll return the pattern directly; else, it'll return an 'empty' result.
We will use a test () to find a string for a specific pattern. It will return the
Boolean value 'true' on finding the given text otherwise, it will return 'false'.
17. What is currying in JavaScript?
Currying is an advanced technique to transform a function of arguments n, to n
functions of one or fewer arguments.
function multiply(a,b){
return a*b;
}
function currying(fn){
return function(a){
return function(b){
return fn(a,b);
}
}
}
It allows web designers and developers to collaborate on HTML and javascript files.
We can reuse the code.
Code readability is simple in external javascript.
19. Explain Scope and Scope Chain in javascript.
Scope in JS determines the accessibility of variables and functions at various
parts of one’s code.
In general terms, the scope will let us know at a given part of code, what are
variables and functions we can or cannot access.
Global Scope
Local or Function Scope
Block Scope
Global Scope: Variables or functions declared in the global namespace have global
scope, which means all the variables and functions having global scope can be
accessed from anywhere inside the code.
function sendMessage(){
return globalVariable; // can access globalVariable since it's written in global
space
}
function sendMessage2(){
return sendMessage(); // Can access sendMessage function since it's written in
global space
}
sendMessage2(); // Returns “Hello world”
Function Scope: Any variables or functions declared inside a function have
local/function scope, which means that all the variables and functions declared
inside a function, can be accessed from within the function and not outside of it.
function awesomeFunction(){
var a = 2;
{
let x = 45;
}
var y = 24;
function favFunction(){
var x = 667;
var anotherFavFunction = function(){
console.log(x); // Does not find x inside anotherFavFunction, so looks for
variable inside favFunction, outputs 667
}
anotherFavFunction();
yetAnotherFavFunction();
}
favFunction();
As you can see in the code above, if the javascript engine does not find the
variable in local scope, it tries to check for the variable in the outer scope. If
the variable does not exist in the outer scope, it tries to find the variable in
the global scope.
If the variable is not found in the global space as well, a reference error is
thrown.
this.getName = function(){
return name;
}
}
function randomFunc(){
var obj1 = {name:"Vivian", age:45};
return function(){
console.log(obj1.name + " is "+ "awesome"); // Has access to obj1 even when the
randomFunc function is executed
}
}
initialiseClosure();
Let’s understand the code above,
The function randomFunc() gets executed and returns a function when we assign it to
a variable:
initialiseClosure();
The line of code above outputs “Vivian is awesome” and this is possible because of
closure.
This ability of a function to store a variable for further reference even after it
is executed is called Closure.
The reason is the use of prototypes. As we discussed before, Array objects inherit
properties from the Array prototype.
The javascript engine sees that the method push does not exist on the current array
object and therefore, looks for the method push inside the Array prototype and it
finds the method.
Whenever the property or method is not found on the current object, the javascript
engine will always try to look in its prototype and if it still does not exist, it
looks inside the prototype's prototype and so on.
Functions that are used as an argument to another function are called callback
functions. Example:
function divideByHalf(sum){
console.log(Math.floor(sum / 2));
}
function multiplyBy2(sum){
console.log(sum * 2);
}
function operationOnSum(num1,num2,operation){
var sum = num1 + num2;
operation(sum);
}
Syntax error: Syntax errors are mistakes or spelling problems in the code that
cause the program to not execute at all or to stop running halfway through. Error
messages are usually supplied as well.
Logical error: Reasoning mistakes occur when the syntax is proper but the logic or
program is incorrect. The application executes without problems in this case.
However, the output findings are inaccurate. These are sometimes more difficult to
correct than syntax issues since these applications do not display error signals
for logic faults.
25. What is memoization?
Memoization is a form of caching where the return value of a function is cached
based on its parameters. If the parameter of that function is not changed, the
cached version of the function is returned.
Let’s understand memoization, by converting a simple function to a memoized
function:
Note- Memoization is used for expensive function calls but in the following
example, we are considering a simple function for understanding the concept of
memoization better.
function addTo256(num){
return num + 256;
}
addTo256(20); // Returns 276
addTo256(40); // Returns 296
addTo256(20); // Returns 276
In the code above, we have written a function that adds the parameter to 256 and
returns it.
When we are calling the function addTo256 again with the same parameter (“20” in
the case above), we are computing the result again for the same parameter.
Computing the result with the same parameter, again and again, is not a big deal in
the above case, but imagine if the function does some heavy-duty work, then,
computing the result again and again with the same parameter will lead to wastage
of time.
This is where memoization comes in, by using memoization we can store(cache) the
computed results based on the parameters. If the same parameter is used again while
invoking the function, instead of computing the result, we directly return the
stored (cached) value.
function memoizedAddTo256(){
var cache = {};
return function(num){
if(num in cache){
console.log("cached value");
return cache[num]
}
else{
cache[num] = num + 256;
return cache[num];
}
}
}
var memoizedFunc = memoizedAddTo256();
function add(number) {
if (number <= 0) {
return 0;
} else {
return number + add(number - 1);
}
}
add(3) => 3 + add(2)
3 + 2 + add(1)
3 + 2 + 1 + add(0)
3 + 2 + 1 + 0 = 6
Example of a recursive function:
The following function calculates the sum of all the elements in an array by using
recursion:
function computeSum(arr){
if(arr.length === 1){
return arr[0];
}
else{
return arr.pop() + computeSum(arr);
}
}
computeSum([7, 8, 9, 99]); // Returns 123
logo
Practice Problems
Solve these problems to ace this concept
Recursion
Medium
14.59 Mins
Solve
function Person(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
}
Let’s compare the normal function declaration and the arrow function declaration in
detail:
var obj1 = {
valueOfThis: function(){
return this;
}
}
var obj2 = {
valueOfThis: ()=>{
return this;
}
}
In the arrow functions, there is no binding of this keyword. This keyword inside an
arrow function does not refer to the object calling it. It rather inherits its
value from the parent scope which is the window object in this case. Therefore, in
the code above, obj2.valueOfThis() returns the window object.
logo
Practice Problems
Solve these problems to ace this concept
Regular vs Arrow Functions
Easy
7.38 Mins
Solve
The introduction of business objects with parameters that match the database's
default settings is a good example of where the Prototype pattern comes in handy.
The default settings for a newly generated business object are stored in the
prototype object.
34. Differences between declaring variables using var, let and const.
Before the ES6 version of javascript, only the keyword var was used to declare
variables. With the ES6 Version, keywords let and const were introduced to declare
variables.
function catchValues(){
console.log(variable1);
console.log(variable2);
// Both the variables can be accessed anywhere since they are declared in the
global scope
}
function varVsLetFunction(){
let awesomeCar1 = "Audi";
var awesomeCar2 = "Mercedes";
}
{
var variable3 = [1, 2, 3, 4];
}
{
let variable4 = [6, 55, -1, 2];
}
console.log(j) // Outputs 2
In javascript, a block means the code written inside the curly braces {}.
Variables declared with var keyword do not have block scope. It means a variable
declared in block scope {} with the var keyword is the same as declaring the
variable in the global scope.
Variables declared with let keyword inside the block scope cannot be accessed from
outside of the block.
Const keyword
Variables with the const keyword behave exactly like a variable declared with the
let keyword with only one difference, any variable declared with the const keyword
cannot be reassigned.
Example:
const x = {name:"Vivek"};
const y = 23;
Rest parameter ( … ):
// extractingArgs(8,9,1); // Returns 9
function addAllArgs(...args){
let sumOfArgs = 0;
let i = 0;
while(i < args.length){
sumOfArgs += args[i];
i++;
}
return sumOfArgs;
}
addFourNumbers(...fourNumbers);
// Spreads [5,6,7,8] as 5,6,7,8
Rest parameter is used to take a variable number of arguments and turns them into
an array while the spread operator takes an array or an object and spreads it
Rest parameter is used in function declaration whereas the spread operator is used
in function calls.
36. In JavaScript, how many different methods can you make an object?
In JavaScript, there are several ways to declare or construct an object.
Object.
using Class.
create Method.
Object Literals.
using Function.
Object Constructor.
37. What is the use of promises in javascript?
Promises are used to handle asynchronous operations in javascript.
Before promises, callbacks were used to handle asynchronous operations. But due to
the limited functionality of callbacks, using multiple callbacks to handle
asynchronous code can lead to unmanageable code.
Pending - Initial state of promise. This state represents that the promise has
neither been fulfilled nor been rejected, it is in the pending state.
Fulfilled - This state represents that the promise has been fulfilled, meaning the
async operation is completed.
Rejected - This state represents that the promise has been rejected for some
reason, meaning the async operation has failed.
Settled - This state represents that the promise has been either rejected or
fulfilled.
A promise is created using the Promise constructor which takes in a callback
function with two parameters, resolve and reject respectively.
resolve is a function that will be called when the async operation has been
successfully completed.
reject is a function that will be called, when the async operation fails or if some
error occurs.
Example of a promise:
Promises are used to handle asynchronous operations like server requests, for ease
of understanding, we are using an operation to calculate the sum of three elements.
function sumOfThreeElements(...elements){
return new Promise((resolve,reject)=>{
if(elements.length > 3 ){
reject("Only three elements or less are allowed");
}
else{
let sum = 0;
let i = 0;
while(i < elements.length){
sum += elements[i];
i++;
}
resolve("Sum has been calculated: "+sum);
}
})
}
In the code above, we are calculating the sum of three elements, if the length of
the elements array is more than 3, a promise is rejected, or else the promise is
resolved and the sum is returned.
We can consume any promise by attaching then() and catch() methods to the consumer.
then() method is used to access the result when the promise is fulfilled.
catch() method is used to access the result/error when the promise is rejected. In
the code below, we are consuming the promise:
sumOfThreeElements(4, 5, 6)
.then(result=> console.log(result))
.catch(error=> console.log(error));
// In the code above, the promise is fulfilled so the then() method gets executed
Unlike functions, classes are not hoisted. A class cannot be used before it is
declared.
A class can inherit properties and methods from other classes by using the extend
keyword.
All the syntaxes inside the class must follow the strict mode(‘use strict’) of
javascript. An error will be thrown if the strict mode rules are not followed.
logo
Practice Problems
Solve these problems to ace this concept
Classes And Their Instances
Medium
11.5 Mins
Solve
Class Inheritance
Medium
11.26 Mins
Solve
They can be stopped midway and then continue from where they had stopped.
Generator functions are declared with the function* keyword instead of the normal
function keyword:
function* genFunc(){
// Perform operation
}
In normal functions, we use the return keyword to return a value and as soon as the
return statement gets executed, the function execution stops:
function normalFunc(){
return 22;
console.log(2); // This line of code does not get executed
}
In the case of generator functions, when called, they do not execute the code,
instead, they return a generator object. This generator object handles the
execution.
function* genFunc(){
yield 3;
yield 4;
}
genFunc(); // Returns Object [Generator] {}
The generator object consists of a method called next(), this method when called,
executes the code until the nearest yield statement, and returns the yield value.
Generator functions are used to return iterators. Let’s see an example where an
iterator is returned:
function* iteratorFunc() {
let count = 0;
for (let i = 0; i < 2; i++) {
count++;
yield i;
}
return count;
}
console.log(classStrength); // Outputs 78
console.log(classBenches); // Outputs 39
console.log(classBlackBoard); // Outputs 1
As one can see, using object destructuring we have extracted all the elements
inside an object in one line of code. If we want our new variable to have the same
name as the property of an object we can remove the colon:
let x;
function anotherRandomFunc(){
message = "Hello"; // Throws a reference error
let message;
}
anotherRandomFunc();
In the code above, both in the global scope and functional scope, we are trying to
access variables that have not been declared yet. This is called the Temporal Dead
Zone.
48. Difference between Async/Await and Generators usage to achieve the same
functionality.
Generator functions are run by their generator yield by yield which means one
output at a time, whereas Async-await functions are executed sequentially one after
another.
Async/await provides a certain use case for Generators easier to execute.
The output result of the Generator function is always value: X, done: Boolean, but
the return value of the Async function is always an assurance or throws an error.
Boolean
Undefined
Null
Number
String
50. What is the role of deferred scripts in JavaScript?
The processing of HTML code while the page loads are disabled by nature till the
script hasn't halted. Your page will be affected if your network is a bit slow, or
if the script is very hefty. When you use Deferred, the script waits for the HTML
parser to finish before executing it. This reduces the time it takes for web pages
to load, allowing them to appear more quickly.
51. What has to be done in order to put Lexical Scoping into practice?
To support lexical scoping, a JavaScript function object's internal state must
include not just the function's code but also a reference to the current scope
chain.
function func1(){
setTimeout(()=>{
console.log(x);
console.log(y);
},3000);
var x = 2;
let y = 12;
}
func1();
// Code 2:
function func2(){
for(var i = 0; i < 3; i++){
setTimeout(()=> console.log(i),2000);
}
}
func2();
// Code 3:
(function(){
setTimeout(()=> console.log(1),2000);
console.log(2);
setTimeout(()=> console.log(3),0);
console.log(4);
})();
Answers:
Code 1 - Outputs 2 and 12. Since, even though let variables are not hoisted, due to
the async nature of javascript, the complete function code runs before the
setTimeout function. Therefore, it has access to both x and y.
Code 2 - Outputs 3, three times since variable declared with var keyword does not
have block scope. Also, inside the for loop, the variable i is incremented first
and then checked.
Code 3 - Output in the following order:
2
4
3
1 // After two seconds
Even though the second timeout function has a waiting time of zero seconds, the
javascript engine always evaluates the setTimeout function using the Web API, and
therefore, the complete function executes before the setTimeout function can
execute.
// Code 2:
function runFunc(){
console.log("1" + 1);
console.log("A" - 1);
console.log(2 + "-2" + "2");
console.log("Hello" - "World" + 78);
console.log("Hello"+ "78");
}
runFunc();
// Code 3:
let a = 0;
let b = false;
console.log((a == b));
console.log((a === b));
Answers:
11
Nan
2-22
NaN
Hello78
Code 3 - Output in the following order due to equality coercion:
true
false
55. Guess the output of the following code:
var x = 23;
(function(){
var x = 43;
(function random(){
x++;
console.log(x);
var x = 21;
})();
})();
Answer:
Output is NaN.
random() function has functional scope since x is declared and hoisted in the
functional scope.
Rewriting the random function will give a better idea about the output:
function random(){
var x; // x is hoisted
x++; // x is not a number since it is not initialized yet
console.log(x); // Outputs NaN
x = 21; // Initialization of x
}
56. Guess the outputs of the following code:
// Code 1
let hero = {
powerLevel: 99,
getPower(){
return this.powerLevel;
}
}
// Code 2
const a = function(){
console.log(this);
const b = {
func1: function(){
console.log(this);
}
}
const c = {
func2: ()=>{
console.log(this);
}
}
b.func1();
c.func2();
}
a();
// Code 3
const b = {
name:"Vivek",
f: function(){
var self = this;
console.log(this.name);
(function(){
console.log(this.name);
console.log(self.name);
})();
}
}
b.f();
Answers:
undefined
42
Reason - The first output is undefined since when the function is invoked, it is
invoked referencing the global object:
window.getPower() = getPower();
global/window object
object "b"
global/window object
Since we are using the arrow function inside func2, this keyword refers to the
global object.
"Vivek"
undefined
"Vivek"
Only in the IIFE inside the function f, this keyword refers to the global/window
object.
57. Guess the outputs of the following code:
**Note - Code 2 and Code 3 require you to modify the code, instead of guessing the
output.
// Code 1
(function(a){
return (function(){
console.log(a);
a = 23;
})()
})(45);
// Code 2
function bigFunc(element){
let newArray = new Array(700).fill('♥');
return newArray[element];
}
// Code 3
// The following code outputs 2 and 2 after waiting for one second
// Modify the code to output 0 and 1 after one second.
function randomFunc(){
for(var i = 0; i < 2; i++){
setTimeout(()=> console.log(i),1000);
}
}
randomFunc();
Answers -
Even though a is defined in the outer function, due to closure the inner functions
have access to it.
function bigFunc(){
let newArray = new Array(700).fill('♥');
return (element) => newArray[element];
}
function randomFunc(){
for(let i = 0; i < 2; i++){
setTimeout(()=> console.log(i),1000);
}
}
randomFunc();
Using closure:
function randomFunc(){
for(var i = 0; i < 2; i++){
(function(i){
setTimeout(()=>console.log(i),1000);
})(i);
}
}
randomFunc();
58. Write a function that performs binary search on a sorted array.
function binarySearch(arr,value,startPos,endPos){
if(startPos > endPos) return -1;
return [4,5,7,2,3]
Answer:
function rotateRight(arr,rotations){
if(rotations == 0) return arr;
for(let i = 0; i < rotations;i++){
let element = arr.pop();
arr.unshift(element);
}
return arr;
}
rotateRight([2, 3, 4, 5, 7], 3); // Return [4,5,7,2,3]
rotateRight([44, 1, 22, 111], 5); // Returns [111,44,1,22]
60. Write the code for dynamically inserting new components.
<html>
<head>
<title>inserting new components dynamically</title>
<script type="text/javascript">
function addNode () { var newP = document. createElement("p");
var textNode = document.createTextNode(" This is other node");
newP.appendChild(textNode);
document.getElementById("parent1").appendChild(newP); }
</script>
</head>
<body> <p id="parent1">firstP<p> </body>
</html>
61. Write the code given If two strings are anagrams of one another, then return
true.
var firstWord = "Deepak";
var secondWord = "Aman";
// Sort the strings, then combine the array to a string. Examine the outcomes.
a = a.split("").sort().join("");
b = b.split("").sort().join("");
return a === b;
}
62. Write the code to find the vowels
const findVowels = str => {
let count = 0
const vowels = ['a', 'e', 'i', 'o', 'u']
for(let char of str.toLowerCase()) {
if(vowels.includes(char)) {
count++
}
}
return count
}
63. In JavaScript, how do you turn an Object into an Array []?
let obj = { id: "1", name: "user22", age: "26", work: "programmer" };
1
2
3
4
5
6
7
8
9
10
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
Conclusion
It is preferable to keep the JavaScript, CSS, and HTML in distinct Separate
'javascript' files. Dividing the code and HTML sections will make them easier to
understand and deal with. This strategy is also simpler for several programmers to
use at the same time. JavaScript code is simple to update. Numerous pages can
utilize the same group of JavaScript Codes. If we utilize External JavaScript
scripts and need to alter the code, we must do it just once. So that we may utilize
a number and maintain it much more easily. Remember that professional experience
and expertise are only one aspect of recruitment. Previous experience and personal
skills are both vital in landing (or finding the ideal applicant for the job.
Remember that many JavaScript structured interviews are free and have no one proper
answer. Interviewers would like to know why you answered the way you did, not if
you remembered the answer. Explain your answer process and be prepared to address
it.
JavaScript MCQ
1.
Which of the following statements regarding JavaScript is true?
JavaScript is Assembly-language
true
runtime error
compilation error
false
3.
In JavaScript, which of the following is not a bug?
A grammatical mistake
Bracket is missing
4.
JavaScript was created by which company?
IBM
Sun Microsystems
Netscape
Bell Labs
5.
What do you mean by block statement in JavaScript?
Block-based on condition
A block of code that combines many sentences together into a single compound
statement.
toString()
substring()
toUpperCase()
toLocaleUpperCase()
8.
The JSON() method's property is
Number
Undefined
Float
Boolean
10.
The interpreter for Javascript is
Client
Object
Server