Organize your code with ES modules and understand import/export syntax.
Example of defining and using ES modules with import and export:
// file: mathUtils.js
export function add(a, b) {
return a + b;
}
export const PI = 3.14159;
// file: app.js
import { add, PI } from './mathUtils.js';
console.log('Add:', add(2, 3)); // 5
console.log('PI:', PI); // 3.14159
This code demonstrates:
export
.import { ... } from
..js
extension in imports.JavaScript ES Modules provide a standard way to structure and share code across files.
type="module"
in script tags, and in Node.js with .mjs
files or proper configuration.Q1: Which keyword is used to export a function in ES modules?
import
export
require
module.exports
Answer: B. export
Q2: How do you import a named export called foo
from utils.js
?
import foo from './utils.js'
import { foo } from './utils.js'
require('foo')
export { foo }
Answer: B. import { foo } from './utils.js'
Q3: What is the correct way to import a default export?
import foo from './module.js'
import { default as foo } from './module.js'
export default foo
Answer: C. Both A and B
Q4: What attribute must be added to a <script> tag to use ES modules in browsers?
async
defer
type="module"
src
Answer: C. type="module"