JavaScript Fundamentals
Add interactivity, dynamic logic, and network requests to web pages using modern JavaScript, arrow functions, and async/await.
If HTML is the skeleton of a web page and CSS is the clothing and visual styling, JavaScript (JS) is the muscles, brain, and nervous system.
JavaScript is the world’s most ubiquitous programming language: it is the only language that runs natively inside every modern web browser without needing any plugins or software installations. When you click a like button, see live notifications appear without refreshing the page, or play a game in your browser, JavaScript is running the show.
Running JavaScript
You can test JavaScript right now by opening your browser’s Developer Tools (F12 or right-click -> Inspect -> Console tab).
In production HTML files, JavaScript is linked using the <script> tag:
<!-- Inside index.html, right before the closing </body> tag -->
<script src="app.js"></script>
Declaring Variables: const and let
In modern JavaScript (ES6+), avoid the legacy var keyword because of scoping quirks and bugs. Always use const and let:
const(Constant): Default choice. Use this for values, objects, and functions that will never be reassigned.let: Use this for counters, flags, and variables whose values will change over time.
// Cannot be reassigned:
const maxRetries = 3;
const siteName = "Roadmappro";
// Mutable variable:
let currentScore = 0;
currentScore += 10;
console.log(currentScore); // 10
Core Data Types
JavaScript includes dynamic, lightweight data types:
// 1. Strings (Use backticks `` for template literals with ${} interpolation)
const name = "Alice";
const greeting = `Hello, ${name}! Welcome back.`;
// 2. Numbers (Integers and floats share the Number type)
const price = 49.99;
const quantity = 3;
const total = price * quantity;
// 3. Booleans
const isLoggedIn = true;
const hasSubscription = false;
// 4. Arrays (Ordered lists)
const fruits = ["Apple", "Banana", "Orange"];
fruits.push("Mango");
// 5. Objects (Key-value dictionaries)
const user = {
id: 101,
username: "coder123",
isAdmin: false,
};
console.log(user.username); // "coder123"
Modern Functions and Arrow Syntax
You can declare functions using traditional syntax or modern, concise arrow functions:
// Traditional function declaration:
function addNumbers(a, b) {
return a + b;
}
// Modern Arrow function (concise and idiomatic):
const multiply = (a, b) => a * b;
console.log(addNumbers(5, 10)); // 15
console.log(multiply(4, 5)); // 20
Strict Equality: Why You Must Use ===
One of the most famous traps in JavaScript is loose equality (==), which attempts automatic “type coercion” behind your back:
// LOOSE EQUALITY (DANGEROUS):
console.log(0 == ""); // true! (Coerces empty string to number 0)
console.log(1 == "1"); // true! (Coerces string "1" to number 1)
console.log(null == undefined); // true!
// STRICT EQUALITY (SAFE AND IDIOMATIC):
console.log(0 === ""); // false! (Different types: Number vs String)
console.log(1 === "1"); // false! (Different types)
console.log(null === undefined); // false!
[!IMPORTANT] Always use triple equals (
===and!==). Never use double equals (==and!=).
Asynchronous Code: fetch and async / await
Browsers are single-threaded: if a script pauses to wait for a network download, the entire webpage would freeze and stop responding to clicks.
JavaScript solves this using non-blocking asynchronous programming with Promises and async / await:
async function loadUserData(userId) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const userData = await response.json();
console.log("Fetched user:", userData.name, userData.email);
return userData;
} catch (error) {
console.error("Failed to fetch user data:", error);
}
}
loadUserData(1);
Common Traps to Avoid
- Reassigning a
const: Writingconst x = 5; x = 10;raisesTypeError: Assignment to constant variable. If a variable needs to change, uselet. undefinedvsnull:undefinedmeans a variable was declared but never assigned a value.nullis an intentional assignment representing empty or absent data.- Forgetting
awaiton Asynchronous Calls: If you writeconst res = fetch(url);,resis a pending Promise object, not the response! Always rememberawait. - Using
var:varis function-scoped and creates tricky variable leaking bugs. Always useconstandlet.
Next Steps
Now that you know how to write JavaScript logic, how does your code actually interact with the HTML elements displayed on your screen? How do you listen for button clicks, read form inputs, or change text dynamically?
Discover the bridge between JavaScript and HTML in The DOM (Document Object Model), or dive deep into the full language curriculum in js-variables-declarations.