DEV Community

Harshit Kedia
Harshit Kedia

Posted on

Useful Javascript ES6 nuggets

Important points I noted while revising Javascript ES6:

:> Adding external script to webpage:

<script type="module" src="index.js"></script>
Enter fullscreen mode Exit fullscreen mode

:> Exporting function to Share a Code Block:

export const add = (x, y) => {
  return x + y;
}
Enter fullscreen mode Exit fullscreen mode

*Export multiple things by repeating for each export.

:> Reusing JavaScript Code Using import:

import { add, subtract } from './math_functions.js';
Enter fullscreen mode Exit fullscreen mode

*Here ./ tells the import to look for the math_functions.js file in the same folder as the current file.

:> Import Everything from a File and use specific functions:

import * as myMathModule from "./math_functions.js";
myMathModule.add(2,3);
myMathModule.subtract(5,3);
Enter fullscreen mode Exit fullscreen mode

:> For default export functions, while importing, no need to add braces {}, and name can be anything, not compulsorily the name of the function.

:> Promise: task completes, you either fulfill your promise or fail to do so, with two parameters - resolve and reject, to determine the outcome of the promise. Syntax:

const myPromise = new Promise((resolve, reject) => {
  if(condition here) {
    resolve("Promise was fulfilled");
  } else {
    reject("Promise was rejected");
  }
});
Enter fullscreen mode Exit fullscreen mode

:> When you make a server request it takes some amount of time, and after it completes you usually want to do something with the response from the server. The then method is executed immediately after your promise is fulfilled with resolve, eg:

myPromise.then(result => {});
Enter fullscreen mode Exit fullscreen mode

:> Catch can be executed if after a promise's reject method is called:

myPromise.catch(error => {});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)