fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,64 @@
---
title: Arrow Functions
---
## Arrow functions
Functions in ES6 have changed a bit. I mean the syntax.
```javascript
// Old Syntax
function oldOne() {
console.log("Hello World..!");
}
// New Syntax
var newOne = () => {
console.log("Hello World..!");
}
```
The new syntax may be confusing a little bit. But I will try to explain the syntax.
There are two parts of the syntax.
1. var newOne = ()
2. => {}
The first part is just declaring a variable and assigning the function (i.e) () to it. It just says the variable is actually a function.
Then the second part is declaring the body part of the function. The arrow part with the curly braces defines the body part.
Another example with parameters:
```javascript
let NewOneWithParameters = (a, b) => {
console.log(a+b); // 30
}
NewOneWithParameters(10, 20);
```
Parentheses are optional when there's only one parameter name:
```javascript
let newOneWithOneParam = a => {
console.log(a);
}
```
An incredible advantage of the arrows function is that you can not rebind an arrow function. It will always be called with the context in which it was defined. Just use a normal function.
```javascript
// Old Syntax
axios.get(url).then(function(response) {
this.data = response.data;
}).bind(this);
// New Syntax
axios.get(url).then(response => {
this.data = response.data;
});
```
I dont think I need to give an explanation for this. It's straightforward.

View File

@ -0,0 +1,55 @@
---
title: Default Parameters
---
## Default Parameters
If you are familiar with other programming languages like Ruby, Python then default parameters isnt new to you.
Default parameters are parameters which are given by default while declaring a function. But its value can be changed when calling the function.
Example
```
let Func = (a, b = 10) => {
return a + b;
}
Func(20); // 20 + 10 = 30
```
In the above example, we are passing only one parameter. The function makes use of the default parameter and executes the function.
Consider another example:
```
Func(20, 50); // 20 + 50 = 70
```
In the above example, the function takes two parameters and the second parameter replaces the default parameter.
Consider another example:
```
let NotWorkingFunction = (a = 10, b) => {
return a + b;
}
NotWorkingFunction(20); // NAN. Not gonna work.
```
When you are calling the function with parameters they get assigned in the order. (i.e) the first value gets assigned to the first parameter and the second value gets assign to the second parameter and so on..
In the above example, the value 20 gets assigned to parameter a and b is not having any value. So we are not getting any output.
But,
```
NotWorkingFunction(20, 30); // 50;
```
Works fine.
However, if you want to use the default first parameter, you can pass `undefined` as the first argument of the function call.
```
NotWorkingFunction(undefined, 30); // 40;
```

View File

@ -0,0 +1,72 @@
---
title: Destructuring Assignment
---
## Destructuring Assignment
Destructuring Assignment syntax is a Javascript expression that makes it possible to unpack values or properties from arrays or objects.
Lets say that you have an array that contains a first name and last name as it's two values, but you want to reassign those values to something more descriptive. You can use Destructuring to accomplish this.
**ES5 Destructuring**
```js
var fullName = ["John", "Smith"];
var firstName = fullName[0];
var lastName = fullName[1];
console.log(firstName, lastName); // John Smith
```
**ES6 Destructuring**
```js
const fullName = ["John", "Smith"];
const [firstName, lastName] = fullName;
console.log(firstName, lastName); // John Smith
```
The examples above show the benefit of using the ES6 Destructuring Assignment.
You can also use Destructuring on objects using a similar syntax
```js
const fullName = { first: "John", last: "Smith"};
const {first, last} = fullName;
console.log(first, last); // John Smith
```
Object Destructuring Assignment is a little bit different because the object must have properties with the names you are assigning. Therefore the code below would not work as intended.
```js
const fullName = { first: "John", last: "Smith"};
const {firstName, lastName} = fullName;
console.log(firstName, lastName); // undefined undefined
```
You can still achieve the desired result using the following syntax.
```js
const obj = {propertyName: value}
const {propertyName: desiredVariableName} = obj
```
Our previous example would be rewritten as follows:
```js
const fullName = { first: "John", last: "Smith"};
const {first: firstName, last: lastName} = fullName;
console.log(firstName, lastName); // John Smith
```
**Array Destructuring with rest**
When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:
```js
const [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
```

View File

