Answer: JavaScript can be implemented in three main ways:
- Inline JavaScript
- Internal JavaScript
- External JavaScript
Answer:
Inline JavaScript is written directly within an HTML element’s attribute, typically the onclick, onload, or other event attributes.
📌 Example:
<button onclick="alert('Hello!')">Click Me</button>🔹 Use Case: Simple, one-liner scripts 🔹 Drawback: Not clean, hard to maintain, violates separation of concerns
Answer:
Internal JavaScript is written inside a <script> tag within the HTML document, typically placed in the <head> or <body> section.
📌 Example:
<!DOCTYPE html>
<html>
<head>
<script>
function greet() {
alert('Hello from internal JS');
}
</script>
</head>
<body>
<button onclick="greet()">Click</button>
</body>
</html>🔹 Use Case: Small projects or prototypes 🔹 Drawback: Mixing HTML and JS reduces maintainability
Answer:
External JavaScript is written in a separate .js file and then linked to the HTML file using a <script src="..."> tag.
📌 Example:
index.html
<!DOCTYPE html>
<html>
<head>
<script src="script.js" defer></script>
</head>
<body>
<button onclick="greet()">Click</button>
</body>
</html>script.js
function greet() {
alert('Hello from external JS!');
}🔹 Use Case: Best for large apps, reusable code 🔹 Advantage: Clean structure, separation of concerns, cacheable
Answer: External JavaScript is considered best practice because:
- Keeps HTML and JavaScript code separate
- Easier to manage and maintain
- Promotes reusability
- JS files are cacheable by browsers
- Works well with build tools, bundlers, and frameworks
Answer:
Yes. You can place <script> tags either in the <head> or the <body>.
✅ Best Practice:
- Place scripts at the end of
<body>, or use the**defer**/**async**attributes in<head>to avoid render-blocking.
📌 Example with defer:
<script src="script.js" defer></script>| Attribute | Description |
|---|---|
async |
Loads the script asynchronously and executes it as soon as it’s ready, may not preserve order |
defer |
Loads the script asynchronously but executes it after HTML parsing is complete, preserves order |
Answer: Yes, JavaScript can be run without HTML in environments like:
- Node.js (server-side scripting)
- REPL/CLI tools
- Script runners (Bun, Deno)
- Command line interpreters (
node file.js)
Answer:
- In React, JavaScript is written using JSX — a syntax extension combining HTML and JavaScript.
- In Angular, JavaScript/TypeScript is used in components and services, with HTML templates.
| Method | Location | Use Case | Example |
|---|---|---|---|
| Inline | In HTML attribute | Small event handlers | <button onclick="..."> |
| Internal | In <script> tag |
Small apps, quick test | <script> ... </script> |
| External | Separate .js file |
Best practice | <script src="file.js" defer></script> |
| Type | Environment | Example |
|---|---|---|
| Client-side | Browser | Chrome, Firefox |
| Server-side | Node.js | Express API |