How does the JavaScript Promise work?

Promise

A Promise is an object representing the eventual completion or failure of an asynchronous operation. A JavaScript Promise object contains both the producing code and calls to the consuming code. It can be used to deal with Asynchronous operations in JavaScript.

Promise State:-

Pending – Initial State, Not yet Fulfilled or Rejected
Fulfilled/Resolved – Promise Completed
Rejected – Promise Failed

How Promise works

  • A pending promise can either be Resolved with a value or Rejected with a reason (error).
  • When either of these options happens, the associated handlers queued up by a promise’s then method are called.
  • A promise is said to be settled if it is either Resolved or Rejected, but not Pending.

Creating Promise

Promise () – A Promise object is created using the new keyword and its constructor. This constructor takes a function, called the “executor function”, as its parameter. This function should take two functions as parameters. The first of these functions (resolve) is called when the asynchronous task completes successfully and returns the results of the task as a value. The second (reject) is called when the task fails and returns the reason for failure, which is typically an error object.

Syntax:- Promise (executor)

A JavaScript Promise object contains both the producing code and calls to the consuming code.

Function Returning a Promise

then( ) Method

The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise. As then the method returns a Promise so we can do method chaining.

Syntax:- then(onResolved, onRejected)

onResolved – A Function called if the Promise is fulfilled. This function has one argument, the fulfillment value.

onRejected – A Function called if the Promise is rejected. This function has one argument, the rejection reason.

Promise

Chaining

The then method returns a Promise which allows for method chaining. If the function passed as a handler to then returns a Promise, an equivalent Promise will be exposed to the subsequent then in the method chain.

catch () Method

The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling then(undefined, onRejected). In fact, calling catch(onRejected) internally calls then(undefined, onRejected).

The catch method is used for error handling in promise composition. Since it returns a Promise, it can be chained in the same way as its sister method, then()

Syntax:- catch(callback)

Where the callback is a function called when the Promise is rejected. This function has one argument error – The rejection error.

catch () Method

finally () Method

The finally() method returns a Promise. When the promise is settled, i.e either fulfilled or rejected, the specified callback function is executed. This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with.

This helps to avoid duplicating code in both the promise’s then() and catch() handlers.

Syntax:- finally(callback)

finally () Method

Chaining

Tagged : / / / /

How does the Import and Export module work in JavaScript?

What is Module

In JavaScript, a Module is a JavaScript file where we write codes. The object is a module that is not available for use unless the module file exports them.

Exporting Module

export – The export statement is used when creating JavaScript modules to export functions, objects, or primitive values from the module so they can be used by other programs with the import statement.

There are two different types of export – named and default. You can have multiple named exports per module but only one default export.

Default Export

You can have only one default export per module. A default export can be imported with any name.

mobile.js

Named Export

You can have multiple named exports per module. Named exports are useful to export several values. During the import, it is mandatory to use the same name of the corresponding object.

mobile.js

Named Export

You can have multiple named exports per module. Named exports are useful to export several values. During the import, it is mandatory to use the same name of the corresponding object.

mobile.js

Importing Module

import –  The static import statement is used to import bindings that are exported by another module. Imported modules are in strict mode whether you declare them as such or not.

Importing Defaults

You can have only one default export per module. A default export can be imported with any name.

mobile.js

app.js

Importing Named

You can have multiple named exports per module. Named exports are useful to export several values. During the import, it is mandatory to use the same name of the corresponding object.

mobile.js

app.js

Importing All

mobile.js

app.js

Importing Default and Named

mobile.js

app.js

Tagged : / / / /

Why doesn’t this JavaScript destructuring assignment work?

Destructuring

Destructuring is a convenient way of extracting multiple values from data stored in objects and Arrays. The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Ex:- var a = [10, 20, 30];

[x, y, z] = a;
console.log(x) // 10
console.log(y) // 20
console.log(z) // 30

Left-hand side of the assignment to define what values to unpack from the sourced variable.

Array Destructuring

