Limited Time Offer!

For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!

Enroll Now

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 : / / / /

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 : / / /

How to use Form Handling in javascript

Form Handling

JavaScript provides access to the forms within an HTML document through the Form object known as HTMLFormElement in the DOM. Which is a child of the Document Object.

Properties

PropertiesValueDescription
accept-charsetUTF-8Specifies the charset used in the submitted form (default: the page charset).
actionURLContains a URL that defines where to send the data after submitting the form
autocompleteOn (default)
Off
Determines that the browser retains the history of previous values.
enctypespecifies how the browser encodes the data before it sends it to the server. (default: is url-encoded).
encodingHolds the value of the enctype attribute, which usually contains either application/x-www-form-urlencoded value or the multipart/form-data value (in the case of file upload)
elements[ ]An array of DOM elements that correspond to the interactive form fields within the form

Properties

PropertiesValueDescription
lengthThe number of a form field with a given form tag. Should bt the same as elements.length
methodGET (default)
POST
Specifies how to send the form data to a web server. The data can be sent as URL variables, by using the get method or as HTTP post, by using the post method
namenameSpecifies a name used to identify the form
novalidatenovalidateSpecifies that the browser should not validate the form.
target_self (default)
_blank
_parent
_top
framename
Specifies the target of the address in the action attribute

Methods

MethodDescription
checkValidity ( )Returns a true or false value indicating whether or not all the fields in the form are in a valid state.
reset ( )Returns all form fields to their initial state.
submit ( )Submits the form to the URL specified in the form’s action attribute

Events: –

  • onreset
  • onsubmit
Tagged : / / / / / / /

What is the difference between a timeout and an interval in Javascript?

setTimeout( ) Method

The setTimeout() method sets a timer which executes a function or specified piece of code once after the timer expires. The function is only executed once. It returns a positive integer value which identifies the timer created by the call to setTimeout(); this value can be passed to clearTimeout() to cancel the timeout.

Syntax: –
setTimeout (function, milliseconds, para1, para2);
Ex: – var timeoutID = setTimeout(show, 2000);

clearTimeout( ) Method

The clearTimeout() method cancels a timeout previously established by calling setTimeout(). The ID value returned by setTimeout() is used as the parameter for the clearTimeout() method.

Syntax: – clearTimeout (timeoutID);

Ex: – clearTimeout(timeoutID);

setInterval( ) Method

The setInterval() method repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID that uniquely identifies the interval, so you can remove it later by calling clearInterval().

Syntax: – setInterval (function, milliseconds, para1, para2);

Ex: – var intervalID = setInterval(show, 2000);

clearInterval( ) Method

The clearInterval() method cancels a timed, repeating action that was previously established by a call to setInterval().

Syntax: – clearInterval (intervalID);

Ex: – clearInterval(intervalID);

Tagged : / / / / / /

Moving Windows in JavaScript

Moving Windows

moveBy ( ) – This method moves the current window by a specified amount of pixels.

Syntax:- window.moveBy(horizontalPixels, verticalPixels);

Where,

window – It is the name of the window to move or is called just window if it is the main window.

horizontalPixels – It is the number of horizontal pixels to move the window where positive numbers move the window to the right and negative numbers to the left.

verticalPixels – It is the number of vertical pixels to move the window where positive number move the window down and negative number up.

Ex:- newWindow.moveBy(200, 200);

Moving Windows

moveTo ( ) – This method moves the window to the specified coordinates.

Syntax:- window.moveTo(x, y);

Where,

window – It is the name of the window to move or is called just window if it is the main window.

x – It is the screen co-ordinate on the x-axis to move the window to.

y – It is the screen co-ordinate on the y-axis to move the window to.

Ex:- newWindow.moveTo(200, 200);

Resizing Windows

Resizing Windows

resizeBy ( ) – This method is used to resize the current window by a certain amount, relative to its current size. 

Syntax:- window.resizeBy(width, height);

Where,

window – It is the name of the window to move or is called just window if it is the main window.

width – It is the number of width pixels, where positive numbers increase the window and negative numbers decrease.

height – It is the number of height pixels, where positive numbers increase the window and negative numbers decrease.

Ex:- newWindow.resizeBy(200, 200);

Resizing Windows

resizeTo ( ) – This method is used to resize a window to the specified width and height.

Syntax:- window.resizeTo(width, height);

Where,

window – It is the name of the window to move or is called just window if it is the main window.

width – It is an integer representing the new outerWidth in pixels (including scroll bars, title bars, etc).

height – It is an integer value representing the new outerHeight in pixels (including scroll bars, title bars, etc).

Ex:- newWindow.resizeTo(200, 200);

