π΅ Local Variable:
- A local variable is declared inside a function.
- It can only be used within that function (not outside).
function greet() {
let localVar = "I'm local!";
console.log(localVar); // Accessible here
}
greet();
// console.log(localVar); // β Error: localVar is not defined
π’ Global Variable:
- A global variable is declared outside any function.
- It can be accessed from anywhere in the code (inside or outside functions).
let globalVar = "I'm global!";
function sayHello() {
console.log(globalVar); // Accessible here
}
sayHello();
console.log(globalVar); // Also accessible here
Link JavaScript file in HTML file:
In HTML, you can link or write JavaScript in three ways: inline, internal, and external. Here's a clear explanation with examples for each:
β 1. Inline JavaScript
JavaScript is written directly inside an HTML tag's attribute, like onclick.
<!DOCTYPE html>
<html>
<body>
<button onclick="alert('Hello from inline JS!')">Click Me</button>
</body>
</html>
π Use for: Very short scripts or event handlers.
β οΈ Not recommended for large or reusable code.
β 2. Internal JavaScript
JavaScript is written inside a tag within the HTML file.</p>
<p><!DOCTYPE html><br>
<html><br>
<head><br>
<title>Internal JS Example</title><br>
<script><br>
function sayHello() {<br>
alert("Hello from internal JS!");<br>
}<br>
Click Me
Top comments (0)