DEV Community

Cover image for JavaScript Basics Tutorial — Introduction, Syntax, Output & Comments
CodePractice
CodePractice

Posted on

JavaScript Basics Tutorial — Introduction, Syntax, Output & Comments

So you've decided to learn JavaScript. Good choice. Honestly, one of the best decisions you'll make as a developer.

JavaScript is the language of the web. It's what turns a static HTML page into something people actually want to use — buttons that respond, forms that validate, content that updates without a full page reload. And the best part? You don't need to install anything to get started. Your browser already has a JavaScript engine running right now.

In this post, we'll cover the absolute fundamentals — the stuff you need to understand before writing your first real program. Let's go.

Table of Contents

What is JavaScript?

JS Introduction || CodePractice

Learn JavaScript basics with this easy guide. See how it works and how to add dynamic features to websites. Includes 5 hands-on examples and 10 MCQs. Start now!

favicon codepractice.in

JavaScript is a lightweight, interpreted programming language designed to run inside web browsers. It was created in 1995 by Brendan Eich in just 10 days — and despite that rushed origin, it has become one of the most widely-used programming languages on the planet.

Here's how the three core web technologies work together:

HTML  ──►  Structure   (the skeleton)
CSS   ──►  Presentation (the style)
JS    ──►  Behaviour    (the brain)
Enter fullscreen mode Exit fullscreen mode

Without JavaScript, every website would just be a static document — like a PDF you can't interact with. JavaScript is what adds life.

What makes JavaScript unique:

  • ✅ Runs directly in the browser — no compilation needed
  • ✅ Can manipulate HTML and CSS in real time
  • ✅ Handles user events (clicks, keyboard input, form submissions)
  • ✅ Makes API calls and fetches data without refreshing the page
  • ✅ Also runs on servers with Node.js

💡 Quick fact: JavaScript has nothing to do with Java. They share a similar name for marketing reasons from the 90s, but they're completely different languages.

Where Do You Write JavaScript?

JS Where To || CodePractice

Learn where to place JavaScript in HTML files — inside <head>, at the bottom of <body>, or in external files. Understand best practices and performance tips.

favicon codepractice.in

There are three ways to include JavaScript in your project. Each has its use case:

1️⃣ Inline JavaScript

<button onclick="alert('Hello!')">Click Me</button>
Enter fullscreen mode Exit fullscreen mode

JS written directly inside an HTML attribute. Quick for tiny demos, but messy and hard to maintain. Avoid in real projects.

2️⃣ Internal JavaScript (Inside <script> tags)

<!DOCTYPE html>
<html>
  <body>
    <h1>My Page</h1>

    <script>
      console.log("Hello from internal JS!");
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

JavaScript lives in a <script> block inside your HTML file. Better than inline, but still mixes markup and logic.

3️⃣ External JavaScript ✅ (The Right Way)

index.html

<!DOCTYPE html>
<html>
  <body>
    <h1>My Page</h1>
    <script src="app.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

app.js

console.log("Hello from external JS!");
Enter fullscreen mode Exit fullscreen mode

A separate .js file linked via <script src="">. This is how real-world projects are structured — clean, maintainable, and reusable across multiple pages.

⚠️ Important: Always place your <script> tag just before the closing </body> tag. This ensures your HTML is fully loaded before JavaScript tries to interact with it.

How to Display Output

JS Output || CodePractice

Learn JavaScript output methods with this easy guide. See how to use innerHTML, alert, and console.log with examples. Understand when to use each. Start today!

favicon codepractice.in

JavaScript gives you multiple ways to see output. Each one serves a different purpose:

console.log() — For Developers 🛠️

console.log("Hello, World!");
console.log(42);
console.log([1, 2, 3]);
console.log({ name: "Alice", age: 25 });
Enter fullscreen mode Exit fullscreen mode

This writes to your browser's Developer Console (open with F12). The page visitor never sees it — it's purely for you during development. You'll use this constantly.

alert() — The Pop-Up ⚠️

alert("Something important happened!");
Enter fullscreen mode Exit fullscreen mode

