211. ### How do you decode an URL?
The decodeURI() function is used to decode a Uniform Resource Identifier (URI) previously created by encodeURI().
```javascript
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);
}
```
212. ### How do you print the contents of web page?
The window object provided print() method which is used to prints the contents of the current window. It opens Print dialog box which lets you choose between various printing options. Let's see the usage of print method in an example,
```html
<input type="button" value="Print" onclick="window.print()" />
```
**Note:** In most browsers, it will block while the print dialog is open.
213. ### What is the difference between uneval and eval?
The `uneval` function returns the source of a given object; whereas the `eval` function does the opposite, by evaluating that source code in a different memory area. Let's see an example to clarify the difference,
```javascript
var msg = uneval(function greeting() { return 'Hello, Good morning'; });
var greeting = eval(msg);
greeting(); // returns "Hello, Good morning"
```
214. ### 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,
```javascript
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,
```javascript
var x = function (a, b) {return a * b};
var z = x(5, 10);
console.log(z); // 50
```
215. ### 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.
```javascript
var msg = "Good morning";
function greeting() {
msg = "Good Evening";
console.log(msg);
}
greeting();
```
216. ### What are javascript accessors?
ECMAScript 5 introduced javascript object accessors or computed properties through getters and setters. Getters uses `get` keyword whereas Setters uses `set` keyword.
```javascript
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
```
217. ### 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 modifies an existing property on an object, and returns the object. Let's see an example to know how to define property,
```javascript
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
```
218. ### What is the difference between get and defineProperty?
Both has similar results until unless you use classes. If you use `get` the property will be defined on the prototype of the object whereas using `Object.defineProperty()` the property will be defined on the instance it is applied to.
219. ### What are the advantages of Getters and Setters?
Below are the list of benefits of Getters and Setters,
1. They provide simpler syntax
2. They are used for defining computed properties, or accessors in JS.
3. Useful to provide equivalence relation between properties and methods
4. They can provide better data quality
5. Useful for doing things behind the scenes with the encapsulated logic.
220. ### Can I add getters and setters using defineProperty method?
Yes, You can use `Object.defineProperty()` method to add Getters and Setters. For example, the below counter object uses increment, decrement, add and substract properties,
```javascript
var counterObj = {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
```
221. ### What is the purpose of switch-case?
The switch case statement in JavaScript is used for decision making purposes. In few cases, using the switch case statement is going to be more convenient than if-else statements. The syntax would be as below,
```javascript
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.
222. ### What are the conventions to be followed for the usage of switch case?
Below are the list of conventions should be taken care,
1. The expression can be of type either number or string.
2. Duplicate values are not allowed for the expression.
3. The default statement is optional. If the expression passed to switch does not matches with any case value then the statement within default case will be executed.
4. The break statement is used inside the switch to terminate a statement sequence.
5. The break statement is optional. But if it omitted, the execution will continue on into the next case.
223. ### 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.
1. string
2. number
3. boolean
4. null
5. undefined
224. ### What are the different ways to access object properties?
There are 3 possible ways for accessing the property of an object.
1. **Dot notation:** It uses dot for accessing the properties
```javascript
objectName.property
```
2. **Square brackets notation:** It uses square brackets for property access
```javascript
objectName["property"]
```
3. **Expression notation:** It uses expression in the square brackets
```javascript
objectName[expression]
```
225. ### What are the function parameter rules?
JavaScript functions follow below rules for parameters,
1. The function definitions do not specify data types for parameters.
2. Do not perform type checking on the passed arguments.
3. Do not check the number of arguments received.
i.e, The below function follows the above rules,
```javascript
function functionName(parameter1, parameter2, parameter3) {
console.log(parameter1); // 1
}
functionName(1);
```
226. ### 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,
```javascript
try {
greeting("Welcome");
}
catch(err) {
console.log(err.name + "<br>" + err.message);
}
```
227. ### 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
```javascript
try {
eval("greeting('welcome)"); // Missing ' will produce an error
}
catch(err) {
console.log(err.name);
}
```
228. ### 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() |
229. ### What are the various statements in error handling?
Below are the list of statements used in an error handling,
1. **try:** This statement is used to test a block of code for errors
2. **catch:** This statement is used to handle the error
3. **throw:** This statement is used to create custom errors.
4. **finally:** This statement is used to execute code after try and catch regardless of the result.
230. ### What are the two types of loops in javascript?
1. **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.
2. **Exit Controlled Loops:** In this kind of loop typpe, the test condition is tested or evaluated at the end of loop body. i.e, the loop body will execute atleast once irrespective of test condition true or false. For example, do-while loop comes under this category.
231. ### 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.
232. ### 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 an access to several constructors and language sensitive functions.
233. ### How do you perform language specific date and time formatting?
You can use `Intl.DateTimeFormat` object which is constructor for objects that enable language-sensitive date and time formatting. Let's see this behavior with an example,
```javascript
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
```
234. ### 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) and done (which is true if the last value in the sequence has been consumed).
235. ### 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 async function has finished executing the code.
**Note:** It allows Node.js to perform non-blocking I/O operations eventhough JavaScript is single-threaded.
236. ### What is call stack?
237. ### What is an event queue?
238. ### 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,
```javascript
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
```
239. ### What are the properties of Intl object?
Below are the list of properties available on Intl object,
1. **Collator:** These are the objects that enable language-sensitive string comparison.
2. **DateTimeFormat:** These are the objects that enable language-sensitive date and time formatting.
3. **ListFormat:** These are the objects that enable language-sensitive list formatting.
4. **NumberFormat:** Objects that enable language-sensitive number formatting.
5. **PluralRules:** Objects that enable plural-sensitive formatting and language-specific rules for plurals.
6. **RelativeTimeFormat:** Objects that enable language-sensitive relative time formatting.
240. ### 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.
```javascrippt
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
```
241. ### 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,
```javascript
var months = ["Aug", "Sep", "Jan", "June"];
months.sort();
console.log(months); // ["Aug", "Jan", "June", "Sep"]
```
242. ### 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,
```javascript
let numbers = [1, 2, 5, 3, 4];
numbers.sort((a, b) => b - a);
console.log(numbers); // [5, 4, 3, 2, 1]
```
243. ### How do you reversing an array?
You can use reverse() method is used 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,
```javascript
let numbers = [1, 2, 5, 3, 4];
numbers.sort((a, b) => b - a);
numbers.reverse();
console.log(numbers); // [1, 2, 3, 4 ,5]
```
244. ### How do you find min and max value in an array?
You can use `Math.min` and `Math.max` methods on array variable to find the minimum and maximum elements with in an array. Let's create two functions to find the min and max value with in an array,
```javascript
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));
```
245. ### How do you find min and max values without Math functions?
You can write functions which loops 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 an max values,
```javascript
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));
```
246. ### 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,
```javascript
// Initialize an array a
for(int i=0; i < a.length; a[i++] = 0) ;
```
247. ### How do you get meta data of a module?
You can use `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 module's URL. In browser, you might get different meta data than NodeJS.
```javascript
<script type="module" src="welcome-module.js"></script>
console.log(import.meta); // { url: "file:///home/user/welcome-module.js" }
```
248. ### 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,
```javascript
var x = 1;
x = (x++, x);
console.log(x); // 2
```
249. ### 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 usage 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,
```javascript
for (var a = 0, b =10; a <= 10; a++, b--)
```
You can also use the comma operator in a return statement where it process before returning.
```javascript
function myFunction() {
var a = 1;
return (a += 10, a); // 11
}
```
250. ### 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,
```typescript
function greeting(person: string) {
return "Hello, " + person;
}
let user = "Sudheer";
document.body.innerHTML = greeting(user);
```
The greeting method allows only string type as argument.
251. ### 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 |
252. ### What are the advantages of typescript over javascript?
Below are some of the advantages of typescript over javascript,
1. TypeScript is able to find compile time errors at the development time only and it make sures less runtime errors. Whereas javascript is interpreted language.
2. TypeScript is is strongly-typed or supports static typing which allows for checking type correctness at compile time. This is not available in javascript.
3. 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.
253. ### 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.
```javascript
var initObject = {a: 'John', b: 50, c: {}};
console.log(initObject.a); // John
```
254. ### 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,
```javascript
class Employee {
constructor() {
this.name = "John";
}
}
var employeeObject = new Employee();
console.log(employeeObject.name); // John
```
255. ### 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.
```javascript
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);
```
256. ### How do you call the constructor of a parent class?
You can use `super` keyword to call the constructor of a parent class. Remember that `super()` must be called before using 'this' reference. Otherwise it will cause a reference error. Let's the usage of it,
```javascript
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;
}
}
```
257. ### How do you get the prototype of an object?
You can use `Object.getPrototypeOf(obj)` method is used to return the prototype of the specified object. i.e. The value of the internal `prototype` property. If there are no inherited properties then `null` value is returned.
```javascript
const newPrototype = {};
const newObject = Object.create(newPrototype);
console.log(Object.getPrototypeOf(newObject) === newPrototype); // true
```
258. ### 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`.
```javascript
// ES5
Object.getPrototypeOf('James'); // TypeError: "James" is not an object
// ES2015
Object.getPrototypeOf('James'); // String.prototype
```
259. ### How do you set prototype of one object to another?
You can use `Object.setPrototypeOf()` method that sets the prototype (i.e., the internal `Prototype` 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,
```javascript
Object.setPrototypeOf(Square.prototype, Rectangle.prototype);
Object.setPrototypeOf({}, null);
```
260. ### How do you check whether an object can be extendable or not?
The `Object.isExtensible()` method is used to determine if an object is extensible or not. i.e, Whether it can have new properties added to it or not.
```javascript
const newObject = {};
console.log(Object.isExtensible(newObject)); //true
```
**Note:** By default, all the objects are extendable. i.e, The new properties can added or modified.
261. ### 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,
```javascript
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
}
```
262. ### What are the different ways to make an object non-extensible?
You can mark an object non-extensible in 3 ways,
1. Object.preventExtensions
2. Object.seal
3. Object.freeze
```javascript
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
```
263. ### How do you define multiple properties on an object?
The `Object.defineProperties()` method is used to define new or modifies existing properties directly on an object and returning the object. Let's define multiple properties on an empty object,
```javascript
const newObject = {};
Object.defineProperties(newObject, {
newProperty1: {
value: 'John',
writable: true
},
newProperty2: {}
});
```
264. ### 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.
265. ### 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,
```javascript
function greeeting() {
console.log('Hello, welcome to JS world');
}
```
And after the code Obfuscation, it would be appeared as below,
```javascript
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|greeeting|function|log|Hello|JS|to|welcome|world'.split('|'),0,{}))
```
266. ### Why do you need Obfuscation?
Below are the few reasons for Obfuscation,
1. The Code size will be reduced. So data transfers between server and client will be fast.
2. It hides the business logic from outside world and protects the code from others
3. Reverse engineering is highly difficult
4. The download time will be reduced
267. ### 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 .
268. ### What are the advantages of minification?
Normally it is recommend to use minification for heavy traffic and intensive requirements of resources. It reduces file sizes with below benefits,
1. Decreases loading times of a web page
2. Saves bandwidth usages
269. ### 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 |
270. ### What are the common tools used for minification?
There are many online/offline tools to minify the javascript files,
1. Google's Closure Compiler
2. UglifyJS2
3. jsmin
4. javascript-minifier.com/
5. prettydiff.com
Comments
Post a Comment
please do not enter any spam link in the comment box