Javascript More Interview Questions

 

1. What is var?

The

var
keyword is a way of declaring a variable similar to
let
and
const
.

Var has no block scope

Variables declared with

var
are either function-scoped or global-scoped.

If a variable is declared inside a function, it is function-scoped. Else, it is global-scoped.

Example: Function-scoped

function sayHi() {
if (true) {
var phrase = "Hello";
}
alert(phrase); // works
}
sayHi();
alert(phrase); // ReferenceError: phrase is not defined
JAVASCRIPT

Var can be redeclared

We can redeclare a variable with

var
any number of times.

var user = "Pete";
var user = "John";
alert(user); // John
JAVASCRIPT

Var can be declared below their use

All variables declared with

var
are hoisted to the top of the function.

Example:

function sayHi() {
alert(phrase); // undefined
var phrase;
phrase = "Hello";
}
sayHi();
JAVASCRIPT
Note
Declarations are hoisted, but assignments are not.

2. What are the differences between var, let and const?

Some of the differences between

var
,
let
and
const
are:

basis of comparisonvarletconst
ScopeVariables declared with var are in the function scopeVariables declared as let are in the block scopeVariables declared as const are in the block scope
HoistingAllowedNot allowedNot allowed
Reassigning valueAllowedAllowedNot allowed
Redeclaring variableAllowedNot allowedNot allowed

3. When do you use the var, let and const?

let: It is used when we know that the value of a variable will change. const: It is used for all the variables which don't change their value. var: It is not recommended to use the

var
keyword to avoid errors/bugs.


4. What is Type coercion?

Type coercion is the implicit conversion of values from one data type to another.

Implicit type coercion in JavaScript is the automatic conversion of value from one data type to another.

It takes place when the operands of an expression are of different data types.

Example:

let x = 3;
let y = "3";
console.log(x + y); // Returns "33"
JAVASCRIPT

In the above example, a number is added to a string, the number type is always converted to the string type.


5. What is the result of 
3+3
3+"3"
"3"-3
?

Implicit type coercion takes place when the operands of an expression are of different data types.

  1. 3+3

The result of

3+3
is
6
as both the operands are numbers and the addition operation is performed.

  1. 3+"3"

The result is

33
.

When one of the operands is a string and an arithmetic operator

+
is used, the number is converted to a string.

When an arithmetic operator is used between two strings, the two strings are concatenated.

  1. "3"-3

The result is

0
.

When the subtraction is performed, all the strings are converted to numbers.


6. Is JavaScript typed dynamically?

Yes, JavaScript is a dynamically typed language. Because

  • We can declare a variable without specifying the data type
  • We can change the data type of the variable when it is reassigned

Example:

let count = "one";
count = 2;
JAVASCRIPT

7. What is a self-invoking function?

The Self-invoking function is a JavaScript function that executes immediately after it has been defined. So, there is no need to manually invoke IIFE.

It is also called the Immediately Invoked Function Expressions(IIFE).

Example:

(function () {
let message = "Hello World!!"; // I will invoke myself
})();
JAVASCRIPT

8. What are the different DOM methods to access the HTML elements from JavaScript?

Some of the DOM methods to access the HTML elements from JavaScript are:

  • getElementsByClassName('classname'): Returns all the elements that have the specified class name. It returns an array-like object.

  • getElementById('id'): Returns the element that has the specified id.

  • getElementsByTagName('tagname'): Returns all the elements that have the specified tag name. It returns an array-like object.

  • querySelector(): Takes CSS style selector as argument and returns the first selected HTML element.


9. Is JavaScript synchronous or asynchronous?

JavaScript is always synchronous and single-threaded. If we are executing a JavaScript block of code on a page, then no other JavaScript on that page will currently be executed.

JavaScript is only asynchronous when it has API calls, timers, etc.


10. What is a pure function in JavaScript?

A function is called a pure function when:

  • Given the same input, it always returns the same output.
  • It produces no side effects.

Example:

const add = (num1, num2) => num1 + num2;
add(2, 4);
console.log(add(2, 4)); // Output: 6
JAVASCRIPT

In the above example, It returns a value based on the given parameters regardless of where/when you call it.

If you pass 2 and 4, you’ll always get 6.


11. Explain NaN in JavaScript?

