DEV Community

Chithra Priya
Chithra Priya

Posted on

Today JavaScript topics: Local variable and Global Variable, Introduction to DOM..

πŸ”΅ 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>&lt;!DOCTYPE html&gt;<br> <html><br> <head><br> <title>Internal JS Example</title><br> <script><br> function sayHello() {<br> alert(&quot;Hello from internal JS!&quot;);<br> }<br>

Click Me

Top comments (0)