Browse Web basics Topics ▼

JavaScript Fundamentals

📂 Behavior 📘 Lesson 4 of 5

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

  1. Reassigning a const: Writing const x = 5; x = 10; raises TypeError: Assignment to constant variable. If a variable needs to change, use let.
  2. undefined vs null: undefined means a variable was declared but never assigned a value. null is an intentional assignment representing empty or absent data.
  3. Forgetting await on Asynchronous Calls: If you write const res = fetch(url);, res is a pending Promise object, not the response! Always remember await.
  4. Using var: var is function-scoped and creates tricky variable leaking bugs. Always use const and let.

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.

Test your understanding of JavaScript Fundamentals

Quick interactive practice questions with instant feedback.

Take Quiz →