@ -0,0 +1,96 @@
---
title: for-of loop
---
## for-of Loop
for-of loop can be used to iterate over the things which are not arrays but are iterable like a DOM collection, string, set, arguments or map.
```javascript
const fruits = ['Orange','Apple','Grapes','Banana'];
for (const fruit of fruits)
{
console.log(fruit);
}
```
The above snippet is going to return us the items in the array above.
## for-of loop in knowing index
What if we want to know the index of each item too.In that case we can iterate over fruits.entries() which gives us the ArrayIterator.
```javascript
for (const fruit of fruits.entries())
{
console.log(fruit);
}
```
In the above snippet, fruit is going to be an array with two items. 0th item is going to contain the index and the 1st item would contain the actual fruit name.The output would be like :
```
[0, "Orange"]
[1, "Apple"]
[2, "Grapes"]
[3, "Banana"]
```
We can further destructure fruit like below:
```javascript
for (const [index,fruit] of fruits.entries())
{
console.log(index,fruit);
}
```
## for-of loop in iterating over unknown number of arguments
for-of loop is very helpful in iterating over the unknown number of arguments to a function.
Suppose we want to add the numbers which are passed to a function and the number of arguments is not fixed.
'arguments' is a special keyword in javascript which gives us the Array-ish (not array) type and gives us all of the arguments.
```javascript
function addNumbers()
{
let sum = 0;
for (const num of arguments)
sum+=num;
return sum;
}
addNumbers(1, 2, 3, 4, 5); // 15
```
Here arguments is not a true array still we can iterate over it using for-of loop.
## for-of loop to iterate over string
We can use for-of loop to iterate over string to give us character by character of the string.
```javascript
const name = 'John Doe';
for (const char of name)
console.log(char);
```
which results in following output:
characters 'J' ,'o','h','n',' ','D','o','e'
## for-of loop to iterate over DOM collection
DOM collections are not the true array type. They are usually NodeList for most of the browsers. If we create a number of paragraphs and want to iterate over them to assign some event on each of paragraph, we can make use of for-of loop.
```javascript
const paragraphs = document.querySelectorAll('p');
```
Here paragraphs is a NodeList which can be iterated over using for-of loop.
```javascript
for (const para of paragraphs)
{
console.log(para);
// We can add event listeners to each para here
}
```

View File

@ -0,0 +1,58 @@
---
title: ES6
---
## ES6
The 6th edition of ECMAScript is called ES6.
It is also know as ES2015.
The changes add a lot of syntactic sugar that allow developers to create applications in an object oriented style.
> ES5 example:
```javascript
var User = function () {
function User(name) {
this._name = name;
}
User.prototype.getName = function getName(x) {
return 'Mr./Mrs. ' + this._name;
};
return User;
}();
```
> ES6 example:
```javascript
class User {
constructor(name) {
this._name = name
}
getName() {
return `Mr./Mrs. ${this._name}`
}
}
```
A lot of new syntax features were introduced including:
- classes,
- modules,
- templating,
- for/of loops,
- generator expressions,
- arrow functions,
- collections,
- promises.
Nowadays most of the features are available in all popular browsers. The <a href='https://kangax.github.io/compat-table/es6/' target='_blank' rel='nofollow'>compatibility table</a> contains all information about feature availability of all modern browsers.
Frequently new features arrive that are part of the successor ES7. A common way is to translate modern JavaScript (ES6, ES7 and other experimental proposals) to ES5. This makes sure that also old browsers can execute the code. There are tools like <a href='https://babeljs.io/' target='_blank' rel='nofollow'>Babel</a> that transforms new JavaScript to ES5.
Besides syntactic sugar coming from ECMAScript standards there are features that require a <a href='https://babeljs.io/docs/usage/polyfill' target='_blank' rel='nofollow'>Polyfill</a>. Usually they are necessary because whole class/method implementations were added to the standard.

View File

@ -0,0 +1,52 @@
---
title: Let and Const
---
## Let
let is similar to var but let has scope. let is only accessible in the block level it is defined.
```
if (true) {
let a = 40;
console.log(a); //40
}
console.log(a); // undefined
```
In the above example variable a is defined inside an If statement and so its not accessible outside of the function.
Another example:
```
let a = 50;
let b = 100;
if (true) {
let a = 60;
var c = 10;
console.log(a/c); // 6
console.log(b/c); // 10
}
console.log(c); // 10
console.log(a); // 50
```
## Const
Const is used to assign a constant value to the variable. And the value cannot be changed. It's fixed.
```
const a = 50;
a = 60; // shows error. You cannot change the value of const.
const b = "Constant variable";
b = "Assigning new value"; // shows error.
```
Consider another example.
```
const LANGUAGES = ['Js', 'Ruby', 'Python', 'Go'];
LANGUAGES = "Javascript"; // shows error.
LANGUAGES.push('Java'); // Works fine.
console.log(LANGUAGES); // ['Js', 'Ruby', 'Python', 'Go', 'Java']
```
This may be little confusing.
Consider in this way. Whenever you define a const variable, Javascript references the address of the value to the variable. In our example the variable LANGUAGES actually references to the memory allocated to the array. So you cannot change the variable to reference some other memory location later. Throughout the program it only references to the array.

View File

@ -0,0 +1,24 @@
---
title: Map Function
---
## The Map Function
The `map()` function is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.
The original syntax of the map function is:
```javascript
let new_arr = arr.map(function callback(currentValue, index, array) {
// Do some stuff with currentValue (index and array are optionals)
})
```
### Example (ES6):
```javascript
const myArray_1 = [1, 2, 3, 4];
const myArray_2 = myArray_1.map(el => el * 2);
```
`myArray_2` will contain the elements: `[2, 4, 6, 8]`
`map()` is a method of the `Array` object, so to pass that function to an iterable object it is necessary to make the object an Array.

