So in this blog, we’re going to create a little bit more at Timing Animations Using Callback Functions in jQuery.
In the previous blog, we also learn how can animate multiple C S S properties at once. So let’s go ahead and do that for the blue box first in index.html, with help of style.css & main.js.
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.
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.
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.
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().
Arrays are a collection of data items stored under a single name. Array provides a mechanism for declaring and accessing several data items with only one identifier, thereby simplifying the task of data management.
We use an array when we have to deal with multiple data items. Arrays are a special type of object. The typeof operator in JavaScript returns “object” for arrays.
Declaration and initialization of Array
Using Array Literal
Syntax: – var array_name = [ ];
Declaration and initialization of Array
Using Array Literal
Syntax: – var array_name = [value1, value2, value_n];
Declaration and initialization of Array
Using Array Constructor
Syntax: – var array_name = new Array( );
Declaration and initialization of Array
Using Array Constructor
This will create an empty array with 5 lengths. So this is not a good idea to use Array Constructor if you have only a single numeric value.
Note – By default, the array starts with index 0.
Important Points
JavaScript arrays are zero-indexed: the first element of an array is at index 0.
Using an invalid index number returns undefined.
It’s possible to quote the JavaScript array indexes as well (e.g., geek[‘2’] instead of geek[2]), although it’s not necessary.
Arrays cannot use strings as element indexes but must use integers.
There is no associative array in JavaScript. geek[“fees”] = 200;
No advantage to use Array Constructor so better to use Array Literal for creating Arrays in JavaScript.
Accessing Array Elements
Accessing Array Elements
Access all at once
Modifying Array Elements
Removing Array Elements
Array elements can be removed using the delete operator. This operator sets the array element it is invoked on to undefined but does not change the array‟s length.
The length property retrieves the index of the next available position at the end of the array. The length property is automatically updated as new elements are added to the array. For this reason, length is commonly used to iterate through all elements of an array.
JavaScript classes, introduced in ECMAScript 2015 or ES 6, Classes are in fact “special functions”. There are two ways to define a class in JavaScript using classkeyword:-
Class Declaration
Class Expression
Class Declaration
Constructor
The constructor method is a special method for creating and initializing an object created within a class. There can be only one special method with the name “constructor” in a class.
Default Constructor
If you do not specify a constructor method a default constructor is used.
Parameterized Constructor
Class Expression
Class expressions can be named or unnamed.
Class Hoisting
Class Declarations and Class Expression are not hoisted. You first need to declare your class and then access it.
Inheritance
Class Inheritance
The extends keyword is used in class declarations or class expressions to create a class that is a child of another class. The extended keyword can be used to subclass custom classes as well as built-in objects.
Class Inheritance
Inherit Built-in Object
– Date – String – Array
class myDate extends Date { }
Super
Super ( ) is used to initialize parent class constructor. If there is a constructor present in a subclass, it needs to first call super() before using “this”. A constructor can use the super keyword to call the constructor of a parent class.
Method Overriding
Same function name with different implementation.
Parent ———————> show ( ) {return “Super Class”; } Child ———————–> show ( ) {return “Sub Class”; } show ( ) {return “Super Class”; }
Static Method
The static keyword is used to define a static method for a class. Static methods are called without creating object and cannot be called through a class instance (object). Static methods are often used to create utility functions for an application.
IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. It is a design pattern which is also known as Self-Executing Anonymous Function and contains two major parts. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope. The second part is creating the immediately executing function expression (), through which the JavaScript engine will directly interpret the function.
Immediately Invoked Function Expression (IIFE)
Avoid Creating Global variable and Functions
As it doesn‟t define variable and function globally so there will be no name conflicts
Scope is limited to that particular function
Pass by Value
JavaScript arguments are passed by value: The function only gets to know the values, not the argument’s locations.
If a function changes an argument’s value, it does not change the parameter’s original value.
Changes to arguments are not visible (reflected) outside the function.
Pass by reference
In JavaScript, object references are values.
Because of this, objects will behave like they are passed by reference:
If a function changes an object property, it changes the original value.
Changes to object properties are visible (reflected) outside the function.