编程知识 cdmana.com

Modern JavaScript -- imports, exports, let, const and promise in ES6 +

Reprint please indicate the source : Grape city official website , Grape city provides professional development tools for developers 、 Solutions and services , Enabling developers .
The source of the original text is :https://www.freecodecamp.org/news/learn-modern-javascript/

 

In the last few years ,JavaScript There are a lot of updates . If you want to improve your ability to write code , These updates will help you a lot .

For programmers , It is very important to know the latest development of the language . It keeps you up to date , Improve code quality , Excel in your work , So as to further improve your salary .

Specially , If you want to learn something like React、 Angular or Vue Such a framework , You have to master these latest features .

lately ,JavaScript Added many useful features , such as Nullish coalescing operator, optional chaining, Promises, async/await, ES6 destructuring, wait .

So now , We're going to look at each JavaScript Concepts that developers should know .

 

JavaScript Medium Let and const

 

stay ES6 Before ,JavaScript Use var Keyword to declare variables ,var Only global scope and function scope , Global scope means that you can access anywhere in your code var Declared variables , The function scope accesses the variable inside the current function declared by the variable . There is no block level scope at this time .

With let and const The addition of these two keywords ,JS Added the concept of block level scope .

How to be in JavaScript Use in let

When we use let When variables are declared , It can't be redeclared with the same name after being declared once .

// ES5 Code
var value = 10;
console.log(value); // 10

var value = "hello";
console.log(value); // hello

var value = 30;
console.log(value); // 30

As shown above , We use it many times var Keyword redeclares the variable value .

stay ES6 Before , We can use var Redeclare previously declared variables , This leads to a problem : If we don't know , The variable has been redeclared elsewhere , It is very likely to override the value of the original variable , It's hard to debug .

therefore ,Let Solve the problem well . When you use let When you redeclare a variable value , Will be an error .

// ES6 Code
let value = 10;
console.log(value); // 10

let value = "hello"; // Uncaught SyntaxError: Identifier 'value' has already been declared

 however , The following code is legal :
// ES6 Code
let value = 10;
console.log(value); // 10

value = "hello";
console.log(value); // hello

We found that the above code looks ok , It's because we give it back value The variable is assigned a new value , But there's no restatement .

Let's take a look at the following code :

// ES5 Code
var isValid = true;
if(isValid) {
  var number = 10;
  console.log('inside:', number); // inside: 10
}
console.log('outside:', number); // outside: 10

As shown above , In the use of var When variables are declared , Can be in if Access the variable outside of the block .

While using let Declarative number Variables can only be in if Intra block access , If in if Out of block access will report an error .

Let's take a look at the following code

// ES6 Code
let isValid = true;
if(isValid) {
  let number = 10;
  console.log('inside:', number); // inside: 10
}
console.log('outside:', number); // Uncaught ReferenceError: number is not defined

As shown in the above code , Use let Respectively in if block 、if It's declared out of the block number Variable . stay if Out of block ,number Can't be accessed , So there's a citation error .

however , If the variable number stay if It has been declared that , The following results will appear .

// ES6 Code
let isValid = true;
let number = 20;

if(isValid) {
  let number = 10;
  console.log('inside:', number); // inside: 10
}

console.log('outside:', number); // outside: 20

Now there are two in a separate scope number Variable . stay if Out of block ,number The value of is 20.

// ES5 Code
for(var i = 0; i < 10; i++){
 console.log(i);
}
console.log('outside:', i); // 10

When using var When a keyword ,i stay for Outside the loop, you can also access .

 

// ES6 Code
for(let i = 0; i < 10; i++){
 console.log(i);
}

console.log('outside:', i); // Uncaught ReferenceError: i is not defined

While using let When a keyword , stay for The outside of the loop is not accessible .

therefore , As the example code above shows ,let Declared variables can only be used inside blocks , It's not accessible outside the block .

We can use a pair of braces to create a block , as follows :