Creates a browser dialog box. Useful for quick testing but annoying in real apps. Use sparingly.

document.write() — Write to Page (With Caution)

document.write("<h2>This was written by JS</h2>");
Enter fullscreen mode Exit fullscreen mode

Writes HTML directly into the document. The catch: calling this after the page loads will wipe your entire HTML. Mainly used in tutorials, not production code.

innerHTML — The Professional Way ✅

<p id="output">Default text</p>

<script>
  document.getElementById("output").innerHTML = "Updated by JavaScript!";
</script>
Enter fullscreen mode Exit fullscreen mode

This targets a specific element and updates its content. This is what you'll use most often when building real UIs.

Quick Comparison

Method Visible to User? Use Case
console.log() ❌ No (Dev only) Debugging & development
alert() ✅ Yes (Pop-up) Quick tests & warnings
document.write() ✅ Yes (Inline) Demos only
innerHTML ✅ Yes (In-page) Real UI updates

JavaScript Statements

JS Statements || CodePractice

Learn JavaScript statements with this easy guide. Understand declarations, loops, and syntax rules. See why semicolons matter with examples. Start coding today!

favicon codepractice.in

A statement is a single instruction you give JavaScript. A program is just a list of statements executed top to bottom, one after another.

let x = 5;           // Statement 1: declare a variable
let y = 10;          // Statement 2: declare another variable
let sum = x + y;     // Statement 3: add them together
console.log(sum);    // Statement 4: print the result → 15
Enter fullscreen mode Exit fullscreen mode

Key Rules for Statements

Semicolons mark the end of a statement:

let name = "Alice";  // ← semicolon ends the statement
Enter fullscreen mode Exit fullscreen mode

JavaScript can usually infer them (ASI — Automatic Semicolon Insertion), but writing them explicitly is considered best practice.

Code blocks group multiple statements with {}:

if (x > 5) {
    console.log("x is greater than 5");
    console.log("still inside the block");
}
// ↑ both statements are part of this block
Enter fullscreen mode Exit fullscreen mode

Whitespace is ignored. Indent for readability:

// Both are valid — the second is just more readable
let z=x+y; // hard to read
let z = x + y; // clear and professional
Enter fullscreen mode Exit fullscreen mode

JavaScript Syntax

JS Syntax || CodePractice

Learn JavaScript syntax with this easy guide. Understand statements, variables, and semicolons with examples and MCQs. Master your code structure today now!

favicon codepractice.in

Syntax is the set of rules that defines how JavaScript code must be written. Break these rules and your code simply won't work.

Variables

Variables are containers that store values:

var oldWay = "avoid this";   // old — function-scoped, hoisted
let counter = 0;             // modern — block-scoped, can reassign
const MAX_SIZE = 100;        // modern — block-scoped, cannot reassign
Enter fullscreen mode Exit fullscreen mode

Rule of thumb: Use const by default. Switch to let only when you need to reassign. Pretend var doesn't exist.

Data Types

// Primitive types
let name    = "Alice";        // String
let age     = 25;             // Number
let isAdmin = false;          // Boolean
let nothing = null;           // Null (intentional empty)
let missing = undefined;      // Undefined (unassigned)

// Reference types
let colors  = ["red", "blue", "green"];   // Array
let user    = { name: "Alice", age: 25 }; // Object
Enter fullscreen mode Exit fullscreen mode

Operators

// Arithmetic
5 + 3   // 8  — addition
10 - 4  // 6  — subtraction
3 * 4   // 12 — multiplication
20 / 5  // 4  — division
10 % 3  // 1  — modulus (remainder)

// Assignment
let x = 5;     // assigns 5 to x
x += 3;        // x is now 8 (shorthand for x = x + 3)

// Comparison — ALWAYS use === not ==
x === 8   // true  — strict equality (value + type)
x == "8"  // true  — loose equality (just value, unsafe!)
x !== 5   // true  — not equal
x > 3     // true  — greater than
Enter fullscreen mode Exit fullscreen mode