Scrolling Windows

scrollBy ( ) – This method scrolls the document in the window by the given amount.

Syntax:- window.scrollBy(x, y); or window.scrollBy(options);

Where,

window – It is the name of the window to scroll or is called just window if it is the main window.

x – How many pixels to scroll by, along the x-axis (horizontal). Positive values will scroll to the right, while negative values will scroll to the left

y – How many pixels to scroll by, along the y-axis (vertical). Positive values will scroll down, while negative values scroll up

Options – It is an object with three possible properties:
top, which is the same as the y-coord
left, which is the same as the x-coord
behavior, which is a string containing one of smooth, instant, or auto; default is auto

Note – For this method to work, the visible property of the window’s scrollbar must be set to true!

Scrolling Windows

scrollTo ( ) – This method scrolls to a particular set of coordinates in the document.

Syntax:- window.scrollTo(x, y); or window.scrollTo(options);

Where,

window – It is the name of the window to scroll or is called just window if it is the main window.

x – It is the pixel along the horizontal axis of the document that you want to be displayed in the upper left.

y – It is the pixel along the vertical axis of the document that you want to be displayed in the upper left.

options is an object with three possible properties:
top, which is the same as the y-coord
left, which is the same as the x-coord
behavior, which is a string containing either smooth, instant, or auto; default is auto

Tagged : / / / /

What is a window object in JavaScript? What are its properties?

Window Object

  • Window object represents the browser’s window or potentially frame, that a document is displayed in.
  • As long as a browser window is open, even if no document is loaded in the window, the window object is defined in the current model in memory.
  • All global JavaScript variables, functions and objects automatically become members of the window object.

Dialog boxes

It is used to provide some information to users.

Type of Dialog box:-

  • Alert
  • Confirm
  • Prompt

alert ( ) Method

This Window object’s method is used to display data in the alert dialog box. alert really should be used only when you truly want to stop everything and let the user know something.

Syntax:- window.alert( ) or alert ( )

confirm ( ) Method

This Window object’s method is used to display a message for a user to respond to by pressing either an OK button to agree with the message to a Cancel button to disagree with the message. It returns true on OK and false on Cancel.

Syntax:- window.confirm( ) or confirm ( )

prompt ( ) Method

Window object’s method prompt() can be used to get input from the user, named prompt. The prompt( ) method displays a dialog box that prompts the visitor for input.

Once the prompt function obtains input from the user, it returns that input. If the user press the cancel button in the dialog or close box, a value null will be returned.

Syntax: – prompt(text, defaultText)

open ( ) Method

The open( ) method creates a new secondary browser window, similar to choosing New Window from the File menu. It returns a Window object representing the newly-created window. If the window couldn’t be opened, the returned value is instead null.

Syntax: – window.open (URL, name, features, replace)

URL – URL indicates the document to load into the window. If no URL is specified, a new window with about: blank is opened

Name – Specifies the target attribute or the name of the window. The following values are supported:

_blank – URL is loaded into a new window. This is default
_parent – URL is loaded into the parent frame
_self – URL replaces the current page
_top – URL replaces any framesets that may be loaded

open ( ) Method

Syntax: – window.open (URL, name, features, replace)

Features – It is a comma-delimited string that lists the features of the window.

Replace – It indicates whether or not the URL specified should replace the window’s contents. This would apply to a window that was already created. Value can be true/false.

Features

Feature ParameterValueExample
alwaysLoweredyes/noalwaysLowered=yes
alwaysRaisedyes/noalwaysRaised=no
centerscreenyes/nocenterscreen=yes
chromeyes/nochrome=yes/true
closeyes/noclose=no
dialogyes/nodialog=yes
dependentyes/nodependent=yes
z-lockyes/noz-lock=yes
hotkeysyes/nohotkeys=yes

Features

Feature ParameterValueExample
locationyes/nolocation=no
menubaryes/nomenubar=no
minimizableyes/nominimizable=no
modalyes/nomodal=yes
personalbaryes/nopersonalbar=yes/true
resizableyes/noresizable=no
scrollbarsyes/noscrollbars=no
statusyes/nostatus=no
titlebaryes/notitlebar=yes

Features

Feature ParameterValueExample
toolbaryes/notoolbar=yes
toppixel valuetop=20
heightpixel valueheight=200
widthpixel valuewidth=200
innerHeightpixel valueinnerHeight=200
innerWidthpixel valueinnerWidth=200
outerHeightpixel valueouterHeight=200
outerWidthpixel valueouterWidth=200
leftpixel valueleft=20

close ( ) Method

Once a window is open, the close ( ) method is used to close it. It closes the current window or the window on which it was called. This method is only allowed to be called for windows that were opened by a script using the window.open() method. It is often used together with open ( ) method.

