Part-3 : 500 JavaScript Important Questions with Answers and Explanation
201-300 JS questions
JavaScript Interview Questions & Answers
Table of Contents
How can you get the list of keys of any object
You can use the
Object.keys()
method which is used to return an array of a given object's own property names, in the same order as we get with a normal loop. For example, you can get the keys of a user object,const user = { name: 'John', gender: 'male', age: 40 }; console.log(Object.keys(user)); //['name', 'gender', 'age']
How do you create an object with prototype
The Object.create() method is used to create a new object with the specified prototype object and properties. i.e, It uses an existing object as the prototype of the newly created object. It returns a new object with the specified prototype object and properties.
const user = { name: 'John', printInfo: function () { console.log(`My name is ${this.name}.`); } }; const admin = Object.create(user); admin.name = "Nick"; // Remember that "name" is a property set on "admin" but not on "user" object admin.printInfo(); // My name is Nick
What is a WeakSet
WeakSet is used to store a collection of weakly(weak references) held objects. The syntax would be as follows,
new WeakSet([iterable]);
Let's see the below example to explain it's behavior,
var ws = new WeakSet(); var user = {}; ws.add(user); ws.has(user); // true ws.delete(user); // removes user from the set ws.has(user); // false, user has been removed
What are the differences between WeakSet and Set
The main difference is that references to objects in Set are strong while references to objects in WeakSet are weak. i.e, An object in WeakSet can be garbage collected if there is no other reference to it. Other differences are,
- Sets can store any value Whereas WeakSets can store only collections of objects
- WeakSet does not have size property unlike Set
- WeakSet does not have methods such as clear, keys, values, entries, forEach.
- WeakSet is not iterable.
List down the collection of methods available on WeakSet
Below are the list of methods available on WeakSet,
- add(value): A new object is appended with the given value to the weakset
- delete(value): Deletes the value from the WeakSet collection.
- has(value): It returns true if the value is present in the WeakSet Collection, otherwise it returns false.
- length(): It returns the length of weakSetObject Let's see the functionality of all the above methods in an example,
var weakSetObject = new WeakSet(); var firstObject = {}; var secondObject = {}; // add(value) weakSetObject.add(firstObject); weakSetObject.add(secondObject); console.log(weakSetObject.has(firstObject)); //true console.log(weakSetObject.length()); //2 weakSetObject.delete(secondObject);
What is a WeakMap
The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. In this case, keys must be objects and the values can be arbitrary values. The syntax is looking like as below,
new WeakMap([iterable])
Let's see the below example to explain it's behavior,
var ws = new WeakMap(); var user = {}; ws.set(user); ws.has(user); // true ws.delete(user); // removes user from the map ws.has(user); // false, user has been removed
What are the differences between WeakMap and Map
The main difference is that references to key objects in Map are strong while references to key objects in WeakMap are weak. i.e, A key object in WeakMap can be garbage collected if there is no other reference to it. Other differences are,
- Maps can store any key type Whereas WeakMaps can store only collections of key objects
- WeakMap does not have size property unlike Map
- WeakMap does not have methods such as clear, keys, values, entries, forEach.
- WeakMap is not iterable.
List down the collection of methods available on WeakMap
Below are the list of methods available on WeakMap,
- set(key, value): Sets the value for the key in the WeakMap object. Returns the WeakMap object.
- delete(key): Removes any value associated to the key.
- has(key): Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.
- get(key): Returns the value associated to the key, or undefined if there is none. Let's see the functionality of all the above methods in an example,
var weakMapObject = new WeakMap(); var firstObject = {}; var secondObject = {}; // set(key, value) weakMapObject.set(firstObject, 'John'); weakMapObject.set(secondObject, 100); console.log(weakMapObject.has(firstObject)); //true console.log(weakMapObject.get(firstObject)); // John weakMapObject.delete(secondObject);
What is the purpose of uneval
The uneval() is an inbuilt function which is used to create a string representation of the source code of an Object. It is a top-level function and is not associated with any object. Let's see the below example to know more about it's functionality,
var a = 1; uneval(a); // returns a String containing 1 uneval(function user() {}); // returns "(function user(){})"
How do you encode an URL
The encodeURI() function is used to encode complete URI which has special characters except (, / ? : @ & = + $ #) characters.
var uri = 'https://mozilla.org/?x=шеллы'; var encoded = encodeURI(uri); console.log(encoded); // https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B
How do you decode an URL
The decodeURI() function is used to decode a Uniform Resource Identifier (URI) previously created by encodeURI().
var uri = 'https://mozilla.org/?x=шеллы'; var encoded = encodeURI(uri); console.log(encoded); // https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B try { console.log(decodeURI(encoded)); // "https://mozilla.org/?x=шеллы" } catch(e) { // catches a malformed URI console.error(e); }
How do you print the contents of web page
The window object provided a print() method which is used to print the contents of the current window. It opens a Print dialog box which lets you choose between various printing options. Let's see the usage of print method in an example,
<input type="button" value="Print" onclick="window.print()" />
Note: In most browsers, it will block while the print dialog is open.
What is the difference between uneval and eval
The
uneval
function returns the source of a given object; whereas theeval
function does the opposite, by evaluating that source code in a different memory area. Let's see an example to clarify the difference,var msg = uneval(function greeting() { return 'Hello, Good morning'; }); var greeting = eval(msg); greeting(); // returns "Hello, Good morning"
What is an anonymous function
An anonymous function is a function without a name! Anonymous functions are commonly assigned to a variable name or used as a callback function. The syntax would be as below,
function (optionalParameters) { //do something } const myFunction = function(){ //Anonymous function assigned to a variable //do something }; [1, 2, 3].map(function(element){ //Anonymous function used as a callback function //do something });
Let's see the above anonymous function in an example,
var x = function (a, b) {return a * b}; var z = x(5, 10); console.log(z); // 50
What is the precedence order between local and global variables
A local variable takes precedence over a global variable with the same name. Let's see this behavior in an example.
var msg = "Good morning"; function greeting() { msg = "Good Evening"; console.log(msg); } greeting();
What are javascript accessors
ECMAScript 5 introduced javascript object accessors or computed properties through getters and setters. Getters uses the
get
keyword whereas Setters uses theset
keyword.var user = { firstName: "John", lastName : "Abraham", language : "en", get lang() { return this.language; } set lang(lang) { this.language = lang; } }; console.log(user.lang); // getter access lang as en user.lang = 'fr'; console.log(user.lang); // setter used to set lang as fr
How do you define property on Object constructor
The Object.defineProperty() static method is used to define a new property directly on an object, or modify an existing property on an object, and returns the object. Let's see an example to know how to define property,
const newObject = {}; Object.defineProperty(newObject, 'newProperty', { value: 100, writable: false }); console.log(newObject.newProperty); // 100 newObject.newProperty = 200; // It throws an error in strict mode due to writable setting
What is the difference between get and defineProperty
Both have similar results until unless you use classes. If you use
get
the property will be defined on the prototype of the object whereas usingObject.defineProperty()
the property will be defined on the instance it is applied to.What are the advantages of Getters and Setters
Below are the list of benefits of Getters and Setters,
- They provide simpler syntax
- They are used for defining computed properties, or accessors in JS.
- Useful to provide equivalence relation between properties and methods
- They can provide better data quality
- Useful for doing things behind the scenes with the encapsulated logic.
Can I add getters and setters using defineProperty method
Yes, You can use the
Object.defineProperty()
method to add Getters and Setters. For example, the below counter object uses increment, decrement, add and subtract properties,var obj = {counter : 0}; // Define getters Object.defineProperty(obj, "increment", { get : function () {this.counter++;} }); Object.defineProperty(obj, "decrement", { get : function () {this.counter--;} }); // Define setters Object.defineProperty(obj, "add", { set : function (value) {this.counter += value;} }); Object.defineProperty(obj, "subtract", { set : function (value) {this.counter -= value;} }); obj.add = 10; obj.subtract = 5; console.log(obj.increment); //6 console.log(obj.decrement); //5
What is the purpose of switch-case
The switch case statement in JavaScript is used for decision making purposes. In a few cases, using the switch case statement is going to be more convenient than if-else statements. The syntax would be as below,
switch (expression) { case value1: statement1; break; case value2: statement2; break; . . case valueN: statementN; break; default: statementDefault; }
The above multi-way branch statement provides an easy way to dispatch execution to different parts of code based on the value of the expression.
What are the conventions to be followed for the usage of switch case
Below are the list of conventions should be taken care,
- The expression can be of type either number or string.
- Duplicate values are not allowed for the expression.
- The default statement is optional. If the expression passed to switch does not match with any case value then the statement within default case will be executed.
- The break statement is used inside the switch to terminate a statement sequence.
- The break statement is optional. But if it is omitted, the execution will continue on into the next case.
What are primitive data types
A primitive data type is data that has a primitive value (which has no properties or methods). There are 5 types of primitive data types.
- string
- number
- boolean
- null
- undefined
What are the different ways to access object properties
There are 3 possible ways for accessing the property of an object.
- Dot notation: It uses dot for accessing the properties
objectName.property
- Square brackets notation: It uses square brackets for property access
objectName["property"]
- Expression notation: It uses expression in the square brackets
objectName[expression]
What are the function parameter rules
JavaScript functions follow below rules for parameters,
- The function definitions do not specify data types for parameters.
- Do not perform type checking on the passed arguments.
- Do not check the number of arguments received. i.e, The below function follows the above rules,
function functionName(parameter1, parameter2, parameter3) { console.log(parameter1); // 1 } functionName(1);
What is an error object
An error object is a built in error object that provides error information when an error occurs. It has two properties: name and message. For example, the below function logs error details,
try { greeting("Welcome"); } catch(err) { console.log(err.name + "<br>" + err.message); }
When you get a syntax error
A SyntaxError is thrown if you try to evaluate code with a syntax error. For example, the below missing quote for the function parameter throws a syntax error
try { eval("greeting('welcome)"); // Missing ' will produce an error } catch(err) { console.log(err.name); }
What are the different error names from error object
There are 6 different types of error names returned from error object, | Error Name | Description | |---- | --------- | EvalError | An error has occurred in the eval() function | | RangeError | An error has occurred with a number "out of range" | | ReferenceError | An error due to an illegal reference| | SyntaxError | An error due to a syntax error| | TypeError | An error due to a type error | | URIError | An error due to encodeURI() |
What are the various statements in error handling
Below are the list of statements used in an error handling,
- try: This statement is used to test a block of code for errors
- catch: This statement is used to handle the error
- throw: This statement is used to create custom errors.
- finally: This statement is used to execute code after try and catch regardless of the result.
What are the two types of loops in javascript
- Entry Controlled loops: In this kind of loop type, the test condition is tested before entering the loop body. For example, For Loop and While Loop comes under this category.
- Exit Controlled Loops: In this kind of loop type, the test condition is tested or evaluated at the end of the loop body. i.e, the loop body will execute at least once irrespective of test condition true or false. For example, do-while loop comes under this category.
What is nodejs
Node.js is a server-side platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications. It is an event-based, non-blocking, asynchronous I/O runtime that uses Google's V8 JavaScript engine and libuv library.
What is an Intl object
The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. It provides access to several constructors and language sensitive functions.
How do you perform language specific date and time formatting
You can use the
Intl.DateTimeFormat
object which is a constructor for objects that enable language-sensitive date and time formatting. Let's see this behavior with an example,var date = new Date(Date.UTC(2019, 07, 07, 3, 0, 0)); console.log(new Intl.DateTimeFormat('en-GB').format(date)); // 07/08/2019 console.log(new Intl.DateTimeFormat('en-AU').format(date)); // 07/08/2019
What is an Iterator
An iterator is an object which defines a sequence and a return value upon its termination. It implements the Iterator protocol with a
next()
method which returns an object with two properties:value
(the next value in the sequence) anddone
(which is true if the last value in the sequence has been consumed).How does synchronous iteration works
Synchronous iteration was introduced in ES6 and it works with below set of components,
Iterable: It is an object which can be iterated over via a method whose key is Symbol.iterator. Iterator: It is an object returned by invoking
[Symbol.iterator]()
on an iterable. This iterator object wraps each iterated element in an object and returns it vianext()
method one by one. IteratorResult: It is an object returned bynext()
method. The object contains two properties; thevalue
property contains an iterated element and thedone
property determines whether the element is the last element or not.Let's demonstrate synchronous iteration with an array as below,
const iterable = ['one', 'two', 'three']; const iterator = iterable[Symbol.iterator](); console.log(iterator.next()); // { value: 'one', done: false } console.log(iterator.next()); // { value: 'two', done: false } console.log(iterator.next()); // { value: 'three', done: false } console.log(iterator.next()); // { value: 'undefined, done: true }
What is an event loop
The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start processing the event loop until the async function has finished executing the code. Note: It allows Node.js to perform non-blocking I/O operations even though JavaScript is single-threaded.
What is call stack
Call Stack is a data structure for javascript interpreters to keep track of function calls in the program. It has two major actions,
- Whenever you call a function for its execution, you are pushing it to the stack.
- Whenever the execution is completed, the function is popped out of the stack.
Let's take an example and it's state representation in a diagram format
function hungry() { eatFruits(); } function eatFruits() { return "I'm eating fruits"; } // Invoke the `hungry` function hungry();
The above code processed in a call stack as below,
- Add the
hungry()
function to the call stack list and execute the code. - Add the
eatFruits()
function to the call stack list and execute the code. - Delete the
eatFruits()
function from our call stack list. - Delete the
hungry()
function from the call stack list since there are no items anymore.
What is an event queue
What is a decorator
A decorator is an expression that evaluates to a function and that takes the target, name, and decorator descriptor as arguments. Also, it optionally returns a decorator descriptor to install on the target object. Let's define admin decorator for user class at design time,
function admin(isAdmin) { return function(target) { target.isAdmin = isAdmin; } } @admin(true) class User() { } console.log(User.isAdmin); //true @admin(false) class User() { } console.log(User.isAdmin); //false
What are the properties of Intl object
Below are the list of properties available on Intl object,
- Collator: These are the objects that enable language-sensitive string comparison.
- DateTimeFormat: These are the objects that enable language-sensitive date and time formatting.
- ListFormat: These are the objects that enable language-sensitive list formatting.
- NumberFormat: Objects that enable language-sensitive number formatting.
- PluralRules: Objects that enable plural-sensitive formatting and language-specific rules for plurals.
- RelativeTimeFormat: Objects that enable language-sensitive relative time formatting.
What is an Unary operator
The unary(+) operator is used to convert a variable to a number.If the variable cannot be converted, it will still become a number but with the value NaN. Let's see this behavior in an action.
var x = "100"; var y = + x; console.log(typeof x, typeof y); // string, number var a = "Hello"; var b = + a; console.log(typeof a, typeof b, b); // string, number, NaN
How do you sort elements in an array
The sort() method is used to sort the elements of an array in place and returns the sorted array. The example usage would be as below,
var months = ["Aug", "Sep", "Jan", "June"]; months.sort(); console.log(months); // ["Aug", "Jan", "June", "Sep"]
What is the purpose of compareFunction while sorting arrays
The compareFunction is used to define the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. Let's take an example to see the usage of compareFunction,
let numbers = [1, 2, 5, 3, 4]; numbers.sort((a, b) => b - a); console.log(numbers); // [5, 4, 3, 2, 1]
How do you reversing an array
You can use the reverse() method to reverse the elements in an array. This method is useful to sort an array in descending order. Let's see the usage of reverse() method in an example,
let numbers = [1, 2, 5, 3, 4]; numbers.sort((a, b) => b - a); numbers.reverse(); console.log(numbers); // [1, 2, 3, 4 ,5]
How do you find min and max value in an array
You can use
Math.min
andMath.max
methods on array variables to find the minimum and maximum elements within an array. Let's create two functions to find the min and max value with in an array,var marks = [50, 20, 70, 60, 45, 30]; function findMin(arr) { return Math.min.apply(null, arr); } function findMax(arr) { return Math.max.apply(null, arr); } console.log(findMin(marks)); console.log(findMax(marks));
How do you find min and max values without Math functions
You can write functions which loop through an array comparing each value with the lowest value or highest value to find the min and max values. Let's create those functions to find min and max values,
var marks = [50, 20, 70, 60, 45, 30]; function findMin(arr) { var length = arr.length var min = Infinity; while (length--) { if (arr[length] < min) { min = arr[len]; } } return min; } function findMax(arr) { var length = arr.length var max = -Infinity; while (len--) { if (arr[length] > max) { max = arr[length]; } } return max; } console.log(findMin(marks)); console.log(findMax(marks));
What is an empty statement and purpose of it
The empty statement is a semicolon (;) indicating that no statement will be executed, even if JavaScript syntax requires one. Since there is no action with an empty statement you might think that it's usage is quite less, but the empty statement is occasionally useful when you want to create a loop that has an empty body. For example, you can initialize an array with zero values as below,
// Initialize an array a for(int i=0; i < a.length; a[i++] = 0) ;
How do you get metadata of a module
You can use the
import.meta
object which is a meta-property exposing context-specific meta data to a JavaScript module. It contains information about the current module, such as the module's URL. In browsers, you might get different meta data than NodeJS.<script type="module" src="welcome-module.js"></script> console.log(import.meta); // { url: "file:///home/user/welcome-module.js" }
What is a comma operator
The comma operator is used to evaluate each of its operands from left to right and returns the value of the last operand. This is totally different from comma usage within arrays, objects, and function arguments and parameters. For example, the usage for numeric expressions would be as below,
var x = 1; x = (x++, x); console.log(x); // 2
What is the advantage of a comma operator
It is normally used to include multiple expressions in a location that requires a single expression. One of the common usages of this comma operator is to supply multiple parameters in a
for
loop. For example, the below for loop uses multiple expressions in a single location using comma operator,for (var a = 0, b =10; a <= 10; a++, b--)
You can also use the comma operator in a return statement where it processes before returning.
function myFunction() { var a = 1; return (a += 10, a); // 11 }
What is typescript
TypeScript is a typed superset of JavaScript created by Microsoft that adds optional types, classes, async/await, and many other features, and compiles to plain JavaScript. Angular built entirely in TypeScript and used as a primary language. You can install it globally as
npm install -g typescript
Let's see a simple example of TypeScript usage,
function greeting(name: string): string { return "Hello, " + name; } let user = "Sudheer"; console.log(greeting(user));
The greeting method allows only string type as argument.
What are the differences between javascript and typescript
Below are the list of differences between javascript and typescript,
| feature | typescript | javascript | |---- | --------- | ---- | Language paradigm | Object oriented programming language | Scripting language | | Typing support | Supports static typing | It has dynamic typing | | Modules | Supported | Not supported | | Interface | It has interfaces concept | Doesn't support interfaces | | Optional parameters | Functions support optional parameters | No support of optional parameters for functions |
What are the advantages of typescript over javascript
Below are some of the advantages of typescript over javascript,
- TypeScript is able to find compile time errors at the development time only and it makes sures less runtime errors. Whereas javascript is an interpreted language.
- TypeScript is strongly-typed or supports static typing which allows for checking type correctness at compile time. This is not available in javascript.
- TypeScript compiler can compile the .ts files into ES3,ES4 and ES5 unlike ES6 features of javascript which may not be supported in some browsers.
What is an object initializer
An object initializer is an expression that describes the initialization of an Object. The syntax for this expression is represented as a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). This is also known as literal notation. It is one of the ways to create an object.
var initObject = {a: 'John', b: 50, c: {}}; console.log(initObject.a); // John
What is a constructor method
The constructor method is a special method for creating and initializing an object created within a class. If you do not specify a constructor method, a default constructor is used. The example usage of constructor would be as below,
class Employee { constructor() { this.name = "John"; } } var employeeObject = new Employee(); console.log(employeeObject.name); // John
What happens if you write constructor more than once in a class
The "constructor" in a class is a special method and it should be defined only once in a class. i.e, If you write a constructor method more than once in a class it will throw a
SyntaxError
error.class Employee { constructor() { this.name = "John"; } constructor() { // Uncaught SyntaxError: A class may only have one constructor this.age = 30; } } var employeeObject = new Employee(); console.log(employeeObject.name);
How do you call the constructor of a parent class
You can use the
super
keyword to call the constructor of a parent class. Remember thatsuper()
must be called before using 'this' reference. Otherwise it will cause a reference error. Let's the usage of it,class Square extends Rectangle { constructor(length) { super(length, length); this.name = 'Square'; } get area() { return this.width * this.height; } set area(value) { this.area = value; } }
How do you get the prototype of an object
You can use the
Object.getPrototypeOf(obj)
method to return the prototype of the specified object. i.e. The value of the internalprototype
property. If there are no inherited properties thennull
value is returned.const newPrototype = {}; const newObject = Object.create(newPrototype); console.log(Object.getPrototypeOf(newObject) === newPrototype); // true
What happens If I pass string type for getPrototype method
In ES5, it will throw a TypeError exception if the obj parameter isn't an object. Whereas in ES2015, the parameter will be coerced to an
Object
.// ES5 Object.getPrototypeOf('James'); // TypeError: "James" is not an object // ES2015 Object.getPrototypeOf('James'); // String.prototype
How do you set prototype of one object to another
You can use the
Object.setPrototypeOf()
method that sets the prototype (i.e., the internalPrototype
property) of a specified object to another object or null. For example, if you want to set prototype of a square object to rectangle object would be as follows,Object.setPrototypeOf(Square.prototype, Rectangle.prototype); Object.setPrototypeOf({}, null);
How do you check whether an object can be extendable or not
The
Object.isExtensible()
method is used to determine if an object is extendable or not. i.e, Whether it can have new properties added to it or not.const newObject = {}; console.log(Object.isExtensible(newObject)); //true
Note: By default, all the objects are extendable. i.e, The new properties can be added or modified.
How do you prevent an object to extend
The
Object.preventExtensions()
method is used to prevent new properties from ever being added to an object. In other words, it prevents future extensions to the object. Let's see the usage of this property,const newObject = {}; Object.preventExtensions(newObject); // NOT extendable try { Object.defineProperty(newObject, 'newProperty', { // Adding new property value: 100 }); } catch (e) { console.log(e); // TypeError: Cannot define property newProperty, object is not extensible }
What are the different ways to make an object non-extensible
You can mark an object non-extensible in 3 ways,
- Object.preventExtensions
- Object.seal
- Object.freeze
var newObject = {}; Object.preventExtensions(newObject); // Prevent objects are non-extensible Object.isExtensible(newObject); // false var sealedObject = Object.seal({}); // Sealed objects are non-extensible Object.isExtensible(sealedObject); // false var frozenObject = Object.freeze({}); // Frozen objects are non-extensible Object.isExtensible(frozenObject); // false
How do you define multiple properties on an object
The
Object.defineProperties()
method is used to define new or modify existing properties directly on an object and returning the object. Let's define multiple properties on an empty object,const newObject = {}; Object.defineProperties(newObject, { newProperty1: { value: 'John', writable: true }, newProperty2: {} });
What is MEAN in javascript
The MEAN (MongoDB, Express, AngularJS, and Node.js) stack is the most popular open-source JavaScript software tech stack available for building dynamic web apps where you can write both the server-side and client-side halves of the web project entirely in JavaScript.
What Is Obfuscation in javascript
Obfuscation is the deliberate act of creating obfuscated javascript code(i.e, source or machine code) that is difficult for humans to understand. It is something similar to encryption, but a machine can understand the code and execute it. Let's see the below function before Obfuscation,
function greeting() { console.log('Hello, welcome to JS world'); }
And after the code Obfuscation, it would be appeared as below,
eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replace(/^/,String)){while(c--){d[c]=k[c]||c}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('2 1(){0.3(\'4, 7 6 5 8\')}',9,9,'console|greeting|function|log|Hello|JS|to|welcome|world'.split('|'),0,{}))
Why do you need Obfuscation
Below are the few reasons for Obfuscation,
- The Code size will be reduced. So data transfers between server and client will be fast.
- It hides the business logic from outside world and protects the code from others
- Reverse engineering is highly difficult
- The download time will be reduced
What is Minification
Minification is the process of removing all unnecessary characters(empty spaces are removed) and variables will be renamed without changing it's functionality. It is also a type of obfuscation .
What are the advantages of minification
Normally it is recommended to use minification for heavy traffic and intensive requirements of resources. It reduces file sizes with below benefits,
- Decreases loading times of a web page
- Saves bandwidth usages
What are the differences between Obfuscation and Encryption
Below are the main differences between Obfuscation and Encryption,
| Feature | Obfuscation | Encryption | |---- | --------- | ---- | Definition | Changing the form of any data in any other form | Changing the form of information to an unreadable format by using a key | | A key to decode | It can be decoded without any key | It is required | | Target data format | It will be converted to a complex form | Converted into an unreadable format |
What are the common tools used for minification
There are many online/offline tools to minify the javascript files,
- Google's Closure Compiler
- UglifyJS2
- jsmin
- javascript-minifier.com
- prettydiff.com
How do you perform form validation using javascript
JavaScript can be used to perform HTML form validation. For example, if the form field is empty, the function needs to notify, and return false, to prevent the form being submitted. Lets' perform user login in an html form,
<form name="myForm" onsubmit="return validateForm()" method="post"> User name: <input type="text" name="uname"> <input type="submit" value="Submit"> </form>
And the validation on user login is below,
function validateForm() { var x = document.forms["myForm"]["uname"].value; if (x == "") { alert("The username shouldn't be empty"); return false; } }
How do you perform form validation without javascript
You can perform HTML form validation automatically without using javascript. The validation enabled by applying the
required
attribute to prevent form submission when the input is empty.<form method="post"> <input type="text" name="uname" required> <input type="submit" value="Submit"> </form>
Note: Automatic form validation does not work in Internet Explorer 9 or earlier.
What are the DOM methods available for constraint validation
The below DOM methods are available for constraint validation on an invalid input,
- checkValidity(): It returns true if an input element contains valid data.
- setCustomValidity(): It is used to set the validationMessage property of an input element. Let's take an user login form with DOM validations
function myFunction() { var userName = document.getElementById("uname"); if (!userName.checkValidity()) { document.getElementById("message").innerHTML = userName.validationMessage; } else { document.getElementById("message").innerHTML = "Entered a valid username"; } }
What are the available constraint validation DOM properties
Below are the list of some of the constraint validation DOM properties available,
- validity: It provides a list of boolean properties related to the validity of an input element.
- validationMessage: It displays the message when the validity is false.
- willValidate: It indicates if an input element will be validated or not.
What are the list of validity properties
The validity property of an input element provides a set of properties related to the validity of data.
- customError: It returns true, if a custom validity message is set.
- patternMismatch: It returns true, if an element's value does not match its pattern attribute.
- rangeOverflow: It returns true, if an element's value is greater than its max attribute.
- rangeUnderflow: It returns true, if an element's value is less than its min attribute.
- stepMismatch: It returns true, if an element's value is invalid according to step attribute.
- tooLong: It returns true, if an element's value exceeds its maxLength attribute.
- typeMismatch: It returns true, if an element's value is invalid according to type attribute.
- valueMissing: It returns true, if an element with a required attribute has no value.
- valid: It returns true, if an element's value is valid.
Give an example usage of rangeOverflow property
If an element's value is greater than its max attribute then rangeOverflow property returns true. For example, the below form submission throws an error if the value is more than 100,
<input id="age" type="number" max="100"> <button onclick="myOverflowFunction()">OK</button>
function myOverflowFunction() { if (document.getElementById("age").validity.rangeOverflow) { alert("The mentioned age is not allowed"); } }
Is enums feature available in javascript
No, javascript does not natively support enums. But there are different kinds of solutions to simulate them even though they may not provide exact equivalents. For example, you can use freeze or seal on object,
var DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
What is an enum
An enum is a type restricting variables to one value from a predefined set of constants. JavaScript has no enums but typescript provides built-in enum support.
enum Color { RED, GREEN, BLUE }
How do you list all properties of an object
You can use the
Object.getOwnPropertyNames()
method which returns an array of all properties found directly in a given object. Let's the usage of it in an example,const newObject = { a: 1, b: 2, c: 3 }; console.log(Object.getOwnPropertyNames(newObject)); ["a", "b", "c"]
How do you get property descriptors of an object
You can use the
Object.getOwnPropertyDescriptors()
method which returns all own property descriptors of a given object. The example usage of this method is below,const newObject = { a: 1, b: 2, c: 3 }; const descriptorsObject = Object.getOwnPropertyDescriptors(newObject); console.log(descriptorsObject.a.writable); //true console.log(descriptorsObject.a.configurable); //true console.log(descriptorsObject.a.enumerable); //true console.log(descriptorsObject.a.value); // 1
What are the attributes provided by a property descriptor
A property descriptor is a record which has the following attributes
- value: The value associated with the property
- writable: Determines whether the value associated with the property can be changed or not
- configurable: Returns true if the type of this property descriptor can be changed and if the property can be deleted from the corresponding object.
- enumerable: Determines whether the property appears during enumeration of the properties on the corresponding object or not.
- set: A function which serves as a setter for the property
- get: A function which serves as a getter for the property
How do you extend classes
The
extends
keyword is used in class declarations/expressions to create a class which is a child of another class. It can be used to subclass custom classes as well as built-in objects. The syntax would be as below,class ChildClass extends ParentClass { ... }
Let's take an example of Square subclass from Polygon parent class,
class Square extends Rectangle { constructor(length) { super(length, length); this.name = 'Square'; } get area() { return this.width * this.height; } set area(value) { this.area = value; } }
How do I modify the url without reloading the page
The
window.location.url
property will be helpful to modify the url but it reloads the page. HTML5 introduced thehistory.pushState()
andhistory.replaceState()
methods, which allow you to add and modify history entries, respectively. For example, you can use pushState as below,window.history.pushState('page2', 'Title', '/page2.html');
How do you check whether an array includes a particular value or not
The
Array#includes()
method is used to determine whether an array includes a particular value among its entries by returning either true or false. Let's see an example to find an element(numeric and string) within an array.var numericArray = [1, 2, 3, 4]; console.log(numericArray.includes(3)); // true var stringArray = ['green', 'yellow', 'blue']; console.log(stringArray.includes('blue')); //true
How do you compare scalar arrays
You can use length and every method of arrays to compare two scalar(compared directly using ===) arrays. The combination of these expressions can give the expected result,
const arrayFirst = [1,2,3,4,5]; const arraySecond = [1,2,3,4,5]; console.log(arrayFirst.length === arraySecond.length && arrayFirst.every((value, index) => value === arraySecond[index])); // true `
If you would like to compare arrays irrespective of order then you should sort them before,
const arrayFirst = [2,3,1,4,5]; const arraySecond = [1,2,3,4,5]; console.log(arrayFirst.length === arraySecond.length && arrayFirst.sort().every((value, index) => value === arraySecond[index])); //true `
How to get the value from get parameters
The
new URL()
object accepts the url string andsearchParams
property of this object can be used to access the get parameters. Remember that you may need to use polyfill orwindow.location
to access the URL in older browsers(including IE).let urlString = "http://www.some-domain.com/about.html?x=1&y=2&z=3"; //window.location.href let url = new URL(urlString); let parameterZ = url.searchParams.get("z"); console.log(parameterZ); // 3
How do you print numbers with commas as thousand separators
You can use the
Number.prototype.toLocaleString()
method which returns a string with a language-sensitive representation such as thousand separator,currency etc of this number.function convertToThousandFormat(x){ return x.toLocaleString(); // 12,345.679 } console.log(convertToThousandFormat(12345.6789));
What is the difference between java and javascript
Both are totally unrelated programming languages and no relation between them. Java is statically typed, compiled, runs on its own VM. Whereas Javascript is dynamically typed, interpreted, and runs in a browser and nodejs environments. Let's see the major differences in a tabular format, | Feature | Java | JavaScript | |---- | ---- | ----- | Typed | It's a strongly typed language | It's a dynamic typed language | | Paradigm | Object oriented programming | Prototype based programming | | Scoping | Block scoped | Function-scoped | | Concurrency | Thread based | event based | | Memory | Uses more memory | Uses less memory. Hence it will be used for web pages |
Is javascript supports namespace
JavaScript doesn’t support namespace by default. So if you create any element(function, method, object, variable) then it becomes global and pollutes the global namespace. Let's take an example of defining two functions without any namespace,
function func1() { console.log("This is a first definition"); } function func1() { console.log("This is a second definition"); } func1(); // This is a second definition
It always calls the second function definition. In this case, namespace will solve the name collision problem.
How do you declare namespace
Even though JavaScript lacks namespaces, we can use Objects , IIFE to create namespaces.
- Using Object Literal Notation: Let's wrap variables and functions inside an Object literal which acts as a namespace. After that you can access them using object notation
var namespaceOne = { function func1() { console.log("This is a first definition"); } } var namespaceTwo = { function func1() { console.log("This is a second definition"); } } namespaceOne.func1(); // This is a first definition namespaceTwo.func1(); // This is a second definition
- Using IIFE (Immediately invoked function expression): The outer pair of parentheses of IIFE creates a local scope for all the code inside of it and makes the anonymous function a function expression. Due to that, you can create the same function in two different function expressions to act as a namespace.
(function() { function fun1(){ console.log("This is a first definition"); } fun1(); }()); (function() { function fun1(){ console.log("This is a second definition"); } fun1(); }());
- Using a block and a let/const declaration: In ECMAScript 6, you can simply use a block and a let declaration to restrict the scope of a variable to a block.
{ let myFunction= function fun1(){ console.log("This is a first definition"); } myFunction(); } //myFunction(): ReferenceError: myFunction is not defined. { let myFunction= function fun1(){ console.log("This is a second definition"); } myFunction(); } //myFunction(): ReferenceError: myFunction is not defined.
How do you invoke javascript code in an iframe from parent page
Initially iFrame needs to be accessed using either
document.getElementBy
orwindow.frames
. After thatcontentWindow
property of iFrame gives the access for targetFunctiondocument.getElementById('targetFrame').contentWindow.targetFunction(); window.frames[0].frameElement.contentWindow.targetFunction(); // Accessing iframe this way may not work in latest versions chrome and firefox
How do get the timezone offset from date
You can use the
getTimezoneOffset
method of the date object. This method returns the time zone difference, in minutes, from current locale (host system settings) to UTCvar offset = new Date().getTimezoneOffset(); console.log(offset); // -480
How do you load CSS and JS files dynamically
You can create both link and script elements in the DOM and append them as child to head tag. Let's create a function to add script and style resources as below,
function loadAssets(filename, filetype) { if (filetype == "css") { // External CSS file var fileReference = document.createElement("link") fileReference.setAttribute("rel", "stylesheet"); fileReference.setAttribute("type", "text/css"); fileReference.setAttribute("href", filename); } else if (filetype == "js") { // External JavaScript file var fileReference = document.createElement('script'); fileReference.setAttribute("type", "text/javascript"); fileReference.setAttribute("src", filename); } if (typeof fileReference != "undefined") document.getElementsByTagName("head")[0].appendChild(fileReference) }
What are the different methods to find HTML elements in DOM
If you want to access any element in an HTML page, you need to start with accessing the document object. Later you can use any of the below methods to find the HTML element,
- document.getElementById(id): It finds an element by Id
- document.getElementsByTagName(name): It finds an element by tag name
- document.getElementsByClassName(name): It finds an element by class name
What is jQuery
jQuery is a popular cross-browser JavaScript library that provides Document Object Model (DOM) traversal, event handling, animations and AJAX interactions by minimizing the discrepancies across browsers. It is widely famous with its philosophy of “Write less, do more”. For example, you can display welcome message on the page load using jQuery as below,
$(document).ready(function(){ // It selects the document and apply the function on page load alert('Welcome to jQuery world'); });
Note: You can download it from jquery's official site or install it from CDNs, like google.
What is V8 JavaScript engine
V8 is an open source high-performance JavaScript engine used by the Google Chrome browser, written in C++. It is also being used in the node.js project. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linux systems that use x64, IA-32, ARM, or MIPS processors. Note: It can run standalone, or can be embedded into any C++ application.
Why do we call javascript as dynamic language
JavaScript is a loosely typed or a dynamic language because variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned/reassigned with values of all types.
let age = 50; // age is a number now age = 'old'; // age is a string now age = true; // age is a boolean
What is a void operator
The
void
operator evaluates the given expression and then returns undefined(i.e, without returning value). The syntax would be as below,void (expression) void expression
Let's display a message without any redirection or reload
<a href="javascript:void(alert('Welcome to JS world'))">Click here to see a message</a>
Note: This operator is often used to obtain the undefined primitive value, using "void(0)".
How to set the cursor to wait
The cursor can be set to wait in JavaScript by using the property "cursor". Let's perform this behavior on page load using the below function.
function myFunction() { window.document.body.style.cursor = "wait"; }
and this function invoked on page load
<body onload="myFunction()">