When destructuring Array, we use their index/positions in the assignment.

Array Destructuring

Array Passing to a Function

Array Returning from a Function

Nested Array Destructuring

Object Destructuring

When destructuring objects, we use the keys as variable names. This is how JavaScript knows which property of the object we want to assign.

Object Destructuring

Object Destructuring

Object Destructuring

Object Passing to a Function

Object Returning from a Function

Nested Object Destructuring

Tagged : / / / / /

How do you handle exceptions in JavaScript?

Exception

An exception is a generalization of the concept of an error to include any unexpected condition encountered during execution.

Exception Handling-

  • try
  • catch
  • finally
  • throw

How does the Javascript callback function work?

A callback function is a function (It can be any function Anonymous Function, Arrow Function) passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Synchronous – It waits for each operation to complete, after that it executes the next operation.

Asynchronous – It never waits for each operation to complete, rather it executes all operations in the first GO only.

map ( ) Method in JavaScript

The map( ) method creates a new array with the results of calling a provided function on every element in the calling array.
the map calls a provided callback function once for each element in an array, in order, and returns a new array from the results.

Syntax:-
map(callback(currentValue, index, array), thisArg);

Tagged : / / /

Local Storage And Session Storage in JavaScript

Local Storage

The localStorage is a read-only property of the window objects. It stores data in a web browser specifically to the domain and protocol. It doesn’t get sent to the server as it is stored locally in the web browser with no expiration date. The data will not be deleted when the browser is closed and reopened.

Syntax:- window.localStorage

Methods

  • setItem (key, value) – It allows to add a key/value pair to the storage object. If the key already exists, the name value will overwrite the old value.
  • getItem(key) – It returns the value of the item that is set with the given key.
  • key(n) – It returns the key of the item in the storage object at the nth index which can be useful for looping.
  • removeItem(key) – It removes the item in the storage object with the given key.

Session Storage

The sessionStorage is a read-only property of the window object. It stores data in a web browser specifically to the domain and protocol for a particular session. It doesn’t get sent to the server. Data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores.

Syntax:- window.sessionStorage

Methods

  • setItem (key, value) – It allows to add a key/value pair to the storage object. If the key already exists, the name value will overwrite the old value.
  • getItem(key) – It returns the value of the item that is set with the given key.
  • key(n) – It returns the key of the item in the storage object at the nth index which can be useful for looping.
  • removeItem(key) – It removes the item in the storage object with the given key.
Tagged : / / /

Replace/Append Cookies in JavaScript

Replace/Append Cookies

When we assign a new cookie value to document.cookie, the current cookie is not replaced. The new cookie is parsed and its name-value pair is appended to the list. The exception is when you assign a new cookie with the same name (and same domain and path, if they exist) as a cookie that already exists. In this case, the old value is replaced with the new.

Reading Cookie

We can read cookies by a document.cookie. The problem occurs when we need the specific part of the cookie to perform some action.

Deleting Cookies

A cookie is deleted by setting a cookie with the same name (and domain and path, if they were set) with an expiration date in the past and if using max-age then must set a negative value.

Ex:

Updating Cookies

A cookie is possible to update by setting a new value to a cookie with the same name.

Cookies Security Issues

  • Can misuse Client Details
  • Can track User
  • Client Can Delete Cookies
  • Client can Manipulate Cookies

Cookies Limitation

  • Support HTML4 / HTML 5
  • Each cookie can contain 4kb Data
  • Cookies can be stored in Browser and server
  • It is sent with each request
Tagged : / / /

How many create cookies in JavaScript?

JavaScript Cookies

Cookies are exposed as the cookie property of the Document object. This property is both readable and writeable.

You can see Cookies in Google Chrome by following chrome://settings/content/cookies

Creating Cookies

When you assign a string to document.cookie, the browser parses it as a cookie and adds it to its list of cookies. There are several parts to each cookies, many of them optional.

Syntax: –

document.cookie = “name=value”;
document.cookie = “name=value; expires=date; domain=domain; path=path; secure”;
document.cookie = “name=value; max-age=inSecond; domain=domain; path=path; secure”;