Syntax: – window.close ( )

Tagged : / / / /

Manipulation Attributes in JavaScript

Attributes

The attributes property returns a live collection of all attribute nodes registered to the specified node. It is a read-only property.

Syntax:-
Element.attributes[index/key]

Attr Object

Properties

  • name (do not use nodeName)
  • value (do not use nodeValue or textContent or appendChild() or insertBefore( ) or removeChild( ) or replaceChild( ) these all are deprecated for attr object)

Methods

  • setAttribute( )
  • getAttribute( )
  • removeAttribute( )

setAttribute( )

This method is used to set the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise, a new attribute is added with the specified name and value. We should not use this method to set inline style as it will overwrite other CSS properties.

Syntax:-
Element.setAttribute(name, value);
Element.setAttribute(“style”, “css properties: value”);

Ex: –
p.setAttribute(“id”, “mydiv”);
p.setAttribute(“style”, “font-size: 80px”);

getAttribute( )

The getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or “ ”.

Syntax: –
var attribute = element.getAttribute(attributeName);

removeAttribute( )

This method is used to remove an attribute from the specified element.

Syntax: –
element.removeAttribute(attrName);

hasAttribute( )

The hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not.

Syntax:-
var result = element.hasAttribute(attr_name);

Tagged : / / / /

Insert( ) Method in JavaScript

The insertBefore() method is used to insert a node before the reference node as a child of a specified parent node. If the given child is a reference to an existing node in the document, insertBefore( ) moves it from its current position to the new position.

If referenceNode is null, the newNode is inserted at the end of the list of child nodes.

Syntax: –

parentNode.insertBefore(newNode, referenceNode);

insertAdjacentElement ( ) Method

The insertAdjacentElement() method inserts the specified element into a given specified position. It returns the element that was inserted, or null if the insertion failed.

Syntax:-

element – The element to be inserted into the tree.
The beforebegin and afterend positions work only if the node is in a tree and has an element parent.

insertAdjacentHTML ( ) Method

The insertAdjacentHTML() method is used to insert a text as HTML (parses the specified text as HTML or XML) into a specified position.

Syntax:-

text – The string to be parsed as HTML or XML and inserted into the tree.
It is recommended you not use insertAdjacentHTML when inserting plain text instead, use the node.textContent property

insertAdjacentText ( ) Method

The insertAdjacentText() method inserts the specified element into a specified position.

Syntax:-

text – The text which is about to insert.
The beforebegin and afterend positions work only if the node is in a tree and has an element parent.

Tagged : / / / /

How is Node.js created with JavaScript?

Creating Nodes

  • createElement(element_name)
  • createTextNode(string)
  • createComment(string)
  • createDocumentFragment( )

Create Element Node

The createElement(element_name) method is used to create the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn’t recognized. It returns the New Element.

Syntax:-
createElement(element_name)

Create Text Node

The createTextNode(string) method is used to create the Text Node with the specified text (string).

Syntax:-
createTextNode(string)

Create Comment Node

The createComment(string) method is used to create the Comment Node with the specified string and returns it.

Syntax:-
createComment (string)

Document Fragment

  • The DocumentFragment interface represents a minimal document object that has no parent.
  • A common use for Document Fragment is to create one, assemble a DOM subtree within it, then append or insert the fragment into the DOM using Node interface methods such as appendChild( ) or insertBefore( ).
  • Document fragment isn’t part of the active document tree structure, changes made to the fragment don’t affect the document.
  • Doing this moves the fragment’s nodes into the DOM, leaving behind an empty Document Fragment.
  • An empty Document Fragment can be created using the document.createDocumentFragment() method.

Create Document Fragment

The createDocumentFragment() method creates a imaginary Node object, with all the properties and methods of the Node object.

Tagged : / / / /

How to Use CSS Selector in javascript?

querySelector(“CSS Selector”)

The method querySelector() returns the first Element match of the specified selector or group of selectors. If no matches are found, null is returned.

querySelectorAll(“CSS Selector”)

The method querySelectorAll() returns a static (not live) NodeList representing a list of the document’s elements that match the specified group of selectors.

  • The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
  • You can use the length property of the NodeList object to determine the number of elements that matches the specified selector, then you can loop through all elements and extract the info you want.
  • If the specified selectors include a CSS pseudo-element, the returned list is always empty.

querySelectorAll(“CSS Selector”)

querySelectorAll(“CSS Selector”)

More specific

querySelectorAll(“CSS Selector”)

  • Length Property
  • Loop

innerHTML

The innerHTML property defines the HTML content.

Tagged : / / /