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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay