javascript - Next js - Node Js - React JS

How to Import & Export Multiple Variables from Same Files in JavaScript/React/Next.js

Interview Answer

If I need to export multiple variables, functions, or components from the same file, I use named exports. They are exported using the export keyword and imported inside curly braces. A file can have multiple named exports but only one default export. For example:

In JavaScript/React/Next.js, if you want to export multiple variables, functions, or components from the same file, use named exports.

Example 1: Export Multiple Variables

// utils.js

export const company = "Cybotrix Technologies";
export const city = "Bangalore";
export const experience = 5;

Import:

import { company, city, experience } from "./utils";

console.log(company);

Example 2: Export Multiple Functions

// math.js

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

Import:

import { add, subtract, multiply } from "./math";

console.log(add(10, 20));

Example 3: Export at Bottom

const company = "Cybotrix";

const getCompany = () => {
  return company;
};

const getLocation = () => {
  return "Bangalore";
};

export { company, getCompany, getLocation };

Import:

import { company, getCompany, getLocation } from "./helper";

Example 4: Default Export + Named Export

// user.js

export const role = "Admin";

export function getRole() {
  return role;
}

export default function User() {
  return "User Component";
}

Import:

import User, { role, getRole } from "./user";

Here:

  • User → Default export
  • role, getRole → Named exports

Rename While Importing

import { add as sum } from "./math";

console.log(sum(10, 20));

Import Everything

import * as MathUtil from "./math";

console.log(MathUtil.add(10, 20));
console.log(MathUtil.multiply(5, 5));

Interview Answer

If I need to export multiple variables, functions, or components from the same file, I use named exports. They are exported using the export keyword and imported inside curly braces. A file can have multiple named exports but only one default export. For example:

export const name = "Raj";
export const city = "Bangalore";

export function getData() {}

and imported as:

import { name, city, getData } from "./file";