Javascript interview questions and answers
Introduction
We have covered most asked interview questions and their answers, definetely this page will be help if you are preparing for the interview. Please bookmark yourself for your current or future reference.
- What is IIFE ?
- What is hoisting ?
- What are the different ways of creating variables in Javascript ?
- what is Arrow functions ?
- How to extract unique value from an Array
- What is currying ?
- How to create object in Javascript ?
- What are the different type of client side storages and its differences.
- What is the new way of using window object in Javascript and provide example ?
- How to check a number is Amstrong or not
-
What is IIFE ?
Immediate invoke function expression is a function this will execute right after the declartion, An IIFE can be avoiding the variable hoisting within the blocks. It is also called as self executing anonymous functions.
syntax
(function () { // logic goes here })();
-
What is Hoisting ?
Hoisting is moving the declaration of variable and function to the top of the current scope.
Why hoisting is used ?
Hoisting allows you to use the function and variable before they are declared.
How to prevent hoising ?
After the release of ES6, two new featurea have introduced such as Let and Const. If the variable or function declared any of these will prevent the hoisting, because these two has block scope and the
var
has globally scoped. -
What are the different ways of creating variables in Javascript ?
Before ES6 in Javascript var keyword mainly used, but after the ES6 release other two way of declaration is introduced, that is Let and Const.
The existing keyword
var
have one limitation because it has global scope and there is a chance for overwrittern the value from other places and also can use it before declaration.var name = "abc"; var name = 123; // will not throw any error country = "Mexico"; // will not throw any error about declaration because it is hoisted var country;
The latest keywords let and const has block scoped, So it will not be hoisted.
Let - The let keyword cannot be redeclared, It will not be allow us to use it before declaration.
let name = "abc"; let name = 123; // will throw the error, Let keyword won't allow to redeclare country = "Mexico"; // will throw error because cannot be able to use it before declaration let country;
Const - The const keyword cannot be redeclared and reassigned, It will not be allow us to use it before declaration.
const name = 'abc' name = 'cde' // will throw the error, // const keyword won't allow to reassign the value const name = 123 // will throw the error, // const keyword won't allow to redeclare country = 'Mexico' // will throw error, // because cannot be able to use it before declaration const country
-
What is Arrow functions ?
Arrow function is an another feature of ES6, this is used to write the function shorter. Arrow functions are defined using the fat arrow (=>) notation.const add = (number1, number2) => number1 + number2;
-
How to extract unique value from an array in Javascript ?
There are many ways to find the unique values from an array, but we have to apply more lines of code.
Other than the longer steps we can use Set to find the unique numbers in one line of code.
const arr = [1, 2, 3, 4, 1, 1, 2, 3]; const uniqueArray = Array.from(new Set(arr)); // [1, 2, 3, 4]
-
What is currying ?
Currying in JavaScript transforms a function with multiple arguments into a nested series of functions, each taking a single argument.What are the benefits of currying?
Curried functions can make code more readable and expressive by breaking down complex logic into smaller, more manageable pieces. This can make it easier for developers to understand and maintain code. Currying allows for more flexibility in the way that functions are composed.
function calculateVolume(length) { return function (breadth) { return function (height) { return length * breadth * height; }; }; } console.log(calculateVolume(4)(5)(6));
-
How to create object in Javascript ?
Javascript is not a class based object-oriented language. But it still has ways of using object oriented programming. (object oriented javascript)
There are many ways to create objects in javascript as below
1. Object constructor:
The traditional way to create an empty object is using the Object constructor. But currently this approach is not recommended.
var object = new Object();
2. Object's create method:
The create method of Object creates a new object by passing the prototype of object as a parameter
var object = Object.create(null);
3. Object literal syntax:
The object literal syntax (or object initializer), is a comma-separated set of name-value pairswrapped in curly braces.
var object = { name: "Mr. ABC" age: 34 }; Object literal property values can be of any data type, including array, function, and nested object.
Note: This is an easiest way to create an object
4. Function constructor: Create any function and apply the new operator to create object instances,
function Person(name) { this.name = name; this.age = 21; } var object = new Person("Mr. ABC");
5. Function constructor with prototype:
This is similar to function constructor but it uses prototype for their properties and methods,
function Person() {} Person.prototype.name = "Mr. ABC"; var object = new Person();
This is equivalent to an instance created with an object create method with a functionprototype and then call that function with an instance and parameters as arguments.
function func {}; new func(x, y, z);
(OR)
// Create a new instance using function prototype. var newInstance = Object.create(func.prototype) // Call the function var result = func.call(newInstance, x, y, z), // If the result is a non-null object then use it otherwise just use the new instance. console.log(result && typeof result === 'object' ? result : newInstance);
6. ES6 Class syntax: ES6 introduces class feature to create the objects
class Person { constructor(name) { this.name = name; } } var object = new Person("Mr. ABC");
7. Singleton pattern:
A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance and this way one can ensure that they don't accidentally create multiple instances.
var object = new (function () { this.name = "Mr. ABC"; })();
-
What are the different type of client side storages and its differences.
There are 3 types of client side storages are available, namely Cookie, local storage and session storage. Each 3 type of client storages are more powerful in their feature.Feature Cookie Local storage Session storage Availability Both server and client side Only at client side Only at client side Life time Available until as configured Until deleted or clear browser data Until closing the tab SSL Yes No No Maximum storage 4 KB 5 MB 5 MB -
What is the new way of using window object in Javascript and provide example ?
The globalThis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. Unlike similar properties such as window and self , it's guaranteed to work in window and non-window contexts.globalThis?.window.location.href;
-
How to check a number is Amstrong or not
What is amstrong number
if the sum of its own digits raised to the power number of digits gives the number itself.
function amstrong(num) { let num1 = num; let sum = 0; while (num > 0) { rem = num % 10; sum = sum + Math.pow(rem, num1.toString().length); num = parseInt(num / 10); } if (sum == num1) { console.log(num + " is Armstrong"); } else { console.log(num + " is not Armstrong"); } } amstrong(153); amstrong(154);
Result
"153 is Armstrong"; "154 is not Armstrong";
You might have doubt how 153 is Armstrong and why 154 is not.
153 = (1* 1* 1)+(5 _ 5_ 5)+(3* 3* 3)
where:
(1* 1* 1)=1
(5* 5* 5)=125
(3* 3* 3)=27
So:
1+125+27=153
More Stories
Cross-Origin Resource Sharing (CORS) is a security feature that lets a web page from one domain request resources from a different domain
SVG elements will not add the accessibility atttributes by default, so that will fail to describe by itself, and the NVDA and other screen reader required these attributes to work.
Despite being acquainted with git, many developers struggle to resolve these conflicts due to a lack of understanding of how to pull the conflict details into their local machines.
Firebase Authentication is one of its gems, allowing you to add user authentication effortlessly. It's secure, reliable, and comes with Google's seal of approval.
Why am I getting an auth/invalid-api-key error when setting the Firebase values in the environment variable on NextJS ?
Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none.
Easist way of downloading the SVG file as PNG file is done using javascript snippet
To keep the code is safe and distrubuted between multiple resources that been achieved with the help of GIT
The importance of the http response headers are highly needed to protect the websites from hackers. If you poorly managed the response header then one day the website will be compromise to the hacker.
An HTTP header is a response by a web server to a browser that is trying to access a web page.
Application Insights is an feature of Azure Monitor and it provides application performance monitoring features. APM tools are very useful to analyse applications from development, testing and production release.
A lazy function lets you defer the loading of a components code until it is rendered for the first time. Before, it will remain in the bundle. So that we can reduce the load of the application.
we are displaying these emojis with the help of ASCII code and it is not that easy to remember because its a mix of numeric and special characters.
ES6 or the ECMAScript 2015 is the major edition of ECMAScript language, it introduced several new features which are very special to the developers
what are the new features among the various versions of ECMA script and what is difference
We can squash the number of commits from a git branch
Your focus-trap must have at least one container with at least one tabbable node in it at all times, when using dialog or modal in ReactJS or other front-end framework
Writing test cases for modal popup in jest
Cannot read property location of undefined, this is an common test cases error in react jest while using useLocation hook in your react component
There is a common problem when parsing the markdown file the ID attribute is missing in the element, here we found a solution to fix/overcome
It is basicall demonstrating how to find the fibanocci, amstrong, prime numbers and pyramid pattern using javascript.
Markdown is a lightweight markup language that you can use to add formatting elements to plaintext text documents.
There are few development tips for Javascript array operation, these tips will reduce your development time.
For every website the Sitemap will be playing important role for SEO performance. In Ecommerce and other consumer websites also SEO have important role for developing their revenue.
This question is very usual, to get solve this issue by using the browser property user agent to check whether the device type.
What are the possible ways to create objects in JavaScript, The traditional way to create an empty object is using the Object constructor. But currently this approach is not recommended.