326. ### How do you avoid receiving postMessages from attackers?
Since the listener listens for any message, an attacker can trick the application by sending a message from the attacker’s origin, which gives an impression that the receiver received the message from the actual sender’s window. You can avoid this issue by validating the origin of the message on the receiver's end using “message.origin” attribute. For examples, let's check the sender's origin(http://www.some-sender.com) on receiver side(www.some-receiver.com),
```javascript
//Listener on http://www.some-receiver.com/
window.addEventListener("message", function(message){
if(/^http://www\.some-sender\.com$/.test(message.origin)){
console.log('You recieved the data from valid sender', message.data);
}
});
```
327. ### Can I avoid using postMessages completely?
You cannot avoid using postMessages completely(or 100%). Even though your application doesn’t use postMessage considering the risks, a lot of third party scripts use postMessage to communicate with the third party service. So your application might be using postMessage without your knowledge.
328. ### Is postMessages synchronous?
The postMessages are synchronous in IE8 browser but they are asynchronous in IE9 and all other modern browsers (i.e, IE9+, Firefox, Chrome, Safari).Due to this asynchronous behaviour, we use a callback mechanism when the postMessage is returned.
329. ### What paradigm is Javascript?
JavaScript is a multi-paradigm language, supporting imperative/procedural programming, Object-Oriented Programming and functional programming. JavaScript supports Object-Oriented Programming with prototypical inheritance.
330. ### What is the difference between internal and external javascript?
**Internal JavaScript:** It is the source code with in the script tag.
**External JavaScript:** The source code is stored in an external file(stored with .js extension) and referred with in the tag.
331. ### Is JavaScript faster than server side script?
Yes, JavaScript is than server side script. Because JavaScript is a client-side script it does require any web server’s help for its computation or calculation. So JavaScript is always faster than any server-side script like ASP, PHP, etc.
332. ### How do you get the status of a checkbox?
You can apply `checked` property on selected checkbox in the DOM. If the value is `True` means the checkbox is checked otherwise it is unchecked. For example, the below HTML checkbox element can be access using javascript as below,
```html
<input type="checkbox" name="checkboxname" value="Agree"> Agree the conditions<br>
```
```javascript
console.log(document.getElementById(‘checkboxname’).checked); // true or false
```
333. ### What is the purpose of double tilde operator?
The double tilde operator(~~) is known as double NOT bitwise operator. This operator is going to be a quicker substitute for Math.floor().
334. ### How do you convert character to ASCII code?
You can use `String.prototype.charCodeAt()` method to convert string characters to ASCII numbers. For example, let's find ASCII code for the first letter of 'ABC' string,
```javascript
"ABC".charCodeAt(0) // returns 65
```
Whereas `String.fromCharCode()` method to convert numbers to equal ASCII character.
```javascript
String.fromCharCode(65,66,67); // returns 'ABC'
```
335. ### What is ArrayBuffer?
An ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. You can create it as below,
```javascript
let buffer = new ArrayBuffer(16); // create a buffer of length 16
alert(buffer.byteLength); // 16
```
To manipulate an ArrayBuffer, we need to use a “view” object.
```javascript
//Create a DataView referring to the buffer
let view = new DataView(buffer);
```
336. ### What is the output of below string expression?
```javascript
console.log("Welcome to JS world"[0])
```
The output of the above expression is "W".
**Explanation:** The bracket notation with specific index on a string returns the character at a specific location. Hence, it returns character "W" of the string. Since this is not supported in IE7 and below versions, you may need to use .charAt() method to get the desired result.
337. ### What is the purpose of Error object?
The Error constructor creates an error object and the instances of error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. The syntax of error object would be as below,
```javascript
new Error([message[, fileName[, lineNumber]]])
```
You can throw user defined exceptions or errors using Error object in try...catch block as below,
```javascript
try {
if(withdraw > balance)
throw new Error('Oops! You don't have enough balance');
} catch (e) {
console.log(e.name + ': ' + e.message);
}
```
338. ### What is the purpose of EvalError object?
The EvalError object indicates an error regarding the global `eval()` function. Even though this exception is not thrown by JavaScript anymore, the EvalError object remains for compatibility. The syntax of this expression would be as below,
```javascript
new EvalError([message[, fileName[, lineNumber]]])
```
You can throw EvalError with in try...catch block as below,
```javascript
try {
throw new EvalError('Eval function error', 'someFile.js', 100);
} catch (e) {
console.log(e.message, e.name, e.fileName); // "Eval function error", "EvalError", "someFile.js"
```
339. ### What are the list of cases error thrown from non-strict mode to strict mode?
When you apply 'use strict'; syntax, some of the below cases will throw a SyntaxError before executing the script
1. When you use Octal syntax
```javascript
var n = 022;
```
2. Using `with` statement
3. When you use delete operator on a variable name
4. Using eval or arguments as variable or function argument name
5. When you use newly reserved keywords
6. When you declare a function in a block
```javascript
if (someCondition) { function f() {} }
```
Hence, the errors from above cases helpful to avoid errors in development/production environments.
340. ### Is all objects have prototypes?
No. All objects have prototypes except for the base object which is created by the user, or an object that is created using the new keyword.
341. ### What is the difference between a parameter and an argument?
Parameter is the variable name of a function definition whereas an argument represent the value given to a function when it is invoked. Let's explain this with a simple function
```javascript
function myFunction(parameter1, parameter2, parameter3) {
console.log(arguments[0]) // "argument1"
console.log(arguments[1]) // "argument2"
console.log(arguments[2]) // "argument3"
}
myFunction("argument1", "argument2", "argument3")
```
342. ### What is the purpose of some method in arrays?
The some() method is used to test whether at least one element in the array passes the test implemented by the provided function. The method returns a boolean value. Let's take an example to test for any odd elements,
```javascript
var array = [1, 2, 3, 4, 5, 6 ,7, 8, 9, 10];
var odd = element ==> element % 2 !== 0;
console.log(array.some(odd)); // true (the odd element exists)
```
343. ### How do you combine two or more arrays?
The concat() method is used to join two or more arrays by returning a new array containing all the elements. The syntax would be as below,
```javascript
array1.concat(array2, array3, ..., arrayX)
```
Let's take an example of array's concatenation with veggies and fruits arrays,
```javascript
var veggies = ["Tomato", "Carrot", "Cabbage"];
var fruits = ["Apple", "Orange", "Pears"];
var veggiesAndFruits = veggies.concat(fruits);
console.log(veggiesAndFruits); // Tomato, Carrot, Cabbage, Apple, Orange, Pears
```
344. ### What is the difference between Shallow and Deep copy?
There are two ways to copy an object,
### Shallow Copy
Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
### Example
```
var empDetails = {
name: "John", age: 25, expertise: "Software Developer"
}
```
to create a duplicate
```
var empDetailsShallowCopy = empDetails //Shallow copying!
```
if we change some property value in the duplicate one like this:
```
empDetailsShallowCopy.name = "Johnson"
```
The above statement will also change the name of `empDetails`, since we have a shallow copy. That means we're loosing the original data as well.
### Deep copy
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.
### Example
```
var empDetails = {
name: "John", age: 25, expertise: "Software Developer"
}
```
Create a deep copy by using the properties from the original object into new variable
```
var empDetailsDeepCopy = {
name: empDetails.name,
age: empDetails.age,
expertise: empDetails.expertise
}
```
Now if you change `empDetailsDeepCopy.name`, it will only affect `empDetailsDeepCopy` & not `empDetails`
345. ### How do you create specific number of copies of a string?
The `repeat()` method is used to construct and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. Remember that this method has been added to the ECMAScript 2015 specification.
Let's take an example of Hello string to repeat it 4 times,
```javascript
'Hello'.repeat(4); // 'HelloHelloHelloHello'
```
346. ### How do you return all matching strings against a regular expression?
The `matchAll()` method can be used to return an iterator of all results matching a string against a regular expression. For example, the below example returns an array of matching string results against a regular expression,
```javascript
let regexp = /Hello(\d?))/g;
let greeting = 'Hello1Hello2Hello3';
let greetingList = [...greeting.matchAll(regexp)];
console.log(greetingList[0]); //Hello1
console.log(greetingList[1]); //Hello2
console.log(greetingList[2]); //Hello3
```
347. ### How do you trim a string at the beginning or ending?
The `trim` method of string prototype is used to trim on both sides of a string. But if you want to trim especially at the beginning or ending of the string then you can use `trimStart/trimLeft` and `trimEnd/trimRight` methods. Let's see an example of these methods on a greeting message,
```javascript
var greeting = ' Hello, Goodmorning! ';
console.log(greeting); // " Hello, Goodmorning! "
console.log(greeting.trimStart()); // "Hello, Goodmorning! "
console.log(greeting.trimLeft()); // "Hello, Goodmorning! "
console.log(greeting.trimEnd()); // " Hello, Goodmorning!"
console.log(greeting.trimRight()); // " Hello, Goodmorning!"
```
348. ### What is the output of below console statement with unary operator?
Let's take console statement with unary operator as given below,
```javascript
console.log(+ 'Hello');
```
The output of the above console log statement returns NaN. Because the element is prefixed by the unary operator and the JavaScript interpreter will try to convert that element into a number type. Since the conversion fails, the value of the statement results in NaN value.
349. ### Does javascript uses mixins?
350. ### What is a thunk function?
A thunk is just a function which delays the evaluation of the value. It doesn’t take any arguments but gives the value whenever you invoke the thunk. i.e, It is used not to execute now but it will be sometime in the future. Let's take a synchronous example,
```javascript
const add = (x,y) => x + y;
const thunk = () => add(2,3);
thunk() // 5
```
351. ### What are asynchronous thunks?
The asynchronous thunks are useful to make network requests. Let's see an example of network requests,
```javascript
function fetchData(fn){
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => fn(json))
}
const asyncThunk = function (){
return fetchData(function getData(data){
console.log(data)
})
}
asyncThunk()
```
The `getData` function won't be called immediately but it will be invoked only when the data is available from API endpoint. The setTimeout function is also used to make our code asynchronous. The best real time example is redux state management library which uses the asynchronous thunks to delay the actions to dispatch.
352. ### What is the output of below function calls?
**Code snippet:**
const circle = {
radius: 20,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius
};
console.log(circle.diameter());
console.log(circle.perimeter());
**Output:**
The output is 40 and NaN. Remember that diameter is a regular function, whereas the value of perimeter is an arrow function. The this keyword of a regular function(i.e, diameter) refers to surrounding scope which is a class(i.e, Shape object). Whereas this keyword of perimeter function refers the surrounding scope which is window object. Since there is no radius property on window object it returns an undefined value and the multiple of number value returns NaN value.
353. ### How to remove all line breaks from a string?
The easiest approach is using regular expressions to detect and replace newlines in the string. In this case, we use replace function along with string to replace with, which in our case is an empty string.
```javascript
function remove_linebreaks( var message ) {
return message.replace( /[\r\n]+/gm, "" );
}
```
In the above expression, g and m are for global and multiline flags.
354. ### What is the difference between reflow and repaint?
A *repaint* occurs when changes are made which affect the visibility of an element, but not its layout. Examples of this include outline, visibility, or background color. A *reflow* involves changes that affect the layout of a portion of the page (or the whole page). Resizing the browser window, changing the font, content changing (such as user typing text), using JavaScript methods involving computed styles, adding or removing elements from the DOM, and changing an element's classes are a few of the things that can trigger reflow. Reflow of an element causes the subsequent reflow of all child and ancestor elements as well as any elements following it in the DOM.
355. ### What happens with negating an array?
Negating an array with `!` character will coerce the array into a boolean. Since Arrays are considered to be truthy So negating it will return `false`.
```javascript
console.log(![]); // false
```
356. ### What happens if we add two arrays?
If you add two arrays together, it will convert them both to strings and concatenate them. For example, the result of adding arrays would be as below,
```javascript
console.log(['a'] + ['b']); // "ab"
console.log([] + []); // ""
console.log(![] + []); // "false", because ![] returns false.
```
357. ### What is the output of prepend additive operator on falsy values?
If you prepend additive(+) operator on falsy values(null, undefined, NaN, false, ""), the falsy value converts to a number value zero. Let's display them on browser console as below,
```javascript
console.log(+null); // 0
console.log(+undefined);// 0
console.log(+false); // 0
console.log(+NaN); // 0
console.log(+""); // 0
```
358. ### How do you create self string using special characters?
The self string can be formed with the combination of `[]()!+` characters. You need to remember the below conventions to achieve this pattern.
1. Since Arrays are truthful values, negating the arrays will produce false: ![] === false
2. As per JavaScript coercing rules, the addition of arrays together will toString them: [] + [] === ""
3. Prepend an array with + operator will convert an array to false, the negation will make it true and finally converting the result will produce value '1': +(!(+[])) === 1
By applying the above rules, we can derive below conditions
```javascript
![] + [] === "false"
+!+[] === 1
```
Now the character pattern would be created as below,
```javascript
s e l f
^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^
(![] + [])[3] + (![] + [])[4] + (![] + [])[2] + (![] + [])[0]
^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^
(![] + [])[+!+[]+!+[]+!+[]] +
(![] + [])[+!+[]+!+[]+!+[]+!+[]] +
(![] + [])[+!+[]+!+[]] +
(![] + [])[+[]]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(![]+[])[+!+[]+!+[]+!+[]]+(![]+[])[+!+[]+!+[]+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+[]]
```
358. ### How do you remove falsy values from an array?
You can apply filter method on array by passing Boolean as parameter. This way it removes all falsy values(0, undefined, null, false and "") from the array.
```javascript
const myArray = [false, null, 1,5, undefined]
myArray.filter(Boolean); // [1, 5] // is same as myArray.filter(x => x);
```
359. ### How do you get unique values of an array?
You can get unique values of an array with the combination of `Set` and rest expression/spread(...) syntax.
```javascript
console.log([...new Set([1, 2, 4, 4, 3])]); // [1, 2, 4, 3]
```
360. ### What is destructuring aliases?
Sometimes you would like to have destructured variable with a different name than the property name. In that case, you'll use a `: newName` to specify a name for the variable. This process is called destructuring aliases.
```javascript
const obj = { x: 1 };
// Grabs obj.x as as { otherName }
const { x: otherName } = obj;
```
361. ### How do you map the array values without using map method?
You can map the array values without using `map` method by just using `from` method of Array. Let's map city names from Countries array,
```javascrippt
const countries = [
{ name: 'India', capital: 'Delhi' },
{ name: 'US', capital: 'Washington' },
{ name: 'Russia', capital: 'Moscow' },
{ name: 'Singapore', capital: 'Singapore' },
{ name: 'China', capital: 'Beijing' },
{ name: 'France', capital: 'Paris' },
];
const cityNames = Array.from(countries, ({ capital}) => capital);
console.log(cityNames); // ['Delhi, 'Washington', 'Moscow', 'Singapore', 'Beijing', 'Paris']
```
362. ### How do you empty an array?
You can empty an array quicky by setting the array length to zero.
```javascript
let cities = ['Singapore', 'Delhi', 'London'];
cities.length = 0; // cities becomes []
```
363. ### How do you rounding numbers to certain decimals?
You can rounding numbers to a certain number of decimals using `toFixed` method from native javascript.
```javascript
let pie = 3.141592653;
pie = pie.toFixed(3); // 3.142
```
364. ### What is the easiest way to convert an array to an object?
You can convert an array to an object with the same data using spread(...) operator.
```javascript
var fruits = ["banana", "apple", "orange", "watermelon"];
var fruitsObject = {...fruits};
console.log(fruitsObject); // {0: "banana", 1: "apple", 2: "orange", 3: "watermelon"}
```
365. ### How do you create an array with some data?
You can create an array with some data or an array with the same values using `fill` method.
```javascript
var newArray = new Array(5).fill("0");
console.log(newArray); // ["0", "0", "0", "0", "0"]
```
366. ### What are the placeholders from console object?
Below are the list of placeholders available from console object,
1. %o — It takes an object,
2. %s — It takes a string,
3. %d — It is used for a decimal or integer
These placeholders can be represented in the console.log as below
```javascript
const user = { "name":"John", "id": 1, "city": "Delhi"};
console.log("Hello %s, your details %o are available in the object form", "John", user); // Hello John, your details {name: "John", id: 1, city: "Delhi"} are available in object
```
367. ### Is it possible to add CSS to console messages?
Yes, you can apply CSS styles to console messages similar to html text on the web page.
```javascript
console.log('%c The text has blue color, with large font and red background', 'color: blue; font-size: x-large; background: red');
```
The text will be displayed as below,
![Screenshot](images/console-CSS.png)
**Note:** All CSS styles can be applied to console messages.
368. ### What is the purpose of dir method of console object?
The `console.dir()` is used to display an interactive list of the properties of the specified JavaScript object as JSON.
```javascript
const user = { "name":"John", "id": 1, "city": "Delhi"};
console.dir(user);
```
The user object displayed in JSON representation
![Screenshot](images/console-css.png)
369. ### Is it possible to debug HTML elements in console?
Yes, it is possible to get and debug HTML elements in the console just like inspecting elements.
```javascript
const element = document.getElementsByTagName("body")[0];
console.log(element);
```
It prints the HTML element in the console
![Screenshot](images/console-html.png)
370. ### How do you display data in a tabular format using console object?
The `console.table()` is used to display data in the console in a tabular format to visualize complex arrays or objects.
```javascript
const users = [{ "name":"John", "id": 1, "city": "Delhi"},
{ "name":"Max", "id": 2, "city": "London"},
{ "name":"Rod", "id": 3, "city": "Paris"}];
console.table(users);
```
The data visualized in a table format
![Screenshot](images/console-table.png)
**Not:** Remember that `console.table()` is not supported in IE.
371. ### How do you verify that an argument is a Number or not?
The combination of IsNaN and isFinite methods are used to confirm whether an argument is a number or not.
```javascript
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}
```
372. ### How do you create copy to clipboard button?
You need to select the content(using .select() method) of input element and execute the copy command with execCommand (i.e, execCommand('copy')). You can also execute another system commands like cut and paste.
```javascript
document.querySelector("#copy-button").onclick = function() {
// Select the content
document.querySelector("#copy-input").select();
// Copy to the clipboard
document.execCommand('copy');
};
```
373. ### What is the shortcut to get timestamp?
You can use `new Date().getTime()` to get the current timestamp. There is an alternative shortcut to get the value.
```javascript
console.log(+new Date());
console.log(Date.now());
```
374. ### How do you flattening multi dimensional arrays?
Flattening bi-dimensional arrays is trivial with Spread operator.
```javascript
const biDimensionalArr = [11, [22, 33], [44, 55], [66, 77], 88, 99];
const flattenArr = [].concat(...biDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
```
But you can make it work with multi-dimensional arrays by recursive calls,
```javascript
function flattenMultiArray(arr) {
const flattened = [].concat(...arr);
return flattened.some(item => Array.isArray(item)) ? flattenMultiArray(flattened) : flattened;
}
const multiDimensionalArr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
const flatArr = flattenMultiArray(multiDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
```
375. ### What is the easiest multi condition checking?
You can use `indexOf` to compare input with multiple values instead of checking each value as one condition.
```javascript
// Verbose approach
if (input === 'first' || input === 1 || input === 'second' || input === 2) {
someFunction();
}
// Shortcut
if (['first', 1, 'second', 2].indexOf(input) !== -1) {
someFunction();
}
```
376. ### How do you capture browser back button?
The `window.onbeforeunload` method is used to capture browser back button event. This is helpful to warn user about loosing the current data.
```javascript
window.onbeforeunload = function() {
alert("You work will be lost");
};
```
377. ### How do you disable right click in the web page?
The right click on the page can be disabled by returning false from `oncontextmenu` attribute on body element.
```html
<body oncontextmenu="return false;">
```
Comments
Post a Comment
please do not enter any spam link in the comment box