JS Interview

Top 30 JavaScript Interview Questions


What are the features of ES6?

  • Classes
  • Modules
  • Default Parameters > function(height = 50, color = ‘red’) { }
  • Template Literals > Your name is ${first} ${last}.
  • Multi-line Strings >By using backticks.
  • Destructuring Assignment
  • Arrow Functions
  • Promises > ES6 introduced Promises, is a First class representation of a value that may be made asynchronously and be available in the future.
  • Block-Scoped Constructs Let and Const
  • Rest parameter > function f (x, y, …a) { }
  • Spread operator > Spreading of elements of an iterable collection (like an array or even a string)
  • Export and Import feature.
  • New Built-In method on String Searching > startWith, endWith, includes. before we use indexOf only.
  • New Built-In Methods Number Type Checking > Number.isNaN, Number.isFinite

✋ Before Promise, How we had implemented this concept in ES5?

Below is Promise way of ES6:

function message(name, id) {
  return new Promise((resolve, reject) => {
  resolve('success');
})
}

message('JSMount', 101).then(res => {
  console.log(res);
})

Below is the Implementation of the promise way in ES5:

function messageEs5(name, id, cb) {
  if(name === 'JsMount') {
    cb(name);
  }else {
  cb(null)
  }
}

// Passed a callback function 
messageEs5('JsMount', 101, function(res)  {
console.log(res);
  
})

What is Object.preventExtensions()?

The Object.preventExtensions() method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object).

const object1 = {name: 'JsMount'};
Object.preventExtensions(object1);

// Try to add new property 'id', so it will not impact on object.
object1['id'] = 123;

object1
{name: "JsMount"} // object is still same.

What is the difference between Rest API and SOAP API?

  • Rest full form is RestFul API and SOAP is a Standard Communication Protocol System.
  • REST API is an architectural style and it has no official standard. SOAP API, on the other hand, has an official standard because it is a protocol.
  • REST APIs use multiple standards like HTTP, JSON, URL, and XML while SOAP APIs are largely based on HTTP and XML.

What are the important components of JWT?

As per https://jwt.io/introduction

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.
JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

💡 There are three main components used to create a JWT.
And Therefore, a JWT typically looks like the following.
Header.Payload.Signature

  • Header
  • Payload
  • Signature

What are Request Headers?

HTTP headers are used by the client and the server both to pass additional information with an HTTP request or response.
An HTTP header consists of its case-insensitive name followed by a colon (:), then by its value.

What is the difference between 401 and 403?

HTTP 401 - Unauthorized
HTTP 403 - Forbidden

401 is an Unauthorized client error status response code. This error comes due to invalid authentication credentials for the target resource. This status is similar to 403, but in this case, authentication is possible.

403 is forbidden client error status response code indicates that the server understood the request but refuses to authorize it because of insufficient rights to a resource.
In 403, re-authenticating will make no difference because the access is permanently forbidden and tied to the application logic.

What is the difference between 400, 404, and 405?

400 Bad Request
404 Not Found
405 Method Not Allowed

In 400, the server cannot process the request due to something that is perceived to be a client error (e.g., incorrect URL, any request syntax, invalid request message framing).

A 404 Not Found error indicates that the requested resource could not be found, and is often the result of an incorrect URL.

A 405 code response confirms that the requested resource is exists and valid, but the client has used an unacceptable HTTP method during the request.

What is the Http 500 error code?

500 Internal Server Error comes when the server encountered an unexpected condition that prevented it from fulfilling the request.

What is Call Stack?

JavaScript is a single-threaded programming language, so it can do one thing at a time which means it has a single Call Stack.

The Call Stack is a data structure. Each entry in the Call Stack is called a Stack Frame. When we step into a function, we put it on the top of the stack. If we return from a function, we pop off the top of the stack.

What is the benefit of Single thread?

In Single thread, we can execute only one program or task at a time so we don’t have to deal with any complicated scenarios that come in multi-threaded — for example, deadlocks. But running on a single thread is quite limiting as well.

How can we execute heavy code without blocking the UI and making the browser unresponsive?

The solution is asynchronous callbacks.

Which all compilers, JavaScript V8 engine used?

V8 used two compilers before version 5.9 of V8.

2008 – Full-Codegen — a simple and very fast compiler that produced simple and relatively slow machine code.
2010 – Crankshaft — a more complex (Just-In-Time) optimizing compiler that produced highly optimized code.
2015 – TurboFan (Released in V8 – Version 5.9) – V8’s newest optimizing compiler introduced bigger performance improvements and significant memory savings in real-world JavaScript applications.

Ignition – V8’s interpreter that is used with TurboFan compiler.

Top 30 JavaScript Interview Questions

How can we do the browser in Full-screen mode?

To open the whole page in full screen, use the

document.documentElement.requestFullscreen(); // This returns a Promise

// you can write below way if you have to handle success

document.documentElement.requestFullscreen().then(() => {
 console.log('success');
})

document.exitFullscreen().then(() => {
 console.log('success');
})

How to enable navigation prompt message in JavaScript?

Enable navigation prompt

window.onbeforeunload = function() {
    return true;
};

The above code will display a prompt message of “Changes you made may not be saved.” with Reload and Cancel button.

Remove navigation prompt

window.onbeforeunload = null;

What is the difference between mouseleave and mouseout event?

The core difference between mouseleave and mouseout events are that mouseleave does not bubble and mouseout does.

Let’s ee below code snippet.

<ul id="test">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ul>
  • mouseleave – In the case of the mouseleave event, handler executs only when the mouse leaves the element it is bound to, not a descendant.
  • mouseout – But on the other hand, when the mouse pointer moved out of the Inner element, the handler would be triggered as well. This is usually undesirable behavior.