let i = 10;
{
 let i = 20;
 console.log('inside:', i); // inside: 20
 i = 30;
 console.log('i again:', i); // i again: 30
}

console.log('outside:', i); // outside: 10

 

As mentioned earlier ,let Variables cannot be redeclared in the same block , But you can declare it again in another block . As shown in the above code , We've restated it in blocks i, And the assignment 20, This variable can only be used in this block .

Outside the block , When we print variables , What we get is 10 Instead of the previously assigned value , It's because out of the block , Internal variables i It doesn't exist .

If the variable is not declared outside the block , Then there will be an error :

{
 let i = 20;
 console.log('inside:', i); // inside: 20
 i = 30;
 console.log('i again:', i); // i again: 30
}

console.log('outside:', i); // Uncaught ReferenceError: i is not defined

 

How to be in JavaScript Use const

const How keywords work in a block level scope is similar to let The key words are exactly the same . therefore , Let's look at the difference between them .

const Declared variables are constants , Its value cannot be changed . and let Declared variables , You can assign it a new value , As shown below :

let number = 10;
number = 20;
console.log(number); // 20

But the following situation , We can't use it like this const.

const number = 10;
number = 20; // Uncaught TypeError: Assignment to constant variable.

We can't even use const Restate as follows .

const number = 20;
console.log(number); // 20

const number = 10; // Uncaught SyntaxError: Identifier 'number' has already been declared

Now? , Look at the code below :

const arr = [1, 2, 3, 4];
arr.push(5);
console.log(arr); // [1, 2, 3, 4, 5]

We said const Declared constant , Its value will never change —— But we changed the above constant array and did not report an error . Why is that ?

Be careful : An array is a reference type , instead of JavaScript Basic type

The actual storage is arr It's not an array , It's a reference to the memory location stored in the array ( Address ). perform arr.push(5), It hasn't changed arr Reference to , Instead, it changes the value stored on that reference .

The same is true of the object :

const obj = {
 name: 'David',
 age: 30
};

obj.age = 40;

console.log(obj); // { name: 'David', age: 40 }

 

here , We haven't changed obj Reference to , Instead, it changes the value stored in the reference .

therefore , The above code will work , But the following code is invalid .

const obj = { name: 'David', age: 30 };
const obj1 = { name: 'Mike', age: 40 };
obj = obj1; // Uncaught TypeError: Assignment to constant variable.

Writing like this will throw an exception , Because we're trying to change const The reference that the variable points to .

therefore , In the use of const One thing to remember when : Use const When declaring constants , You can't restate , You can't reassign . If the declared constant is a reference type , We can change the value stored in the reference .

Empathy , The following code is also invalid .

const arr = [1, 2, 3, 4];
arr = [10, 20, 30]; // Uncaught TypeError: Assignment to constant variable.

  

summary :

  • keyword let and const stay JavaScript Add block level scope to .
  • When we declare a variable as let when , We can't be in the same scope ( Function or block level scope ) Redefine or redeclare another... With the same name in let Variable , But we can reassign .
  • When we declare a variable as const when , We can't be in the same scope ( Function or block level scope ) Redefine or redeclare another with the same name const Variable . however , If the variable is a reference type ( A group or object ), We can change the value stored in the variable .

Okay , Let's move on to the next topic : promises.

 

JavaScript Medium promises

 

For many new developers ,promises yes JavaScript The more difficult part of .ES6 Zhongyuan Sheng provided Promise object , that Promise What is it ?

Promise Objects represent future events , Messages used to deliver asynchronous operations .

How to create a promise

Use promise Constructor to create a promise, As shown below :

const promise = new Promise(function(resolve, reject) {
 
});

Promise The constructor of takes a function as an argument , And it receives two parameters internally :resolve,reject. resolve and reject Parameters are actually functions that we can call , Depending on the result of the asynchronous operation .

Promise  There are three states :

  • pending: The initial state , It's not a state of success or failure .
  • fulfilled: Indicates that the operation completed successfully .
  • rejected: Indicates that the operation failed .

