lunes, 16 de agosto de 2021

ECMA Script 6 Simple Course, Babel. Part 1

ECMA Script 6 Simple Course, Babel. Part 1

 



  1. Install and Config tools
  2. Ways to declare variables.
  3. Template Strings
  4.  Arrow Function
  5.  Default Parameters
  6.  Array Destructuring
  7. Object Destructuring
  8. Classes and Inheritance
references
FalconMaster course.

1. Install and Config tools.

requirements

Create this file and firectory structure

ES6 
  -- src
        index.html
  -- output
  package.json 

install

  • babel
  • npm
  • nodejs
  • git

 

Go to https://babeljs.io/docs/en/ to install Babel transpiler

In git bash opened over our ES6 working directory type

npm install --save-dev @babel/preset-react 
also
npm install --save-dev @babel/core @babel/cli

Now we can see our package.json file like this

{
  "devDependencies": {
    "@babel/cli""^7.14.8",
    "@babel/core""^7.15.0",
    "@babel/preset-react""^7.14.5"
  }
}

Now config Babel, in package.json file type as following code

{
  "devDependencies": {
    "@babel/cli""^7.14.8",
    "@babel/core""^7.15.0",
    "@babel/preset-react""^7.14.5"
  },
  "scripts": {
      "build""babel src -d output"
  }
}

Now run the script build

$ npm run build

> @ build D:\Descargas\Tutorial2021\ReactCrashCourse2021\ES6
> babel src -d output

Successfully compiled 1 file with Babel (390ms).
 
The output file has the consLet.js file but without any transpilation, we need configure babel with a file
babel.config.json

{
  "presets": ["@babel/preset-env"]
}
 
and install
npm install @babel/preset-env --save-dev
At this point our package.json file will be like this
{
  "devDependencies": {
    "@babel/cli""^7.14.8",
    "@babel/core""^7.15.0",
    "@babel/preset-env""^7.15.0",
    "@babel/preset-react""^7.14.5"
  },
  "scripts": {
    "build""babel src -d output"
  }
 
And execute the stript again
 
$ npm run build
 
When we see the output we obtain the file constlet.js transpiled to javascript

"use strict";

var nombre = "Jose Alberto";
console.log("This is a message to Console " + nombre);
 
 
To enable the automatic traspiling then any file change, add --watch to the package.json build stript

"scripts": {
    "build""babel src -d output --watch"
  }
 
Now we just need update the reference of the src/constLet.js file to output/constLet.js in index.html file.

 2. Ways to declare Variables.

var nombre = "Jose";
var nombre = "Juan";
 
this in javascript is allowed but brings lots of potential problems in order to let us redeclare the variable  with any warning.
 
let and const not allow redeclare variables.
 
let nombre = "Jose";
const nombre = "Juan"; 

SyntaxError: D:\Descargas\Tutorial2021\ReactCrashCourse2021\ES6\src\constLet.js: Identifier 'nombre' has already been declared. (4:4)

  2 |
  3 | let nombre = "Jose Alberto"
> 4 | let nombre = "Redeclarando"
    |     ^
Also with const

SyntaxError: D:\Descargas\Tutorial2021\ReactCrashCourse2021\ES6\src\constLet.js: Identifier 'pais' has already been declared. (7:6)

  5 |
  6 | const pais = "Mexico"
> 7 | const pais = "EU"
    |       ^
 
var, let and const have function scope.
 
let and const have block scope

//var has not a block scope
var age = 18;

if (age >= 18) {
  var isMayor = true;
}
console.logisMayor);

console output: true

//let and const has block scope, not visible outside the block
const age = 18;

if (age >= 18) {
  const isMayor = true;
}
console.logisMayor);

console output: Uncaught ReferenceError: isMayor is not defined
 
let allow change the value of the variable defined.
const not allow to change the value of the variable defined.
 
//const and Array behaviour, allow add with push
const colours = ['red','white'];
//colours = "Not Allowed";
colours.push("blue");

console.logcolours);
 
console output: Array(3) [ "red", "white", "blue" ]
 

3. Template Strings

 
use without template Strings
 
// Without TemplateString
const name = "Jose Alberto";
const age = 50;
const country = "Mexico"

console.log("name: " + name + " age: " + age + " contry: " + country);
 
 
use with template Strings
 
// With TemplateStrings
const name = "Jose Alberto";
const age = 50;
const country = "Mexico"

console.log(`name: ${name}  age: ${age} contry: ${country}`);
 
But how Babel transpile this code, well see the next
 
"use strict";

// With TemplateStrings
var name = "Jose Alberto";
var age = 50;
var country = "Mexico";
console.log("name: ".concat(name"  age: ").concat(age" contry: ").concat(country));
 
Babel use concat

4. Arrow Function

Consider a function that shows data relative to each element of an array

const array = ["Juana""Jose""Alberto""Fulanuto"];

const showArrayElementslength = array.map(function (element) {
  console.log(`${element.length}`);
});
 