So as per the above code, If we attach mouseout on ul element, it will trigger when the pointer moved out from li elements while if we attach mouseleave, it will be triggered when pointer leaves the ul element only.

Understand with an example:
https://developer.mozilla.org/enUS/docs/Web/API/Element/mouseout_event#examples

How can I detect when the mouse leaves the window?

document.onmouseleave = function() {
alert('Don't navigate to any other page else your exam will be dismissed automatically');
};

How to access webcam and take photos with JavaScript?

💡 Implement WebCam feature with Pure JavaScript API

var constraints = { audio: true, video: true };
var promise = navigator.mediaDevices.getUserMedia(constraints);

By Executing the above two lines, Browser will ask you to use your microphone and Camera, and WebCam and Audio functionality will start after allowing it.

✔ Access Camera on mobile devices

// For example, on mobile devices, the following will prefer the front camera (if one is available) over the rear one:

{ audio: true, video: { facingMode: "user" } };

// To require the rear camera, use:

{ audio: true, video: { facingMode: { exact: "environment" } } }

You can get a list of all the constraints supported by the device by calling –

navigator.mediaDevices.getSupportedConstraints()

▶ Let’s see How can we implement this in HTML with code.

<button>Start streaming</button>
<video autoplay></video>
var stream;
document.querySelector('button').addEventListener('click', async (e) => {
 stream = await navigator.mediaDevices.getUserMedia({video: true});  
 document.querySelector('video').srcObject = stream; // display web cam stream in video tag
});

// To stop streaming we can call below function.

stream.getTracks().forEach(function(track) {
        if (track.readyState == 'live') {
            track.stop();
        }
    });

💡 Webcam Easy JS package

We can use the Webcam Easy JS package to implement this feature for both desktop and mobile browsers. This webcam Easy Js package is completely written using JavaScript API MediaDevices.getUserMedia() as explained above.

// Install Package
npm install webcam-easy

// Or Add CDN Link in HTML
<script type="text/javascript" src="https://unpkg.com/webcam-easy/dist/webcam-easy.min.js"></script>

Read more doc on this.
https://www.npmjs.com/package/webcam-easy
https://bensonruan.com/how-to-access-webcam-and-take-photo-with-javascript/

Tell me some important properties of navigator API.

  • appCodeName – Returns the code name of the browser
  • appName – Returns the name of the browser
  • appVersion – Returns the version information of the browser
  • cookieEnabled – Determines whether cookies are enabled in the browser
  • geolocation – Returns a Geolocation object that can be used to locate the user’s position
  • onLine – Determines whether the browser is online
  • platform – Returns for which platform the browser is compiled
  • product – Returns the engine name of the browser

What is history object in JavaScript?

  • The history object is part of the window object and is accessed through the window.history property.
  • The history object contains the URLs visited by the user (within a browser window).
window.history

History {length: 8, scrollRestoration: "auto", state: null}
length: 8
scrollRestoration: "auto"
state: null

Supported methods:

  • back() Loads the previous URL in the history list
  • forward() Loads the next URL in the history list
  • go() Loads a specific URL from the history list

What are the standard sizes of responsive devices?

  • 320px — 480px: Mobile devices
  • 481px — 768px: iPads, Tablets
  • 769px — 1024px: Small screens, laptops
  • 1025px — 1200px: Desktops, large screens
  • 1201px and more —  Extra large screens, TV

What is the output of the below console programs?

console.log(true) // true

console.log(true + 1) // 2

console.log(true - false); // 1

console.log(false - true) // -1
console.log(3 + "2"); // 32

console.log("3" + 2); // 32

console.log("3" -  2); // 1
const func = () => {
  console.log(arguments);
} 
func();

output > reference error: 'arguments' not defined
var a = {};
var b = {};
a === b; 
output > false 
var obj = {};
var obj2 = Object.preventExtensions(obj);

obj === obj2; 

output is > true 
// because Object.preventExtensions returns the object being made non-extensible.

What are the limitations of the Arrow function?

Arrow functions cannot be used as methods or constructors, so we can not create objects of the Arrow function.
You cannot access the arguments object inside of an arrow function.
Arrow functions must be defined above where they’re being invoked.

✋ What are the types of Errors?

RangeError – occurs when a numeric variable or parameter is outside of its valid range.
ReferenceError – occurs when de-referencing an invalid reference.
SyntaxError – Creates an instance representing a syntax error.
TypeError – occurs when a variable or parameter is not of a valid type.

✋ What is form validation?

When we work on any form, we mostly see below errors during the process.

“This field is required” (You can’t leave this field blank).
“Please enter your phone number in the format xxx-xxxx” (A specific data format is required for it to be considered valid).
“Please enter a valid email address” (the data you entered is not in the right format).
“Your password needs to be between 8 and 30 characters long and contain one uppercase letter, one symbol, and a number.” (A very specific data format is required for your data).

This is called form validation. When you enter data, the browser and/or the web server will check to see that the data is in the correct format and within the constraints set by the application. Validation done in the browser is called client-side validation, while validation done on the server is called server-side.

💡 JAVASCRIPT INTERVIEW QUESTIONS

✔ JavaScript Top Interview questions & Answers You should know

✔ JavaScript Interview Questions & Answers for Experienced – Part 2

✔ JavaScript Interview Question to Write Programs for Experienced – Part 1

✔ JavaScript Interview Questions & Answers for Experienced – Part 1

✔ Top Interview Questions and Answer of HTML 5 Canvas

✔ JavaScript Console Interview Questions | Input Output Program

✔ JavaScript Hoisting Interview Questions & Answers | Console Programs

Top 30 JavaScript Interview Questions

Leave a Reply

Your email address will not be published.