When we create Promise when , It's in a state of waiting . When we call resolve Function time , It will go into the completed state . If the reject, He's going to be rejected .

 In the following code , We performed an asynchronous operation , That is to say setTimeout,2 Seconds later , call resolve Method .

 

const promise = new Promise(function(resolve, reject) {
 setTimeout(function() {
  const sum = 4 + 5;
  resolve(sum);
 }, 2000);
});

We need to register a callback using the following method .then get 1promise The result of successful execution , As shown below :

const promise = new Promise(function(resolve, reject) {
 setTimeout(function() {
  const sum = 4 + 5;
  resolve(sum);
 }, 2000);
});

promise.then(function(result) {
 console.log(result); // 9
});

then Receive a parameter , Is the function , And we'll get it promise Call in resolve Parameters of time transmission .

If the operation is not successful , Call reject function :

const promise = new Promise(function(resolve, reject) {
 setTimeout(function() {
  const sum = 4 + 5 + 'a';
  if(isNaN(sum)) {
    reject('Error while calculating sum.');
  } else {
    resolve(sum);
  }
 }, 2000);
});

promise.then(function(result) {
 console.log(result);
});

If sum It's not a number , So we call the... With the error message reject function , Otherwise we call resolve function .

Execute the above code , Output is as follows :

 

 

 

call reject Function throws an error , But we didn't add code to catch errors .

Need to call catch Method to capture and handle the error .

promise.then(function(result) {
 console.log(result);
}).catch(function(error) {
 console.log(error);
});

Output is as follows :

 

 

 

So I suggest you use promise When combined with catch Method , In order to prevent the program from stopping due to errors .

Chain operation

We can go to the individual promise Add multiple then Method , As shown below :

promise.then(function(result) {
 console.log('first .then handler');
 return result;
}).then(function(result) {
 console.log('second .then handler');
 console.log(result);
}).catch(function(error) {
 console.log(error);
});

When adding multiple then When the method is used , Previous then The return value of the method is automatically passed to the next then Method .

 

 

As shown in the figure above , We are in the first then Method output string , And will receive the parameters result(sum) Go back to the next result.

The next then In the method , Output string , And output the previous one then Method passed to it result.

How to be in JavaScript Medium delay promise Implementation

A lot of times , We don't want to create promise, You want to create it after an operation is completed .

We can promise Encapsulated in a function , And then return... From the function promise, As shown below :

 

function createPromise() {
 return new Promise(function(resolve, reject) {
  setTimeout(function() {
   const sum = 4 + 5;
   if(isNaN(sum)) {
     reject('Error while calculating sum.');
   } else {
    resolve(sum);
   }
  }, 2000);
 });
}

such , We can pass parameters to promise, To achieve dynamic goals .

function createPromise(a, b) {
 return new Promise(function(resolve, reject) {
  setTimeout(function() {
   const sum = a + b;
   if(isNaN(sum)) {
     reject('Error while calculating sum.');
   } else {
    resolve(sum);
   }
  }, 2000);
 });
}

createPromise(1,8)
 .then(function(output) {
  console.log(output); // 9
});

// OR

createPromise(10,24)
 .then(function(output) {
  console.log(output); // 34
});

 

 

 

Besides , We can only offer resolve or reject Function passes a value . If you want to pass multiple values to resolve function , You can pass it as an object , as follows :

const promise = new Promise(function(resolve, reject) {
 setTimeout(function() {
  const sum = 4 + 5;
  resolve({
   a: 4,
   b: 5,
   sum
  });
 }, 2000);
});

promise.then(function(result) {
 console.log(result);
}).catch(function(error) {
 console.log(error);
});

 

 

 

How to be in JavaScript Use the arrow function

In the above example code , We use regular ES5 Grammar creates promise. however , The arrow function is usually used instead of ES5 grammar , as follows :

const promise = new Promise((resolve, reject) => {
 setTimeout(() => {
  const sum = 4 + 5 + 'a';
  if(isNaN(sum)) {
    reject('Error while calculating sum.');
  } else {
    resolve(sum);
  }
 }, 2000);
});

