|
| 1 | +// 📌 JavaScript Basics - Variables |
| 2 | + |
| 3 | +// Welcome to the third section of the JavaScript Basics tutorial! |
| 4 | +// Here, you'll learn how to declare and use variables in JavaScript. |
| 5 | + |
| 6 | +// What are Variables? |
| 7 | +// Variables are used to store data values. JavaScript provides three ways to declare variables: |
| 8 | + |
| 9 | +// 🏷️ var - Function-scoped, can be redeclared and updated |
| 10 | +var city = "New York"; |
| 11 | +console.log("var:", city); |
| 12 | + |
| 13 | +// 🔒 let - Block-scoped, can be updated but not redeclared |
| 14 | +let country = "USA"; |
| 15 | +console.log("let:", country); |
| 16 | + |
| 17 | +// 🔐 const - Block-scoped, cannot be updated or redeclared |
| 18 | +const PI = 3.1416; |
| 19 | +console.log("const:", PI); |
| 20 | + |
| 21 | +// ⚠️ Difference between var, let, and const |
| 22 | +function testScope() { |
| 23 | + if (true) { |
| 24 | + var a = "I am var"; // Accessible outside the block |
| 25 | + let b = "I am let"; // Block-scoped |
| 26 | + const c = "I am const"; // Block-scoped |
| 27 | + } |
| 28 | + console.log(a); // Works |
| 29 | + // console.log(b); // Error |
| 30 | + // console.log(c); // Error |
| 31 | +} |
| 32 | +testScope(); |
| 33 | + |
| 34 | +// 💡 Best Practices |
| 35 | +// - Use `const` by default unless the value needs to change. |
| 36 | +// - Use `let` if the value needs to be reassigned. |
| 37 | +// - Avoid `var` due to potential scoping issues. |
| 38 | + |
| 39 | +// 🚀 Practice declaring variables using var, let, and const. |
0 commit comments