console out: 5, 4 ,7 , 8

const array = ["Juana""Jose""Alberto""Fulanuto"];

const showArrayElementslength = array.map(function (element) {
  console.log(`${element} has a length of ${element.length}`);
});
 
Just for Information, Babel transfile this into this javascript

const array = ["Juana""Jose""Alberto""Fulanuto"];

const showArrayElementslength = array.map(function (element) {
  console.log(`${element.length}`);
});
 
"use strict";

var array = ["Juana""Jose""Alberto""Fulanuto"];
var showArrayElementslength = array.map(function (element) {
  console.log("".concat(element" has a length of ").concat(element.length));
});
 
In Arrow Function format
 
"use strict";

var array = ["Juana""Jose""Alberto""Fulanuto"];
var showArrayElementslength = array.map((element=> {
  console.log("".concat(element" has a length of ").concat(element.length));
});
 
Babel Translate the arrow format into the function() format
 
"use strict";

var array = ["Juana""Jose""Alberto""Fulanuto"];
var showArrayElementslength = array.map(function (element) {
  console.log("".concat(element" has a length of ").concat(element.length));
});
 
The arrow function allow us compress or simplify the expression. lets see the next equivalent sentences for a return function.
 
const showArrayElementslength = array.map((element=> {
  return `${element} has a length of ${element.length}`;
});
 
const arrayProc = array.map((element=> {
  `${element} has a length of ${element.length}`;
});
 
The previos code return array of undefined, eliminating the { }, the code works again.
 
const arrayProc = array.map(
  (element=> `${element} has a length of ${element.length}`
);
 
shortening more
const arrayProc = array.map((e=> `${e} has a length of ${e.length}`);

 

5. Default Parameters

 
Consider the next function which receive parameters.

function addUser(namecountryemailphone) {
  return `name: ${name}, country: ${country}, email: ${email}, phone: ${phone}`;
}

console.log(addUser());
 
console output: name: undefined, country: undefined, email: undefined, phone: undefined
 
Now with data in all his parameters
 
function addUser(namecountryemailphone) {
  return `name: ${name}, country: ${country}, email: ${email}, phone: ${phone}`;
}

console.log(addUser("Funalito""México""fulanito@email.com""234234234"));
 
console output: name: Funalito, country: México, email: fulanito@email.com, phone: 234234234
 
Consider not pass the last parameter but assign a default phone number 00000000
 
function addUser(namecountryemailphone = "00000000") {
  return `name: ${name}, country: ${country}, email: ${email}, phone: ${phone}`;
}

console.log(addUser("Funalito""México""fulanito@email.com"));
 
Babel transpile the next way
 
"use strict";

function addUser(namecountryemail) {
  var phone = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "00000000";
  return "name: ".concat(name", country: ").concat(country", email: ").concat(email", phone: ").concat(phone);
}

console.log(addUser("Funalito""México""fulanito@email.com")); 
 
console output: name: Funalito, country: México, email: fulanito@email.com, phone: 00000000
 
Now with the second parameter country
 
function addUser(namecountry = "Not Specified"emailphone = "00000000") {
  return `name: ${name}, country: ${country}, email: ${email}, phone: ${phone}`;
}

console.log(addUser("Funalito"undefined"fulanito@email.com"));
 
Babel transpile the next way

function addUser(name) {
  var country = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "Not Specified";
  var email = arguments.length > 2 ? arguments[2] : undefined;
  var phone = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "00000000";
  return "name: ".concat(name", country: ").concat(country", email: ").concat(email", phone: ").concat(phone);
}

console.log(addUser("Funalito"undefined"fulanito@email.com"));
 
console output: name: Funalito, country: Not Specified, email: fulanito@email.com, phone: 00000000
 

6. Array Destructuring

 
Consider the next code where for each parameter has to assing to a variable according his position.
 
const person = ["Fulanito""34""México""3242342"];

const name = person[0];
const age = person[1];
const country = person[2];
const phone = person[3];

console.log(`${name} ${age} ${country} ${phone}`);
 
 Using Array destructirung
 
const person = ["Fulanito""34""México""3242342"];

♥const [nameagecountryphone] = person;

console.log(`${name} ${age} ${country} ${phone}`);
 
 
const person = ["Fulanito""34""México""3242342"];

const [name] = person;

console.log(`${name}`);
 
 
 Array Destructuring with default values. omiting second and fourth element to take default values.
 
const person = ["Fulanito", , "México"];

const [nameage = "Not Specified"countryphone = "00000000"] = person;

console.log(`${name} ${age} ${country} ${phone}`);
 
Babel transpile the previous code as
"use strict";

var person = ["Fulanito",, "México"];
var name = person[0],
    _person$ = person[1],
    age = _person$ === void 0 ? "Not Specified" : _person$,
    country = person[2],
    _person$2 = person[3],
    phone = _person$2 === void 0 ? "00000000" : _person$2;
console.log("".concat(name" ").concat(age" ").concat(country" ").concat(phone));
 
  Using Array Destructuring in function parameters
const person = ["Fulanito", , "México"];

const showParamsFromArray = ([
  name,
  age = "Not Specified",
  country,
  phone = "00000000",
] = arrayPassed=> {
  console.log(`${name} ${age} ${country} ${phone}`);
};

showParamsFromArray(person);

 
console output: Fulanito Not Specified México 00000000
 

7. Object Destructuring

 
Start with a basic object code
const person = {
  name: "Fulanito",
  email: "fulanito@email.com",
  age: 43,
  country: "México",
  phone: "12345678",
};

console.log(person);

 
console output: Object { name: "Fulanito", email: "fulanito@email.com", age: 43, country: "México", phone: "12345678" }
 
Simple object destructuring
 
const person = {
  name: "Fulanito",
  email: "fulanito@email.com",
  age: 43,
  country: "México",
  phone: "12345678",
};

const { namecountry } = person;

console.log(namecountry);
   
Console output: Fulanito México
 
Also default values can be assigned when destructuring an object
 
const person = {
  name: "Fulanito",
  email: "fulanito@email.com",
  age: 43,
  country: "México",
  phone: "12345678",
};

const { namecountryprofession = "Not Specified" } = person;

console.log(namecountryprofession);

 
console output:  Fulanito México Not Specified
 
Destructuring Object when used as Parameter in function
const person = {
  name: "Fulanito",
  email: "fulanito@email.com",
  age: 43,
  country: "México",
  phone: "12345678",
};

const functionDestructuringParamObject = ({ namecountry } = person=> {
  console.log(namecountry);
};

functionDestructuringParamObject(person);

 
The code can be simplyfied on not specify " = person" because it is passed as parameter, and also can be asigned default values when omited.
 
const person = {
  name: "Fulanito",
  email: "fulanito@email.com",
  age: 43,
  country: "México",
  phone: "12345678",
};

const functionDestructuringParamObject = ({
  name,
  country,
  profession = "Not Specified",
}) => {
  console.log(namecountryprofession);
};

functionDestructuringParamObject(person);

 
console output: Fulanito México Not Specified
 

8. Classes and Inheritance

 
Define a Person Class with two properties name and age, this properties are initialized by his constructor. in this case our editor automatically add the parentesis to each property and the ; and the end. because our visual studio code in their menu File->Preference->Settings->Text Editor->Default Formatter is selected Prettier, change it to null or other like Typescript and JavaScript formatter.

class Person {
  constructor() {
    this.name = "Fulanito"
 this.age = 35;
  }
}

const person = new Person();
document.write(person.name);


  
 Now, use parameters in the constructor to pass the values of their properties.

class Person {
  constructor(nameage) {
    this.name = name
 this.age = age;
  }
}

const person = new Person("Fulanito"37);
document.write(person.name + " " + person.age);
 
Add a method to show their properties.
 
class Person {
  constructor(nameage) {
    this.name = name 
this.age = age;
  }

  showProperties() {
    document.write(person.name + " " + person.age);
  }
}

const person = new Person("Fulanito"37);
person.showProperties();
 
Now with the parametrized constructor we can construct diferent person classes with diferent properties.
 
class Person {
    constructor(nameageemail) {
        this.name = name,
        this.age = age,
        this.email = email;
    }

    showProperties() {
        return `
        <b>Name:</b>  ${this.name} <br />
        <b>Age:</b>   ${this.age} <br />
        <b>Email:</b> ${this.email} <br />
        <hr/>
      `;
    }
}

const personA = new Person("Fulanito"37"fulanito@email.com");
document.write(personA.showProperties());

const personB = new Person("Perenganito"23"perenganito@email.com");
document.write(personB.showProperties());

 Now we need an student entity, lets take Person class and add student properties to a Student class

class Person {
    constructor(nameageemail) {
        this.name = name,
        this.age = age,
        this.email = email;
    }

    showProperties() {
        return `
        <b>Name:</b>  ${this.name} <br />
        <b>Age:</b>   ${this.age} <br />
        <b>Email:</b> ${this.email} <br />
        <hr/>
      `;
    }
}

class Student extends Person{
    constructornameageemailcareer){
        supernameageemail)
        this.career = career
    }

    showProperties() {
        return `
        <b>Name:</b>  ${this.name} <br />
        <b>Age:</b>   ${this.age} <br />
        <b>Email:</b> ${this.email} <br />
        <b>career:</b> ${this.career} <br />
        <hr/>
      `;
    }
}

const personA = new Person("Fulanito"37"fulanito@email.com");
document.write(personA.showProperties());

const studentA = new Student("Perenganito"23"perenganito@email.com","Arts");
document.write(studentA.showProperties());


Browser output:

Name: Fulanito
Age: 37
Email: fulanito@email.com


Name: Perenganito
Age: 23
Email: perenganito@email.com
career: Arts

 

 

eot

No hay comentarios:

Publicar un comentario