promise.then((result) => {
 console.log(result);
});

You can use it according to your needs ES5 or ES6 grammar .

 

ES6 Import and Export grammar

stay ES6 Before , We're in a HTML You can use more than one file script Tags to refer to different JavaScript file , As shown below :

<script type="text/javascript" src="home.js"></script>
<script type="text/javascript" src="profile.js"></script>
<script type="text/javascript" src="user.js"></script>

But if we're in different places JavaScript There is a variable with the same name in the file , There will be naming conflicts , What you actually get may not be what you expect .

ES6 Add the concept of module to solve this problem .

stay ES6 in , Every one we write JavaScript Files are called modules . The variables and functions we declare in each file cannot be used in other files , Unless we export them from the file 、 Get a reference in another file .

therefore , The functions and variables defined in the file are private to each file , Before you export them , They can't be accessed outside the file .

export There are two types of :

  • Named export : There can be multiple named exports in one file
  • The default is derived : There can only be one default export in a single file

JavaScript Named exports in

As shown below , Name a single variable and export it :

export const temp = "This is some dummy text";

If you want to export multiple variables , You can use braces to specify a set of variables to output .

const temp1 = "This is some dummy text1";
const temp2 = "This is some dummy text2";
export { temp1, temp2 };
 It should be noted that , Export syntax is not object Syntax . therefore , stay ES6 in , Cannot be exported in the form of key value pairs .
   // This is invalid syntax of export in ES6
 export { key1: value1, key2: value2 }
import Command to accept a pair of braces , It specifies the variable name to be imported from other modules .
import { temp1, temp2 } from './filename';

Be careful , There is no need to add... To the file name .js Extension , Because the extension will be considered by default .

 // import from functions.js file from current directory 
import { temp1, temp2 } from './functions';
          // import from functions.js file from parent of current directory
import { temp1 } from '../functions';

A hint , The name of the imported variable must be the same as the name of the external interface of the imported module .

therefore , Export should use :

// constants.js
export const PI = 3.14159;

Then when importing , You must use the same name as you exported :

import { PI } from './constants';

// This will throw an error

import { PiValue } from './constants';

If you want to rename the input variable , have access to as keyword , The grammar is as follows :

import { PI as PIValue } from './constants';

We think that PI Rename it to PIValue, So it can't be used anymore PI Variable name .

 

You can also use the following rename syntax when exporting :  

// constants.js
const PI = 3.14159; 
export { PI as PIValue };

  

And then the import is , You have to use PIValue.

import { PIValue } from './constants';

You must declare something before you can name it .

export 'hello'; // this will result in error
export const greeting = 'hello'; // this will work
export { name: 'David' }; // This will result in error
export const object = { name: 'David' }; // This will work

Let's look at the following validations.js file :  

// utils/validations.js

const isValidEmail = function(email) {
  if (/^[^@ ]+@[^@ ]+\.[^@ \.]{2,}$/.test(email)) {
    return "email is valid";
  } else {
    return "email is invalid";
  }
};

const isValidPhone = function(phone) {
  if (/^[\\(]\d{3}[\\)]\s\d{3}-\d{4}$/.test(phone)) {
    return "phone number is valid";
  } else {
    return "phone number is invalid";
  }
};

function isEmpty(value) { 
  if (/^\s*$/.test(value)) {
    return "string is empty or contains only spaces";
  } else {
    return "string is not empty and does not contain spaces";
  } 
}

export { isValidEmail, isValidPhone, isEmpty };

stay index.js in , We can use the following functions :

// index.js
import { isEmpty, isValidEmail } from "./utils/validations";

console.log("isEmpty:", isEmpty("abcd")); // isEmpty: string is not empty and does not contain spaces

console.log("isValidEmail:", isValidEmail("abc@11gmail.com")); // isValidEmail: email is valid

console.log("isValidEmail:", isValidEmail("ab@c@11gmail.com")); // isValidEmail: email is invalid