🚨 Critical habit: Always use === (triple equals) for comparisons. The double equals == does type coercion and can produce unexpected results like 0 == false being true.

Case Sensitivity

JavaScript is fully case-sensitive:

let myVariable = "Hello";
let myvariable = "World";  // completely different variable!

console.log(myVariable);   // "Hello"
console.log(myvariable);   // "World"
Enter fullscreen mode Exit fullscreen mode

Expressions vs Statements

// Expression — evaluates to a value
5 + 3              // → 8
"Hello" + " World" // → "Hello World"
x > 5              // → true or false

// Statement — performs an action
let total = 5 + 3; // declares a variable (action)
console.log(total);// prints to console (action)
Enter fullscreen mode Exit fullscreen mode

JavaScript Comments

JS Comments || CodePractice

Learn JavaScript comments with this easy guide. See how to use single and multi-line comments with examples and MCQs. Master your code readability today now!

favicon codepractice.in

Comments are lines of text that JavaScript completely ignores. They exist for one purpose: helping humans understand the code.

Single-Line Comments //

// This calculates the final price including 18% GST
let finalPrice = basePrice * 1.18;

let retryLimit = 3; // Maximum API retry attempts
Enter fullscreen mode Exit fullscreen mode

Multi-Line Comments /* */

/*
  Authentication middleware
  Checks if the user has a valid JWT token before
  allowing access to protected routes.

  Returns 401 if token is missing or expired.
*/
function authenticateUser(req, res, next) {
    // ... implementation
}
Enter fullscreen mode Exit fullscreen mode

Commenting Out Code (During Debugging)

function calculateDiscount(price) {
    // let discount = price * 0.1;  ← temporarily disabled
    let discount = price * 0.2;     // testing 20% instead
    return price - discount;
}
Enter fullscreen mode Exit fullscreen mode

🔑 The Golden Rule of Comments

Comment the WHY, not the WHAT.

// ❌ BAD — tells us what the code already shows
let count = count + 1; // increment count by 1

// ✅ GOOD — explains the reasoning
let retryCount = retryCount + 1; // retry on network failure, max 3 times before giving up
Enter fullscreen mode Exit fullscreen mode

The code tells you what is happening. A good comment tells you why it's happening that way — the context, the constraints, the decision behind it.

Putting It All Together

Here's a small but complete script that uses everything we covered:

// ============================================
// Simple Click Counter
// Demonstrates: variables, output, statements,
// syntax, and comments working together
// ============================================

const BUTTON_LABEL = "You've clicked ";  // constant — label text won't change
let clickCount = 0;                       // let — will change on each click

/*
  Updates the counter display and logs
  to console every time the button is clicked.
*/
function handleClick() {
    clickCount += 1;  // increment the counter

    // Update the visible text on the page
    document.getElementById("counter").innerHTML =
        BUTTON_LABEL + clickCount + " times!";

    // Log for debugging during development
    console.log("Click registered. Total:", clickCount);
}
Enter fullscreen mode Exit fullscreen mode

HTML for this script:

<button onclick="handleClick()">Click Me!</button>
<p id="counter">You've clicked 0 times!</p>
<script src="counter.js"></script>
Enter fullscreen mode Exit fullscreen mode

That's a complete, working mini-app — variables, constants, output, statements, syntax, and comments all in one place. Not bad for day one.

Recap

Here's everything we covered, in one table:

Topic Core Takeaway
What is JS The language that makes web pages interactive
Where to write External .js files (linked via <script src="">)
Output console.log() for dev, innerHTML for production
Statements Individual instructions; end with ;; grouped in {}
Syntax Use const/let, always ===, camelCase naming
Comments // single-line, /* */ multi-line; comment the why

What's Next?

In the next part of this series, we'll dive into Variables & Data Types — understanding strings, numbers, booleans, arrays, and objects in depth.

But before that — don't just read this. Go open your browser console right now (F12) and type a few of these examples. Break them. Fix them. That's how this actually sticks.


If this helped you, drop a ❤️ and follow for the rest of the series. Got questions? Drop them in the comments — I read every one.


Resources

Top comments (0)