View File

@ -0,0 +1,64 @@
---
title: New String Functions
---
## New String Functions
Following four functions are added new to strings in ES6.
* startsWith
* endsWith
* includes
* repeat
## startsWith:
This is a case sensitive function which helps us to find if a particular string starts with some substring.
startsWith takes in the second optional argument called position which we can use in case when we want to skip particular number of characters from the beginning of the string before searching.
```javascript
const str ='Rachna';
str.startsWith('Rad') //false
str.startsWith('ra') //false as it is case sensitive
str.startsWith('Ra') //true
str.startsWith('ch',2) //true as we are searching from the second position
str.startsWith('ch',3) //false
```
## endsWith
This is a case sensitive function which helps us to find if a particular string ends with some substring.
endsWith takes in a second optional argument called endPosition which we can use to include the number of characters before searching.
```javascript
const city= 'Delhi';
city.endsWith('Hi'); //false as it is case sensitive
city.endsWith('hi');//true
city.endsWith('l',3);//true - include only first three characters before searching
city.endsWith('l',4);//false
```
## includes
includes function is also a case sensitive function that checks if the searchString is present anywhere in the string.
```javascript
const name='John Doe';
name.includes('do'); //false
name.includes('D'); //true
name.includes('Do'); //true
```
## repeat
repeat allows us to take a string and repeat it a number of times.
```javascript
const str = 'This is repeated';
str.repeat(3); //"This is repeatedThis is repeatedThis is repeated"
```
repeat function can be used to pad a string from Left with a number of spaces.

View File

@ -0,0 +1,25 @@
---
title: Some Function
---
## The Some Function
The `some()` function is used for verifying if at least one element of an array meets a given condition. The function returns `true` if the condition is met by one element, and false if any of the elements met the condition
The original syntax of the some function is:
```javascript
arr.some(function callback(currentValue, index, array) {
// Do some stuff with currentValue (index and array are optionals)
}, [thisArg]);
```
### Example (ES6):
```javascript
const arr = [1, 4, 5, 11];
if (arr.some(el => el % 2 == 0)) {
console.log("There's at least one even number");
}
```
`some()` is a method of the `Array` object, so to pass that function to an iterable object it is necessary to be sure that the object is an Array.

View File

@ -0,0 +1,23 @@
---
title: Spread Operator
---
## Spread Operator
The spread operator (`...`), allows to get the elements of a collection.
One of the most commom uses is for `Node` Objects, when using query selectors in the browser, in order to make them iterable Array Objects:
```javascript
const paragraphs = document.querySelectorAll('p.paragraph');
const arr = [...paragraphs];
```
Another use of the spread operator is for Array concatenation:
```javascript
const arr_1 = [1, 2, 3, 4]
const arr_2 = [5, 6, 7, 8]
const arr_final = [...arr_1, ...arr_2]
// arr_final = [1, 2, 3, 4, 5, 6, 7, 8]
```
### More Information:
- [MDN - Spread Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)

View File

@ -0,0 +1,67 @@
---
title: Template Literals
---
## Template Literals
## Introduction:
When we want to use variable to make a string, it becomes very painful as we have to use + sign to concatenate and keep track of quotes.
Now with ES6,We can make string using backticks and using placeholders which are indicated with dollar sign and curly braces, like ${expression } .
```javascript
const name='John';
const city='London';
Older Style:
const sentence ='My name is '+ name +'. I live in '+city.
ES6 way:
const sentence = `My name is ${name}. I live in ${city}`;
Here ${name} and ${city}are going to be interpolated by the variable name and city respectively.
```
## MultiLine Strings:
Older style:
When we wanted to span our string into multiple lines, we had to use backslashes.
```javascript
const multipleLineString= "We have \
multiple lines \
here";
```
Now when we want to create a mutiline string, we can make use of template strings.We can surround our string with backticks. This approach is extremely helpful when we want to create some dynamic html markup.
```javascript
const htmlMarkup = `
<html>
<head></head>
<title>Template string</title>
<body>Hello World</body>
</html>`;
```
## Nesting of Template Strings:
We can nest them inside of each other.
```javascript
const cities =[
{name:'Delhi', year: 2010},
{name:'Mumbai', year: 2015},
{name:'Kolkata', year: 2017}];
const markup = `
<ul>
${cities.map(city=>`<li>I lived in ${city.name} in the year ${city.year}</li>`).join('')}
</ul>`;
```
Here the join operator after map function removes the extra commas which are added after each li.
## If statements and Functions
We can also use If statements inside the template strings.
```javascript
const data = {name: 'John', city: 'London', birthyear: 1900};
const markup = `<div>${data.name} lives in ${data.city}. ${data.birthyear ? `<div>He was born in the year ${data.birthyear}</div>`:''}</div>`;
```
In the example above, if birthyear is defined, then div with contents "He was born in the year" is generated otherwise there would be no div created.
We can also call functions inside the template strings.