JavaScript The default export of

As mentioned above , There can be at most one default export in a single file . however , You can use multiple named exports and one default export in a single file .

To declare a default export , We need to use the following syntax :

//constants.js
const name = 'David'; 
export default name;

There is no need to use curly braces when importing .  

import name from './constants';

  

as follows , We have multiple named exports and one default export :

// constants.js
export const PI = 3.14159; 
export const AGE = 30;

const NAME = "David";
export default NAME;

  

At this time, we use import Import time , Just specify the name of the default exported variable before the braces .

// NAME is default export and PI and AGE are named exports here
import NAME, { PI, AGE } from './constants';

Use export default Exported content , When importing ,import The following name can be arbitrary .

// constants.js
const AGE = 30;
export default AGE;

import myAge from ‘./constants’; 
console.log(myAge); // 30

in addition , export default The variable name of is from Age To myAge The reason why it works , Because there can only be one export default. So you can name whatever you want . Another thing to note , Keywords cannot be declared before variables .

// constants.js
export default const AGE = 30; // This is an error and will not work

therefore , We need to use keywords in a separate line .

// constants.js 
const AGE = 30; 
export default AGE;

  

But the following forms are allowed :

//constants.js
export default {
 name: "Billy",
 age: 40
};

And you need to use it in another file

import user from './constants';
console.log(user.name); // Billy 
console.log(user.age); // 40

  

also , You can use the following syntax to import constants.js All variables exported in the file :

// test.js
import * as constants from './constants';

 

below , We will import all of them constants.js Stored in constants Names in variables and export default. therefore ,constants Now it's going to be the object .

// constants.js
export const USERNAME = "David";
export default {
 name: "Billy",
 age: 40
};

In another file , Let's use .

// test.js

import * as constants from './constants';

console.log(constants.USERNAME); // David
console.log(constants.default); // { name: "Billy", age: 40 }
console.log(constants.default.age); // 40

You can also use a combination of named exports and default exports :

// constants.js
const PI = 3.14159; const AGE = 30;
const USERNAME = "David";
const USER = {
 name: "Billy",
 age: 40 
};
export { PI, AGE, USERNAME, USER as default };

import USER, { PI, AGE, USERNAME } from "./constants";

To make a long story short :

ES6 in , A module is a separate file , All variables within the file , It's not accessible from the outside . If you want to read a variable in a module from outside , You have to use export Keyword to export the variable , Use import Keyword to import the variable .

 

JavaScript Default parameters in

ES6 Added a very useful feature , That is to provide default parameters when defining functions .

Suppose we have an application , Once the user logs into the system , We will show them a welcome message , As shown below :

function showMessage(firstName) {
  return "Welcome back, " + firstName;
}
console.log(showMessage('John')); // Welcome back, John

however , If there is no user name in the database , So what should we do ? therefore , We first need to check if firstName, Then the corresponding information is displayed .

stay ES6 Before , We have to write code like this :  

function showMessage(firstName) {
  if(firstName) {
    return "Welcome back, " + firstName;
  } else {
    return "Welcome back, Guest";
  }
}

console.log(showMessage('John')); // Welcome back, John 
console.log(showMessage()); // Welcome back, Guest

But now use ES6 Default parameters provided , We can write this way :

function showMessage(firstName = 'Guest') {
   return "Welcome back, " + firstName;
}

console.log(showMessage('John')); // Welcome back, John 
console.log(showMessage()); // Welcome back, Guest

The default parameter of the function can be any value .

function display(a = 10, b = 20, c = b) { 
 console.log(a, b, c);
}

display(); // 10 20 20
display(40); // 40 20 20
display(1, 70); // 1 70 70
display(1, 30, 70); // 1 30 70

In the code above , We didn't provide all the parameters of the function , The actual code is equivalent to :

display(); //  Equate to display(undefined, undefined, undefined)
display(40);  Equate to display(40, undefined, undefined)
display(1, 70);  Equate to display(1, 70, undefined)

therefore , If the parameter passed is undefined, Then the corresponding parameter will use the default value .

We can also specify objects or calculated values as default values , as follows :

const defaultUser = {
  name: 'Jane',
  location: 'NY',
  job: 'Software Developer'
};

const display = (user = defaultUser, age = 60 / 2 ) => {

 console.log(user, age);

};

display();

 

/* output

 

{

  name: 'Jane',

  location: 'NY',

  job: 'Software Developer'

} 30

*/

  

ES5 The code is as follows :

// ES5 Code
function getUsers(page, results, gender, nationality) {
  var params = "";
  if(page === 0 || page) {
   params += `page=${page}&`; 
  }
  if(results) {
   params += `results=${results}&`;
  }
  if(gender) {
   params += `gender=${gender}&`;
  }
  if(nationality) {
   params += `nationality=${nationality}`;
  }

  fetch('https://randomuser.me/api/?' + params) 
   .then(function(response) {
     return response.json(); 
   })
   .then(function(result) { 
    console.log(result);
   }) 
   .catch(function(error) {
     console.log('error', error); 
   }); 
}

getUsers(0, 10, 'male', 'us');

  

In this code , We passed the getUsers Function to pass a variety of optional parameters to API call . It's going on API Before you call , We added a variety of if Condition to check whether the parameter is added , And construct the query string based on this , As shown below :

https://randomuser.me/api/? page=0&results=10&gender=male&nationality=us

 

Use ES6 You don't have to add so many default parameters if Conditions , As shown below :

function getUsers(page = 0, results = 10, gender = 'male',nationality = 'us') {
 fetch(`https://randomuser.me/api/?page=${page}&results=${results}&gender=${gender}&nationality=${nationality}`)
 .then(function(response) { 
  return response.json();
 }) 
 .then(function(result) {
   console.log(result); 
 })
 .catch(function(error) { 
  console.log('error', error);
  }); 
}
getUsers();

thus , The code has been greatly simplified , Even if we don't do it for getUsers When the function provides any parameters , It can also take the default value . Of course , We can also pass our own parameters :

getUsers(1, 20, 'female', 'gb');

It will override the default parameters of the function .

null It doesn't mean undefined

Be careful : When defining default parameters ,null and undefined Is different .

Let's look at the following code :

function display(name = 'David', age = 35, location = 'NY'){
 console.log(name, age, location); 
}
display('David', 35); // David 35 NY
display('David', 35, undefined); // David 35 NY
// OR
display('David', 35, undefined); // David 35 NY
display('David', 35, null); // David 35 null
 When we deliver null As a parameter , It's actually for location Assign a null value to the parameter , And undefined Dissimilarity . So it doesn't take the default “NY”.

Array.prototype.includes

ES7 Added array of includes Method , Used to determine whether an array contains a specified value , If it's a return  true, otherwise false.
// ES5 Code
const numbers = ["one", "two", "three", "four"];
console.log(numbers.indexOf("one") > -1); // true 
console.log(numbers.indexOf("five") > -1); // false

Arrays can be used includes Method :

// ES7 Code
const numbers = ["one", "two", "three", "four"];
console.log(numbers.includes("one")); // true 
console.log(numbers.includes("five")); // false
includes Methods make code short and easy to understand , It can also be used to compare different values .
const day = "monday";
if(day === "monday" || day === "tuesday" || day === "wednesday") {
  // do something
}

//  The above code uses include The method can be simplified as follows :
const day = "monday";
if(["monday", "tuesday", "wednesday"].includes(day)) {
  // do something
}
 therefore , When checking the values in an array , Use includes The method will be very convenient .
 Conclusion 
 from ES6 Start ,JavaScript A lot of changes have taken place in . about JavaScript,Angular,React or Vue Developers should know about them 
 Understanding these changes can make you a better developer , It can even help you get a higher salary . and , If you're just learning React Libraries like that and Angular and Vue A framework like that , So you have to master these new features .

版权声明
本文为[Grape City technical team]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225122311484o.html

Scroll to Top