The

NaN
property represents Not-a-Number value. The
typeof
of a
NaN
returns a Number.

Five different types of operations return

NaN
:

  • Number cannot be parsed (e.g. parseInt("blabla") or Number(undefined))
  • Math operation where the result is not a real number (e.g. Math.sqrt(-1))
  • Operand of an argument is NaN (e.g. 7 ** NaN)
  • Indeterminate form (e.g. 0 * Infinity, or undefined + undefined)
  • Any operation that involves a string and is not an addition operation (e.g. "foo" / 3)

We use the

isNaN
function to check if a value is
NaN
or not.

Example:

isNaN(345); // returns false
isNaN(undefined); // returns true
JAVASCRIPT

12. What is Call by value and Call by reference?

Call by value

The Primitive data types are passed by value in JavaScript.

If you pass the argument by value, it will make a new copy of the variable inside the function, without affecting the original variable.

Example:

let bike = "TVS Apache";
let newBike = (vehicle) => {
vehicle = "Royal Enfield";
console.log(vehicle); // Royal Enfield
};
newBike(bike);
console.log(bike); // TVS Apache
JAVASCRIPT

Call by reference

The Object data types are passed by reference in JavaScript.

If you pass the argument by reference, the change will be produced not only inside the function but also affect the original variable.

Example:

let bike = { id: 1, model: "TVS Apache" };
let newBike = (vehicle) => {
vehicle.model = "Royal Enfield";
console.log(vehicle.model); // Royal Enfield
};
newBike(bike);
console.log(bike.model); // Royal Enfield
JAVASCRIPT
Note
The words call by value and pass by value or call by reference and pass by reference are the same. Both are used interchangeably.

13. What are the types of errors in JavaScript?

There are different types of errors in JavaScript. Some of them are:

Syntax error:

A syntax error can be thrown when there is an error in the syntax (rules of language).

Examples:

  • Missing opening or closing brackets, braces, or parentheses
  • Missing variable names while declaring, etc.

Runtime errors:

Type error:

A Type error can be thrown when we try to make an operation on the incorrect data type.

Example:

let isChecked = true;
isChecked.filter((item) => item === true); // Uncaught TypeError: isChecked.filter is not a function
JAVASCRIPT

Reference error:

A reference error can be thrown when a variable is used that does not exist or is not in the current scope.

Example:

function getNumbers() {
let num1 = 2;
let num2 = 3;
return num1 + num2;
}
console.log(num1);
JAVASCRIPT

Here

num1
is declared with the
let
in
getNumbers
function.

As

let
is block-scoped, the variable declared with
let
exists only up to that block (
getNumbers
function).

So, the variable doesn't exist outside the function.


14. What type of errors are shown in the console window?

Both the syntax and runtime errors are shown in the console window.

Syntax error:

It is thrown when we violate the rules of language.

Example:

let nameEl = document.getElementById("name");
nameEl.addEventListener("blur", function() {
console.log("blur event triggered"); // Uncaught SyntaxError: missing ) after argument list
};
 
JAVASCRIPT

Runtime error:

Runtime errors are thrown during the execution of code. It includes reference errors, type errors, etc.

Example: Type error

let isChecked = true;
isChecked.filter((item) => item === true); // Uncaught TypeError: isChecked.filter is not a function
JAVASCRIPT

15. What is an Anonymous function?

An anonymous function is a function without a name. These are commonly assigned to a variable or used as a callback function.

Assigned to a variable

const getNumbers = function(){
...
};
JAVASCRIPT

Callback Function

let array = [1, 2, 3];
array.map(function(item){
...
})
JAVASCRIPT

16. Is JavaScript a single-threaded or multi-threaded language?

JavaScript is a single-threaded language.

A single-thread language is one with a single call stack and a single memory heap. It means that it runs only one thing at a time.


17. What is a Session Storage?

Session Storage is a Storage Object. Data can be stored in the form of key-value pairs.

The properties and methods are the same as the Local Storage. But,

  • The Session Storage exists only within the current browser tab.
  • Another tab with the same page will have different storage.
  • The data survives page refresh, but not closing/opening the tab.

18. What are the differences between Local Storage and Session Storage?

Local StorageSession Storage
Stores data with no expiration dateData is lost when the browser tab is closed
Persists even browser restartPersists only for page refresh (but not tab close)
Shared between all tabs and windows with the same originVisible within a browser tab, including iframes from the same origin

19. What is the maximum storage capacity of Local Storage and Session Storage?

The maximum storage capacity of both Local Storage and Session Storage is > 5MB, depending on the browser.


20. What is the innerHTML property in JavaScript?

The

innerHTML
property is used to set or get the HTML/text contained within the HTML element.

Example:

let containerEl = document.getElementById("container");
let paragraphEl = document.getElementById("para");
containerEl.innerHTML = `
<h1>Tourism</h1>
<p>Plan your trip.</p>`;
paragraphEl.innerHTML = "Explore the world";
JAVASCRIPT

21. What are the disadvantages of using innerHTML in JavaScript?

Some of the disadvantages of using innerHTML are:

  • HTML content is replaced every time
  • Very slow as all the HTML content has to be converted into nodes and updated in the DOM.

22. When does the finally block execute?

The finally block will always execute after the

try
block and
catch
block have finished executing.

It always executes, regardless of whether an exception was thrown or caught.


23. What is the Static keyword in JavaScript?

The

static
Keyword defines a static method or property for a class.

Static methods or Static properties cannot be called on instances of the class. They are called on the class itself.

Example:

class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
static displayName = "Rectangle";
static print() {
return "Static method print() is called from Rectangle";
}
}
console.log(Rectangle.displayName); // Output: Rectangle
console.log(Rectangle.print()); // Output: Static method print() is called from Rectangle
let rectangle1 = new Rectangle(10, 8);
console.log(rectangle1.displayName); // Output: undefined
console.log(rectangle1.print()); // TypeError: rectangle1.print is not a function
 
JAVASCRIPT
Collapse

From the above example,

  • Calling a Static property from a class instance will return undefined
  • Calling a Static method from a class instance will throw an error

24. What is the ES6 Model?

ES6 is also known as ECMAScript 6 and ECMAScript 2015.

It is the latest version of the ECMAScript standard that was introduced in 2015.

Some of the new features in ES6 are:

  • JavaScript let
  • JavaScript const
  • Promises
  • JavaScript Arrow Functions
  • JavaScript Classes
  • Default parameter values
  • Array.find()
  • Array.findIndex()
  • Destructuring Assignment, etc.

25. What is an ECMAScript?

ECMAScript stands for European Computer Manufacturers Association Script.

  • It is a Standard for scripting languages.
  • Languages like Javascript are based on the ECMAScript standard.
  • It specifies the core features that a scripting language should provide and how those features should be implemented.

26. What is the version of JavaScript are you using?

We are using the ES6 version of JavaScript.


27. How to add the Popup?

The Popups are used to display the message or notification to the user.

We can add the Popups using

alert
,
confirm
,
prompt
, etc.

Examples:

alert("I am an alert box!");
window.confirm("sometext");
window.prompt("sometext","defaultText");
JAVASCRIPT

28. Explain alert and confirmation?

Alert

The

alert
method displays an alert box with a message and an OK button.

The User cannot interact with the rest of the page until they press the OK button.

Example:

alert("Hello");
JAVASCRIPT

Confirm

The

confirm
method displays a dialog box with a message, an OK button, and a Cancel button. It returns
true
for OK and
false
for Cancel/Esc.

The User cannot interact with the rest of the page until they press the OK/ Cancel button.

Example:

confirm("Are you the boss?");
JAVASCRIPT

29. What are valid JavaScript variable names?

Valid Javascript variable names should follow the below rules:

  • It can contain alphanumeric characters, _ and $.
  • It cannot start with a number.

Examples of Valid JavaScript variable names:

firstName
,
_firstName
,
firstName12

Examples of Invalid JavaScript variable names:

12firstName
,
firstName 12


30. How to convert date and time into milliseconds in JavaScript?

We can use the third-party package

date-fns
to do manipulations on Date and Time.

The

getMilliseconds
convert the date and time to milliseconds.

Example:

// Get the milliseconds of 29 February 2012 11:45:05.123:
const result = getMilliseconds(new Date(2012, 1, 29, 11, 45, 5, 123)); // Output: 123
JAVASCRIPT

31. How to stop event propagation?

The

stopPropagation
method of the Event object prevents further propagation of the current event in the capturing and bubbling phases.

bubbling:

When an event happens on an element,

  • It runs the event handler of it
  • It runs the event handler of the direct parent
  • It runs the event handler of the grand parent and so on upwards till the document object.

capturing:

When an event happens on an element,

  • It runs the event handler of the outermost element
  • It runs the event handler of the next element and so on downwards till the target element (the element in which the event has happened)

Syntax:

event.stopPropagation();
JAVASCRIPT

32. What is an HTML onmouseover event?

The HTML

onmouseover
event is triggered when the pointing device (such as a mouse or trackpad) is moved onto an HTML element, or onto one of its children.

Example:

<img onmouseover="getCoordinates()" src="IMAGE_URL" />
HTML

33. How do we read and write files in JavaScript?

JavaScript is not allowed to read files from the computer.

To read/write files with JavaScript, We need to be running it as a server (using

Node.js
, etc.)

We can read/write files using the

fs
module in Node.js

fs.readFile(): Reads the file

Syntax:

fs.readFile( filename, encoding, callback )

fs.writeFile(): Writes the file with the given data

Syntax:

fs.writeFile( file, data, options, callback )

To know more about

fs.readFile
,
fs.writeFile
methods, please refer to this


34. How can we get the current URL with JavaScript?

We can use the

window.location.href
property to get the entire URL of the current page.


35. What are the different types of Loops?

JavaScript supports different types of Loops. Some of them are:

while loop: It executes its statements as long as a specified condition evaluates to

true
.

Syntax:

while (condition) {
//lines of code to be executed
}
JAVASCRIPT

for loop: It repeats until a specified conditionExpression evaluates to

false
.

Syntax:

for ([initialExpression]; [conditionExpression]; [incrementExpression]) {
//lines of code to be executed
}
JAVASCRIPT

do...while loop: It repeats until a specified condition evaluates to

false
.

Syntax:

do {
//block of code to be executed
} while (condition);
JAVASCRIPT

The block of code in the

do
statement is always executed once before the condition is checked. If the condition is
true
, the statement executes again.

for...in loop: It iterates a specified variable over all the properties of an object.

Syntax:

for (variable in object) {
//lines of code to be executed
}
JAVASCRIPT

for...of loop: It iterates a specified variable over all the property values of iterable objects( Array, Map, Set, etc).

Syntax:

for (variable of object) {
//lines of code to be executed
}
JAVASCRIPT

36. When to use for and while loops?

For Loop is used when we know the number of times the loop should run.

While loop is used when we want the loop to break based on a condition other than the number of times it runs.


37. What is Recursion?

Recursion is the process of calling a function itself. The function calls itself until a condition is met.

The condition that stops a recursive function from calling itself is known as the base case.

Example:

function factorial(num) {
if (num === 1) {
return num;
}
return num * factorial(num - 1);
}
console.log(factorial(2));
JAVASCRIPT

38. How to create a variable similar to a tuple in JavaScript?

JavaScript doesn't have tuples.

But we can pretend that JavaScript has tuples in many ways.

One of the ways is by array destructuring and making a function to return multiple values.

Example:

function getTuple() {
return ["Bob", 24];
}
let [a, b] = getTuple(); // a is Bob and b is 24
JAVASCRIPT

39. What is the difference between Put & Patch?

PATCH is used for updating partial data and PUT is used for updating all the data.

If we only need to update one field for the resource, we use the PATCH method


40. What is the DOM owner document property?

The

ownerDocument
property returns the top-level document object of the node. It is a read-only property.

The top-level object is the document object in which all child nodes are created.

If this property is used on the top-level document object itself, it returns null.

Example:

let paragraphEl = document.getElementById("para");
console.log(paragraphEl.ownerDocument);
JAVASCRIPT
Note
The DOM tree represents an HTML document as nodes. Each node is referred to as an Object.

41. What are the Sequences in JavaScript and Python?

A sequence is a positionally ordered collection of items. Elements in sequences come out in the same order as it is inserted.

Sequences in Python: lists, byte arrays, strings, tuples, range, and bytes

Sequences in JavaScript: arrays, strings

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form