IT Notes - in
IT Notes - in
ECMA Script: ECMA Script versions, ES5 Features, ES6 introduction, Var Declarations and
Hoisting, let declaration, Constant declaration, function with default parameter values, default
parameter expressions, unnamed parameters, the spread operator, arrow functions, object
destructuring, array destructuring, sets and maps, Array.find(), Array.findIndex(), template strings,
Javascript classes, callbacks, promises, async/await
ECMAScript 6 (ES6)
ES6 Variables
var vs let
There are rules for naming the variable identifier. These are:
function myFunc() {
if(true) {
var my_var = 'test';
}
console.log(my_var); // test
}
function myFunc() {
if(true) {
let my_var = 'test';
}
console.log(my_var); // TypeError
}
function myFunc() {
let my_var = 'test';
if(true) {
let my_var = 'new test';
console.log(my_var); // new test
}
console.log(my_var); // test
}
Variables declared by const (constants) cannot be changed. However, with a for loop the scope is
redeclared at the start of each loop, where a new const can be initalized.
ES6 for/of
The for/of loop uses the iterable protocol to create a loop. Strings, Arrays, TypedArray, Map,
Set, NodeList, and custom iterable function hooks can all be used with for/of.
console.log(number) // 1 2 3
Let’s take a look at the ES5 string and refactor it using a template literal.
// ES5 string
let myName = 'Tony Nguyen'
To create a template literal, just use the backtick(`) character instead of the single or double
quotes. The backtick the same key as the ~ key usually below the escape key.
It really is that simple. Now that you know how to write a template string let’s take a look at
some of the things you can do with template strings.
Template literals are very handy for strings that use variables, or need to make use of a quick
javascript expression. Template literals are enclosed with the back-tick. Template literals can
also have placeholders,these are declared with a dollar sign and curly braces ${placeholder}.
const count = 0;
console.log(`${count + 1}`); // 1
Arrow functions are useful for anonymous functions, however their power is with the lexical
scoping of this.
function es6LexicalScope() {
this.timeSpentSeconds = 0;
setInterval(() => {
console.log(this.timeSpentSeconds++); // 1 2 3 ...
}, 1000);
}
es6LexicalScope();
const person = { name: 'Bill', age: 42, email: '[email protected]', url: 'http://example.ca' };
const {name, age} = person;
console.log(name, age); // Bill, 42
Sometimes you want to keep all the other stuff. That is where the spread operator ... comes in
handy.
const person = { name: 'Bill', age: 42, email: '[email protected]', url: 'http://example.ca' };
const {name, age, ...details} = person;
console.log(name, age, details); // Bill, 42, {email: '[email protected]', url: 'http://example.ca'}
obj now has our person property with our person Bill. If the person
property was already set in otherObj then we would override that property. Let's look at
unpacking the length property from a string with destructuring.
Spread Operator
Spread syntax (...) allows an iterable such as an array expression or string to be expanded in
places where zero or more arguments (for function calls) or elements (for array literals) are
expected, or an object expression to be expanded in places where zero or more key-value pairs
(for object literals) are expected.
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
console.log(sum.apply(null, numbers));
// expected output: 6
Spread syntax can be used when all elements from an object or array need to be included in a list
of some kind.
In the above example, the defined function takes x, y, and z as arguments and returns the sum of
these values. An array value is also defined.
When we invoke the function, we pass it all the values in the array using the spread syntax and
the array name — ...numbers.
Rest parameters
The rest parameter syntax allows a function to accept an indefinite number of arguments as an
array, providing a way to represent variadic functions in JavaScript.
function sum(...theArgs) {
});
console.log(sum(1, 2, 3));
// expected output: 6
console.log(sum(1, 2, 3, 4));
// expected output: 10
function addToFive(addTo = 0) {
return addTo + 5;
}
const ex1 = addToFive();
const ex2 = addToFive(5);
console.log(ex1, ex2); // 5, 10
JavaScript sets and maps have been around for a few years now, but I still get a lot of questions
about them. My students wonder if they should be substituting traditional objects and arrays with
these new data types. While there are some killer use cases for sets and maps, you should really
look at them like specialized tools and not Swiss army knives.
Array.find()
This method returns the value of the first element in the provided array that satisfies the provided
testing function. If no values satisfy the testing function, undefined is returned.
Example:
console.log(found);
// output: 12
Promises in JavaScript
There are two parts to understanding promises. Creation of promises and Handling of
promises. Though most of our code will generally cater to handling of promises created by other
libraries, a complete understanding will help us for sure. Understanding of “creation of
promises” is equally important once you cross the beginner stage.
Creation of Promises
Now that we know how to create a promise. Let us create a simple promise for our
understanding sake.
var keepsHisWord;
keepsHisWord = true;
promise1 = new Promise(function(resolve, reject) {
if (keepsHisWord) {
resolve("The man likes to keep his word");
} else {
reject("The man doesnt want to keep his word");
}
});
console.log(promise1);
Since this promise gets resolved right away we will not be able to inspect the
initial state of the promise. So let us just create a new promise that will take
some time to resolve. The easiest way for that is to use the setTimeOut
function.
The above code just creates a promise that will resolve unconditionally after 10
seconds. So we can checkout the state of the promise until it is resolved.
Promises,callbacks and async/await are all ways to deal with asynchronous data.Basically
asynchronous is when something is going on but you don't want to wait till its done to
continue,and you want to continue while it's happening asynchronously rather than synchronous
programming where something happens where you wait till it finishes to move on to the next.
With the introduction of ES6 promises were introduced to the language.Promises provide us with
a more elegant way to handle asynchronous data.
In ES7,async/await were introduced which deals with promises in an even more elegant way as it
looks more like synchronous programming.
Callbacks
A callback is a function passed as an argument to another function.This technique allows a
function to call another function.A callback function can run after another function has finished
Let us consider a hypothetical situation where we get posts and create post from a server.Lets use
a setTimeout to mimic the time lapse given by the server.
Lets have an array called posts that contains two objects and create a function called getPosts
const posts=[
{title:'Post One',body:'This is post one'},
{title:'Post Two',body:'This is post two'}
];
function getPosts() {
setTimeout(()=> {
let output = '';
posts.forEach((post,index)=> {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
},1000);
}
getPosts();
const posts=[
{title:'Post One',body:'This is post one'},
{title:'Post Two',body:'This is post two'}
];
function getPosts() {
setTimeout(()=> {
let output = '';
posts.forEach((post,index)=> {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
},1000);
}
function createPost(post){
setTimeout(()=> {
posts.push(post);
},2000);
}
getPosts();
But now we don't see the post three because the create post took longer than the getPost which
happened in 1 second and by the time post was created the DOM was already painted.
This is where asynchronous programming comes in.Callbacks are one of the ways to do handle
this.
Now lets have the createPost also take in a function called callback and call the callback() right
after the post is pushed.
function getPosts() {
setTimeout(()=> {
let output = '';
posts.forEach((post,index)=> {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
},1000);
}
function createPost(post,callback){
setTimeout(()=> {
posts.push(post);
callback();
},2000);
}
Now it will wait 2 seconds and call the entire posts array.
Promises
A Promise is a proxy for a value not necessarily known when the promise is created. It allows
you to associate handlers with an asynchronous action's eventual success value or failure reason.
This lets asynchronous methods return values like synchronous methods: instead of immediately
returning the final value, the asynchronous method returns a promise to supply the value at some
point in the future.
Considering the same example lets use the same array and getPost function.
But now instead of using a callback to handle the createPost lets use a promise.
const posts=[
{title:'Post One',body:'This is post one'},
{title:'Post Two',body:'This is post two'}
function getPosts() {
setTimeout(()=> {
let output = '';
posts.forEach((post,index)=> {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
},1000);
}
function createPost(post){
return new Promise((resolve,reject) => {
setTimeout(()=> {
posts.push(post);
if(!error) {
resolve();
} else {
reject('Error:Something is wrong');
}
},2000);
});
}
resolve
reject
When we want to resolve a promise a successfully,we will call the resolve and when something
goes wrong or if there is an error we will call reject.
Now we are not going to pass a callback function and since its returning a promise we will
handle it using .then.
The .catch that is used after the .then is used for error handling if the promise is rejected.
There will be a lot of instances where we might have to deal with promises like when we use
axios,fetch,mongoose..etc and most of the time we will just be required to respond to the promise
but the above code is a good example on how to create a promise yourself.
//Promise.all
The promise.all will return after all the promises are done and it will take time until the longest
promise is handled.
Async/Await
These features basically act as syntactic sugar on top of promises, making asynchronous code
easier to write and to read afterwards. They make async code look more like old-school
synchronous code, so they're well worth learning.
The keyword async before a function makes the function return a promise.The keyword await
before a function makes the function wait for a promise.The await keyword can only be used
inside an async function.
Place the createPost function inside a new function and prefix the async keyword to the function
which will make it asynchronous and before calling createPost prefix it with await and call the
getPosts below it.
const posts=[
{title:'Post One',body:'This is post one'},
{title:'Post Two',body:'This is post two'}
];
function createPost(post){
setTimeout(()=> {
posts.push(post);
},2000);
}
init()
When the init function is called,the await waits till the process is done and once completed it will
move to the next and call the getPosts function.
What is jQuery?
jQuery is a lightweight, "write less, do more", JavaScript library.
The purpose of jQuery is to make it much easier to use JavaScript on your website.
jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish,
and wraps them into methods that you can call with a single line of code.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM
manipulation.
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
jQuery Syntax
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on
the element(s).
Examples:
jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes,
types, attributes, values of attributes and much more. It's based on the existing CSS Selectors,
and in addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().
The jQuery element selector selects elements based on the element name.
$("p")
Example
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to find a
single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the HTML
element:
$("#test")
When a user clicks on a button, the element with id="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
For example, jQuery provides .insertAfter() and .after(). The .insertAfter() method places the
selected element(s) after the element provided as an argument. The .after() method places the
element provided as an argument after the selected element. Several other methods follow this
pattern: .insertBefore() and .before(), .appendTo() and .append(),
and .prependTo() and .prepend().
The method that makes the most sense will depend on what elements are selected, and whether
you need to store a reference to the elements you're adding to the page. If you need to store a
reference, you will always want to take the first approach – placing the selected elements relative
to another element – as it returns the element(s) you're placing. In this
case, .insertAfter(), .insertBefore(), .appendTo(), and .prependTo() should be the tools of choice.
Cloning Elements
Methods such as .appendTo() move the element, but sometimes a copy of the element is needed
instead. In this case, use .clone() first:
When you create a new element, it is not immediately added to the page. There are several ways
to add an element to the page once it's been created.
myNewElement.appendTo( "#content" );
You can also create an element as you're adding it to the page, but note that in this case you don't
get a reference to the newly created element:
1
// Creating and adding an element to the page at the same time.
$( "ul" ).append( "<li>list item</li>" );
2
The syntax for adding new elements to the page is easy, so it's tempting to forget that there's a
huge performance cost for adding to the DOM repeatedly. If you're adding many elements to the
same container, you'll want to concatenate all the HTML into a single string, and then append
that string to the container instead of appending the elements one at a time. Use an array to
gather all the pieces together, then join them into a single string for appending:
Manipulating Attributes
jQuery's attribute manipulation capabilities are extensive. Basic changes are simple, but
the .attr() method also allows for more complex manipulations. It can either set an explicit value,
or set a value using the return value of a function. When the function syntax is used, the function
receives two arguments: the zero-based index of the element whose attribute is being changed,
and the current value of the attribute being changed.
.each()
The .each() method is designed to make DOM looping constructs concise and less error-prone.
When called it iterates over the DOM elements that are part of the jQuery object. Each time the
callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the
callback is fired in the context of the current DOM element, so the keyword this refers to the
element.
<ul>
<li>foo</li>
<li>bar</li>
</ul>
You can select the list items and iterate across them:
You can stop the loop from within the callback function by returning false.
.addClass()
Adds the specified class(es) to each element in the set of matched elements.
.attr()
Get the value of an attribute for the first element in the set of matched elements or set one or
more attributes for every matched element.
.hasClass()
Determine whether any of the matched elements are assigned the given class.
.html()
Get the HTML contents of the first element in the set of matched elements or set the HTML
contents of every matched element.
.prop()
Get the value of a property for the first element in the set of matched elements or set one or more
properties for every matched element.
.removeAttr()
Remove an attribute from each element in the set of matched elements.
.removeClass()
Remove a single class, multiple classes, or all classes from each element in the set of matched
elements.
.removeProp()
Remove a property for the set of matched elements.
Events
These methods are used to register behaviors to take effect when the user interacts with the
browser, and to further manipulate those registered behaviors.
.bind()
Attach a handler to an event for the elements.
.blur()
Bind an event handler to the “blur” JavaScript event, or trigger that event on an element.
.change()
Bind an event handler to the “change” JavaScript event, or trigger that event on an element.
.click()
Bind an event handler to the “click” JavaScript event, or trigger that event on an element.
o Browser Events
o Document Loading
o Event Handler Attachment
o Event Object
o Form Events
o Keyboard Events
o Mouse Events
eventType
Type: String
A string containing one or more DOM event types, such as "click" or "submit," or custom event
names.
handler
In addition to providing fine-grained control over how specific style properties are
handled, $.cssHooks also extends the set of properties available to the .animate() method.
Defining a new css hook is straight-forward. The skeleton template below can serve as a guide to
creating your own.
(function( $ ) {
if ( !$.cssHooks ) {
throw( new Error( "jQuery 1.4.3 or above is required for this plugin to work" ) );
// if they exist.
$(function () {
$.cssHooks[ "someCSSProp" ] = {
};
});
})( jQuery );
The .contents() method can also be used to get the content document of an iframe, if the iframe is
on the same domain as the main page.
Consider a simple <div> with a number of text nodes, each of which is separated by two line
break elements (<br>):
<div class="container">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
<br><br>
Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.
<br><br>
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur.
</div>
We can employ the .contents() method to help convert this blob of text into three well-formed
paragraphs: