2,882 665 3MB
English Pages 
1,983 317 11MB Read more
1,616 388 5MB Read more
1,126 247 387KB Read more
1,533 253 74KB Read more
1,578 300 8MB Read more
439 123 887KB Read more
TABLE OF CONTENT 1. INTRODUCTION 2. CONDITIONALS 3. FUNCTIONS 4. SCOPE 5. ARRAYS 6. LOOPS 7. ITERATORS 8. OBJECTS 9. CLASSES 10. BROWSERCOMPATIBILITY ANDTRANSPILATION 11. MODULES 12. PROMISES 13. ASYNC-AWAIT 14. REQUESTS 15. GLOSSARY 16. CONCLUSION
CLIENT SIDE It supplies objects for the use of the user and its Document Object Model (DOM). As though Client-side extensions enable an application to position items on an HTML form and answer to user events such as mouse clicks, template data, and page navigation. Using complete client-side frameworks like AngularJS, ReactJS, VueJS and so many more.
TOOLS YOU NEED In order to begin with, you need a text editor to write your code and a browser to view your web pages. You should use the text editor of your choosing, like Notepad++, Visual Studio Code, Sublime Text, Atom or some other text editor that you're happy with. You may use any web browser that includes Google Chrome, Safari, Microsoft Edge, Internet Explorer, etc.
IF STATEMENT EXAMPLE The If sentence only runs while the condition in parenthesis () is true. Thus the commonest form of conditional.
ELSE STATEMENT EXAMPLE The if statement with an else statement, adding another block to run if the conditional does not pass, may be expanded.
In the above case, "cat" and "dog" are not identical, so that the other block is run and that the result of the variable is "else block."
ELSE IF STATEMENT EXAMPLE
You can also extend a declaration if with another declaration an else if which adds another conditional on its block.
Example, this code defines a square to refer to a function that generates a square of a given number: A function may have multiple parameters or no parameters or anything. In the following example, makeNoise does not list any names for the parameters, while power labels two:
Some functions generate value, including such power and square, and some do not produce value, such as makeNoise, the only result of which is a side effect. The return statement sets the value that the function returns.The return keyword without an expression will cause the function to return unknown. Functions that have no return statement or anything, such as makeNoise, similarly return undefined. Function parameters act as regular bindings, but their initial values are provided by the function caller, not by the function on its own.
FUNCTION USED AS A VARAIBLE VALUE Functions should be used the same way we use variables in all kinds of formulas, assignments, and calculations.
RETURN VALUE Using The return keyword a function can return zero value, or one value.
In the example mentioned above, a function called Sum adds and returns val1 and val2. It allows the calling code to obtain and assign the return value to a variable. The second Multiply feature does not return a value, so it does not describe the resulting attribute.
external function variables and parameters. External function can not access internal functions specified variables.
SCOPE Accessibility (visibility) of variables is determined by the scope. OR
Local variables of the Function scope: they will only be obtained from within the function. Variables declared within any var parameter function are called local variables. Local variables will not be accessed or changed outside the declaration function. Variables specified within a function are local in scope. But they have a different scope for any call to that function. This means that variables with the same name can be used in various functions. Since these variables are bound to their respective functions, with multiple scopes each and several other functions inaccessible. Since only local variables are defined in their functions, the same
named variables may be used for different functions. Local variables are generated when the function begins, and removed when the function is done.
ARRAY CONSTRUCTOR You can initialize an array with the syntax of the Array constructor using a new keyword. The following example illustrates how to describe an array using the syntax of the Array constructor.
COMMON OPERATIONS CREATE AN ARRAY
ACCESS AN ITEM USING AN ARRAY ITEM
LOOP OVER AN ARRAY
ADD AN ITEM TO THE STARTING OF AN ARRAY
REMOVE AN ITEM BY INDEXPOSITION
ARRAY PROPERTIES - Constructor-Returns the function that generated the prototype of the Array object - Length-Sets or returns the number of items in the list - Prototype-Allows you to add properties and methods to your Array set.
ARRAY METHODS 1. Concat() Joins two or more arrays and returns a copy of the attached arrays. 2. CopyWithin() Copies the array elements to and from the specified positions within the array. 3. Entries() Returns the Array Iteration Object key / value pair 4. Every() Tests whether any element in an array passes a test. 5. Fill() Fill the items in the array with a static value 6. Filter() Creates a new array for every element in the array that passes the test. 7. Find() Returns the value of the very first component in the test sequence. 8. FindIndex() Returns the index of the first item in the array that passes the test. 9. ForEach() Calls a function for each element of the array 10.form() Creates an array from that of an object 11.Includes() Check that the array contains the required element 12.IndexOf() Scan the array for an element and return its location 13.IsArray() Checks whether an object is an array 14.Connect() Connect all the array elements in a list 15.Keys() Returns an Iteration Object array containing the keys of the
original array 16.LastIndexOf() Find an element array, start at the end of the array and return its location. 17.Map() Generates a new array, resulting in the function being named for each array element. 18.Pop() Removes the very last element of the array and returns the element to a array. 19.Push() Adds new elements to the end of the array and returns the new length of the list 20.Reduce() Reduce the values of the collection to a single value (going left to right) 21.ReduceRight() Reduces the values of the array to a single value (going from right to left) 22.Reverse() Reverses the order of the objects in the list 23.Shift() Removes the first element of the array and returns the element 24.Some() Checks if any of the elements in the array have passed the test. 25.Sort() Sorts the array elements 26.Splice() Add / Remove elements via an array 27.ToString() Converts a string array and returns the result. 28.Unshift() Adds new elements to the start of the array, and returns a new length 29.ValueOf() Returns the primary value of the list
4. While-loops through a code block while the stated condition is true 5. Do / while-also loops through a code block while the stated condition is true
The condition is assessed first. If valid, the block of statements that follow the while statement will be executed. This is repeated until the condition is incorrect. It is known as a pre-test loop since it tests the condition before the block is executed. The number++ statement will be called the updater. Removing it will result in an endless loop. You must always provide a statement in the loop to ensure that the loop is terminated or else you will run into this problem.
DO WHILE LOOP
The next do block is executed first, and then the state is evaluated. If the while condition is valid, the block will be executed again and repeated until the condition is false. This is known as a post-test loop as the condition is tested after the block has been executed.
This consists of three sections, separated by semi-colons. The first is the initializer (var I = 1) which initializes the loop and is executed only once at the start of the loop. The second is the state of the test I < = 50). When the conditional expression is evaluated to true, the loop body is executed. The loop stops when it's right. The third element is an updater (i++) that is invoked after each iteration. Usually, the updater raises or reduces the loop counter. In a for-loop, all three phases, i.e. initializer, test condition, and updater, are written together in such a single line (called iteration statement), while in a while they are scattered and lying in different places.
FOR IN LOOP
Note that for-in loops also bring it back properties and methods that are inherited from the prototype chain. The built-in hasOwnProperty method is an simple way to bypass properties and functions that are not part of the object itself.
We haven't mentioned objects yet, but the student object has a name property on the object itself. Its prototype model has age properties. The for-in loop iterates through all properties, but hasOwnProperty guarantees that the age property on the prototype is not shown because it is not the student's own property.
When an infinite loop is deliberately created, you can use a break statement to control the end of the loop, as follows:
The number++; assertion will not be executed when the loop is entered for the 50th time.
In other loops, the continuous phrase is also found. However, in a for-loop it acts differently than in a time-loop. The for-loop first tests the i++ and then examines the I < = 50 condition in the example above. Now notice the time loop:
The power will be restored directly to the testing state when the continuous statement is carried out (number < = 50), and the number + + is not evaluated to create an infinite loop.. The lesson here is that you can't simply replace a for loop with a time loop; you have to be careful, particularly when a continuous statement is involved.
ITERATORS Iterator is a way to extract data from a one-to-one-time data structure, it requires to introduce an iterator interface. It's an object or pattern that helps us to go through a list or a set. Iterators define the sequences and enforce the iterator protocol that returns the object using the next() method that holds the value and is done. The value represents the next value of the sequence of the iterator, and the completed value is the true or false boolean value, if the last value of the sequence has been consumed, then the true value is false. We can check whether an entity is iterable by default or not
ITERATION PROTOCOL There can be two iteration protocols available: the Iterable protocol and the Iterator protocol.
ITERATOR PROTOCOL An object is an iterator when an interface (or an API) is implemented that addresses two questions: 1. Is there an aspect left?
2. If there is something, what is the element? An object is qualified as an iterator when it has a next() method which returns an object with two properties: - Done: a boolean value implying whether or not there are any other elements that could be iterated. - Value: this is the current dimension. Every time you call the next() returns the next value in the compilation:
When the final value returns, the following returns the result object as following if you call the next( )method:
The value of the finished property means that there is no interest to return and that the value of the property is set to undefined.
ITERABLE PROTOCOL An object is iterable if it includes a method called [Symbol.iterator] that does not use an argument and recovers an object that conforms to the iterator protocol. The [Symbol.iterator] is one of the excellently-known symbols of the ES6.
ITERATORS Since ES6 provides built-in iterators for the Array, Set, and Map collection forms, you don't need to create iterators for these objects. When you have a custom form and want to make it iterable so that you can use a loop construct, you need to enforce iteration protocols. The following code generates a sequence object that returns a list of numbers
within the range (start, end) with an interval between subsequent numbers.
The following code uses the Series Iterator for ... the loop:
You can directly access [Symbol.iterator] () as shown in the following script:
CLEANING UP In additional to the next() method, the [Symbol.iterator]()can optionally return the return() method. The returN() method is invoked automatically when the iteration is stopped early. It's where you can set up a application to clean up your tools. The following example uses the return() method for the Sequence object:
The following snippet uses the pattern object to generate an odd number
sequence from 1 to 10. However, the iteration ends prematurely. As a consequence, the return() method is invoked automatically OUTPUT
BY CREATING INTANSE OF OBJECT New keyword is used here to build an object. Let's see the example of directly creating an object
BY USING AN OBJECT CONSTRUTOR Here, you need to construct an argument function. Each argument value can be assigned to the current object and use this keyword. Each keyword refers to the current object . The example of creating an object by an object constructor is given below.
The following example is used to describe the method in the object.
ACCESS OBJECT KEYS Use for .. in loop to get a list of all the attributes and methods of an object.
13.Object.isExtensible() This method decides if an object is extensible. 14.Object.isFrozen() This method decides whether an entity has been frozen. 15.Object.isSealed() This method determines whether an object is sealed. 16.Object.keys() This method returns the property name list of the object. 17.Object.preventExtensions()This method is used to prevent any extension of an entity. 18.Object.seal() This method prevents the addition of new properties and labels all existing properties as non-configurable. 19.Object.setPrototypeOf() This method sets the prototype of the specified object to a different object. 20.Object.values() method returns a set of values.
Using the keyword class to build a package, and always apply the constructor() method to it. The constructor method is called any time a class object is initialized. Example
The constructor method will be called automatically when the object is initialized.
Example Create a method named “present”
As you can see in the example above, you call the method by making reference to the method name of the object followed by the brackets (any parameters would be inside the brackets).
STATIC METHOD Static methods are specified on the class itself, not on the prototype. This means that you can't call the static method on the object (mycar) but on the class (car):
INHERITANCE Using the extended keyword to construct a class inheritance. A class generated with a class inheritance inherits all methods of another class:
Example: Create "Model" class, that inherits the methods of the "Car" class: The super( ) method is the parent class. We also called the super() method in the builder method and referred to the parent properties and the properties of the constructor method.
GETTERS AND SETTERS Classes also permit you using a getters and a setter. It can be smart to use getters and setters for your properties , especially if you're doing something special with a value before you return it, or before you set it. Using the get and set keywords to connect the getters and the setters in the class. Example: Build a getter and a seter for the "carname" property: Even if the getter is a method, you don't use brackets when you want to get the value of the property. In this scenario, the name of the getter / setter method could not be the same as the name of the property.
BROWSERCOMPATIBILITY ANDTRANSPILATION Recently, a good application or website has become much more than a static collection of divisional elements. Modern websites are interactive,
WHY WOULD YOU STILL TRANSPILE? We use React JSX (which currently is very common, so I assume a lot of developers suit this category). At its heart is an XHTML-to-JS-code transformation, not involving a complete transpiler such as Babel. Furthermore, if VirtualDom is all you need, use it instead.
The latest features of the language are to be tried. With ES6 you probably do well if you do not belong to TC39 or have a burning urge to insert volatile language characteristics into your production code. Nowaday, the majority of browsers have a decent language and the need to transpile disappears. You use TypeScript to weighed the drawbacks and advantages. TypeScript compiler typically stretches type knowledge rather than transform syntax when targeting a modern version of ES6. You would like to reduce code by shaking tree (in webpacks and rollups, this is how to do so). You want to obscure or reduce your code by decreasing its size. You want to delete part of the code on condition. Static code analysis is needed. You can use an intelligent bundler for size-sensitive production services, such as Mobiles, but when creating such alternative deployments, we will see more detailed cost evaluations. These kinds of static code analyses are still useful for production code as "advanced optimization techniques." Your files don't need to be minified. At the moment (although a harm branch is present), UglifyJS can not minify ES6, but Babili can deal. Compression algorithms do a reasonable job (not if the files are too small) and it should do all right without a compression unless you give an operating systems with every page load. Images and multimedia content nowadays take far more bandwidth than code.
DON’T TRANSPILE,BUT COMPILE FOR REAL. WASM is the kid in the city and the official building target promises speed and smaller code size. Chrome and Firefox currently support WASM, but the big browser vendors agree that WASM will be the most common run-times of the future. You can try it if you have Chrome. Take a look at Rust if you're the kind of developer that hits for something new. It is WASM compiled, but not web-limited. People actually use it to write a browser or an operating system. In addition to old days, C / C++ developers support it and like it.
MODULES We want to split this application into several files as our application grows
WHAT IS A MODULE? Only a file is a module. A single module is a script. Just that simple. Modules can load each other and export and import special directives, calling from one other module functions, in order to interchange functionalities: Export variables and functions of keyword labels which should be accessible from outside the current module. Import enables the import of other modules functionality. Let's run the in-browser example. As modules support keywords and special features, the user should be told that a script needs to be treated as a module with the < script type="module "> attribute.
Example: ANONYMOUS CLOSURE
Our anonymous function has a self-assessment environment or "closure" with this structure, and then we evaluate immediately. This allows us to hide parent (global) namespace variables.
What is nice about this method is that, without overwriting existing global variables accidentally, you could still access global variables in this function:
As you can see, this approach allows us to decide which parts / methods we
want to keep private (for example myGrades) and which by adding them to our return statement (for example average / failure).
EXAMPLE: REVEALING AND MODULE PATTERN This is very similar to the approach described above, with the exception that all methods and variables are kept private unless specifically stated:
COMMONJS AND AMD
One feature in particular is, above all, the use of a single global variable in order to bundle the code into a function creating a private namespace for itself with a closing scope. We do have their downsides though each solution is successful in its own way. First, as a developer, you have to know how to load your files in the right dependency. For example , let us assume that in your project you are using Backbone, so you include in your file the scripting tag for the source code of Backbone. However, since Backbone has a strong dependency on Underscore.js, the Backbone script tag can not be set before underscore.js. As a developer it can sometimes be a headache to manage dependencies and correct these things. Another disadvantage is that they can lead to collisions with namespace. For example, what if you have the same name for two of your modules? Or what if you have two module versions, and both are needed? So you probably wonder: can we design a way to ask for the interface of the module without crossing the global scope? The response is yes, luckily. The commonJS and AMD approaches are two prominent and well implemented.
context (like closing them). We use the.exports object module to expose and import modules in this field. It could look like this when you define the CommonJS module
We use special object module and place a link in module.exports for our purpose. This allows the CommonJS module system to know what we want to expose to other files. Then, you can require myModule to be in your file, if someone wants to use it:
AMD CommonJS is great and good, but what if we want to asynchronously load modules? The response is called the definition for the Asynchronous Module or shortly AMD. It looks something like the loading of modules with AMD:
What takes place here is that the function defined takes each of the module's dependencies as its first argument. These dependances are loaded (not blocking) in the background, and the callback function it has been provided when it is loaded is specified. Next, in the case of myModule and MyOtherModule the callback function takes, in argument, the dependencies that were loaded to allow the application to use these dependencies. The dependencies also have to be specified with the given keyword. Example: MyModule may look like this
Again, unlike CommonJS, AMD uses the first browser method to complete the job along with asynchronous behaviour. (Note that it's not very beneficial to load files dynamically when you start running code, and we're going to explore that when you start creating a modules in the next section). In addition to asynchronicity, your modules can be objects, functions, constructors, strings, JSON and many more, while CommonJS supports objects as modules only.
closed set of private variables and methods.
BENEFITS OF PROMISE - Enhances readability of code - Better management of asynchronous operations - Best flow of asynchronous logic control description - Effective Handling of Error A promise is a symbol for a value unknown when the commitment is made. It enables you to combine handlers with the eventual success value or failure reason for an asynchronous action. This allows asynchronous methods to return values like synchronous methods: the asynchronous method returns an undertaking to deliver the value in future rather than returning the final value immediately.
A PROMISE HAS THREE STATES Fulfilled: Promise action successful Rejected:concerning the promise failed denied Pending:Promise is still pending and has not yet been fulfilled or refused If a promise is not pending (it was accepted or rejected), a promise is fulfilled. Often people are resolute and resolute: they don't have to hesitate.
PROMISE CAN BE CREATED USING PROMISE CONSTRUCTOR - Promise constructor takes only a single request, a function callback. - Two points, resolution and deny function Callback. - Conduct operations in the callback function and call resolve if all goes well. - If you do not perform well, call reject.
OUTPUT: Success you are a Geek
1. Then( )
Then( ) is used if a promise is either accepted or refused, it is invoked. PARAMETRES • If promise is fulfilled and tests are obtained, the first task will be performed. • If promise is ignored and an error occurs, the second task is carried out .It is optional and it's better to use the .catch() method to find errors EXAMPLE : PROMISE RESOLVED
OUTPUT: Geeks for Geeks EXAMPLE: PROMISE REJECTED
OUTPUT: Promise Rejected
2. CATCH( )
When a promise is either refused or an error occurred during execution, catch( ) is invoked. EXAMPLE : PROMISE REJECTED
OUTPUT: PROMISE REJECTED
EXAMPLE: PROMISE REJECTED
OUTPUT: SOME ERROR HAS OCCURRED
3. FINALLY( ) Often you want to execute the same code if you are fulfilling or refusing the
promise. For example:
For both then() and catch() methods, the call to createApp() is duplicated, as you can see. You use finally( )methods like this in order to delete this duplication and execute createApp() if the promise is fulfilled or rejected:
APPLICATIONS: 1. Promises are used for asynchronous handling of Errors 2. Promises are handled with asynchronous http requests.
SUMMARY 1. An object which returns a value in the future is a promise. 2. A promise begins in the state to be fulfilled or denied in the State to be fulfilled. 3. Using then() method to schedule a callback for fulfillment of the pledge, and catch() method to schedule a callback for rejection. 4. In the finally() process, place the code you want to execute whether the promise is fulfilled or rejected.
OUTPUT: Hello World
OUTPUT: Hello World Note that the console prints 2 in front of "Hello World." This is due to the use of the keyword waiting for you.
SUPPORTED BROWSERS: The Async / Await Function supported browsers are listed below: Google's Chrome Firefox Firewall Apple's Safari Opera
CONCLUSION And here you can – async / await provides a good, easier to read and maintain async code. Even with browser support becoming more limited than other asynchronous code mechanisms at the time of writing, it is very well worth learning and contemplating for use, now and in the coming years.
REQUEST A resource request is defined by the Fetch API Request interface. Using the Request( )constructor to generate a new Request object; however, as a result of another API operation such as a FetchEvent.request service worker it is likely to have a Request object returning. The absence of navigation or reload of a page includes the capability of
SEND A REQUEST TO SERVER We use open( )and send( )methods for the XMLHttpRequest object to send a request to a server: Open(method, url, async) Into the application form • Method: the application type: GET or POST • URL: position of the server (file) • Async: true(asychronous) or false (synchronous) • Send() request (used for GET) to the server • Send(string) Sends the to the server program (POST-used)
GET OR POST? In most cases the GET is easier and quicker than POST. Use POST requests, however, when: No cached file (update a file or server database) is open. Send a lot of data to the server (POST does not have any size restrictions). POST is more robust and reliable than GET when sending user inputs (which may contain unknown characters).
If you want to use the GET method to send information, add it to the URL:
Add an HTTP header using setRequestHeader( ) to the POST data as an HTML type. In send( )method, enter the data you want to send:
Adds HTTP headers to request in setRequestHeader(header, value). Header: Enter the name of the header Value: sets the value of the header
ASYNCHRONOUS- TRUE OR FALSE?
THE ONREADYSTATECHANGE PROPERTY You can set a function to be implemented when the request gets an answer using the XMLHttpRequest object. The function is specified in the XMLHttpRequest object's onreadystatechange property:
SYNCHRONOUS REQUEST Change the third parameter in the open() method to false in order to perform a synchronous request: xhhtp.open(Get, "ajax info.txt", false);
The XMLHttpRequest (async = false) synchronous is not suggested, because
- Immutability: When its value can not change after development, a variable is immutable. You may change a mutable variable. - Scope: In which part of the program a variable is visible, is the scope referred to as a variable. Let and const have the scope of the block, determining the differential range from the var values which have the function scope. - Scoping: Scoping is how the number of variables and functions are calculated in the programming language. For examples, we can have scoping blocks, scoping functions, lexical scoping.