0
0
JavascriptHow-ToBeginner · 3 min read

How to Use from in JavaScript: Syntax and Examples

In JavaScript, from is used in import statements to load modules or specific exports from a file or package. The syntax is import { item } from 'module', which lets you use code from other files or libraries.
📐

Syntax

The from keyword is used in import statements to specify the module or file to load code from.

Basic syntax parts:

  • import: keyword to bring code in
  • { item }: specific parts to import (can be multiple)
  • from: keyword to specify source
  • 'module': string path or package name
javascript
import { item } from 'module';
💻

Example

This example shows how to import a function named greet from a module called ./utils.js and use it.

javascript
import { greet } from './utils.js';

greet('Alice');

// utils.js file content:
// export function greet(name) {
//   console.log(`Hello, ${name}!`);
// }
Output
Hello, Alice!
⚠️

Common Pitfalls

Common mistakes when using from in imports include:

  • Forgetting to use curly braces {} when importing named exports.
  • Using incorrect module paths or missing file extensions.
  • Trying to import default exports with curly braces.
javascript
/* Wrong: importing named export without braces */
// import { greet } from './utils.js'; // ❌

/* Right: import named export with braces */
import { greet } from './utils.js'; // ✅

/* Wrong: importing default export with braces */
// import { default } from './utils.js'; // ❌

/* Right: import default export without braces */
import greet from './utils.js'; // ✅ if greet is default export
📊

Quick Reference

UsageExample
Import named exportimport { func } from './file.js';
Import default exportimport func from './file.js';
Import all as objectimport * as utils from './utils.js';
Import with aliasimport { func as myFunc } from './file.js';

Key Takeaways

Use from in import statements to specify the module source.
Wrap named imports in curly braces {} when using from.
Default exports are imported without curly braces.
Always check the module path and file extension for correctness.
Use aliases to rename imports for clarity or to avoid conflicts.