What is difference b/w export and import with Example in Javascript

export and import  are used for modularization of code in JavaScript.

 Export is used to make values and functions defined in a module available to other modules that import it, while

 Import is used to import the exported values and functions into another module.

Native JavaScript Modules

Modules in JavaScript use the import and export keywords:

  • import: Used to read code exported from another module.
  • export: Used to provide code to other modules.
Export Example--

you can say below code file name is functions.js

export function sum(x, y) {
  return x + y
}

export function difference(x, y) {
  return x - y
}

export function product(x, y) {
  return x * y
}

export function quotient(x, y) {
  return x / y
}


Import Example:-

import { sum, difference, product, quotient } from './functions.js'

const x = 10
const y = 5

document.getElementById('x').textContent = x
document.getElementById('y').textContent = y

document.getElementById('addition').textContent = sum(x, y)
document.getElementById('subtraction').textContent = difference(x, y)
document.getElementById('multiplication').textContent = product(x, y)
document.getElementById('division').textContent = quotient(x, y)

No comments:

Post a Comment

CPU vs GPU Architecture

  CPU vs GPU Architecture CPU (Central Processing Unit) and GPU (Graphics Processing Unit) have distinct architectural differences, optimize...

Best for you