Ex:-

Creating Cookies

Optional Cookies Attribute:-

max-age
expires
domain
path
secure

Whenever you omit the optional cookie fields, the browser fills them in automatically with reasonable defaults.

max-age

It is used to create persistent cookies. It is supported by all modern browsers except IE.

Type of cookies: –

  • Session Cookies – Cookies that are set without the expires/max-age field are called session cookies. It is destroyed when the user quits the browser.
  • Persistent Cookies – The browser keeps it up until their expiration date is reached.

Ex:-

expires

It is used to create persistent cookies.

Type of cookies: –

  • Session Cookies – Cookies that are set without the expires/max-age field are called session cookies. It is destroyed when the user quits the browser.
  • Persistent Cookies – The browser keeps it up until their expiration date is reached.

Ex:-

document.cookie = “username=devops; expires=Monday, 3-Sep-2018 09:00:00 UTC”;

domain

It specifies the domain for which the cookie is valid. If not specified, this defaults to the host portion of the current document location. If a domain is specified, subdomains are always included.

Ex: –

path

Path can be / (root) or /mydir (directory). If not specified, defaults to the current path of the current document location, as well as its descendants.

Ex: – document.cookie = “username=devops; path=/”;

Ex: – document.cookie = “username=devops; path=/home”;

secure

Cookie to only be transmitted over secure protocol as https. Before Chrome 52, this flag could appear with cookies from http domains.

Ex: – document.cookie = “username=devops; secure”;

Tagged : / / / / /

What are cookies in JavaScript?

Cookies

A cookie is a small piece of text data set by the Web server that resided on the client’s machine. Once it’s been set, the client automatically returns the cookie to the webserver with each request that it makes. This allows the server to place values it wishes to ‘remember’ in the cookie, and have access to them when creating a response.

How Cookie Works

How Cookie Works

How Cookie Works

How Dangerous Cookies are

Type of Cookies

  • Session Cookies – Cookies that are set without the expires field are called session cookies. It is destroyed when the user quits the browser.
  • Persistent Cookies – The browser keeps it up until their expiration date is reached.
Tagged : / / /

How to add placeholder to select2.js

Single select placeholders

<select class="js-example-placeholder-single js-states form-control">
  <option></option>
</select>

$(".js-example-placeholder-single").select2({
    placeholder: "Select a state",
    allowClear: true
});

Multi-select placeholders

<select class="js-example-placeholder-multiple js-states form-control" multiple="multiple"></select>
$(".js-example-placeholder-multiple").select2({
    placeholder: "Select a state"
});

Using placeholders with AJAX

Select2 supports placeholders for all configurations, including AJAX. You will still need to add in the empty <option> if you are using a single select.

When using Select2 in single-selection mode, the placeholder option will be passed through the templateSelection callback if specified. You can use some additional logic in this callback to check the id property and apply an alternative transformation to your placeholder option:

$('select').select2({
  templateSelection: function (data) {
    if (data.id === '') { // adjust for custom placeholder values
      return 'Custom styled placeholder text';
    }

    return data.text;
  }
});
Tagged : /

Accessing Form Fields in JavaScript

Accessing Form

JavaScript provides various ways of accessing form:-

  • document.forms[index_number] – It returns collection of form in the documents.
  • document.forms[“name_attribute_value”] – we can use name attribute of the form.
  • document.name_attribute_value – we can use name attribute of the form with dot as well.
  • getElementById(“ID”) – If form as an unique id we can use it.

Accessing Form Fields

If form fields have unique ID then it is possible to access them using the getElementById( ) method. However, There are some other ways: –

  • elements[ ] – It contains collection of form fields.

Syntax: –

document.form_name.elements[index_number];
document.form_name.elements[“name_attribute_value”];
document.form_name.name_attribute_value;
document.form_name.ID_attribute_value;

  • getElementsByName(“field_name”) – This method is also used to access form field.
Tagged : / / /