Introduction & Setup

30 min read Beginner

Learn what JavaScript is, its history and evolution, and how to set up your development environment to start writing code.

What is JavaScript?

JavaScript is a versatile, high-level programming language that powers the interactive web. Originally created to add dynamic behavior to web pages, it has evolved into one of the most widely-used programming languages in the world.

JavaScript can:

JavaScript vs Java

Despite the similar names, JavaScript and Java are completely different languages. The name was a marketing decision made in the 1990s when Java was popular.

A Brief History

JavaScript was created by Brendan Eich in just 10 days in 1995 while working at Netscape. Originally called "Mocha," then "LiveScript," it was finally renamed to JavaScript.

Key Milestones

Today, JavaScript runs in every web browser, on servers via Node.js, in mobile apps through React Native, and even in desktop applications with Electron.

The Name "JavaScript"

JavaScript was originally named Mocha, then briefly LiveScript, before Netscape partnered with Sun Microsystems and renamed it JavaScript as a marketing strategy. This was because Java was extremely popular at the time. Despite the similar names, JavaScript and Java are completely different languages with different use cases, syntax, and type systems.

ECMAScript: The Standard

ECMAScript is the official specification that JavaScript implements. When you hear "ES6" or "ES2015," it refers to a specific version of this specification. Modern JavaScript engines in browsers implement ECMAScript, ensuring code works consistently across different platforms.

ECMAScript Versions Overview
// ES5 (2009) - The foundation
var name = "JavaScript";

// ES6/ES2015 - The revolution
const name = "JavaScript";
let counter = 0;
const greet = () => console.log("Hello!");

// ES2020 - Modern features
const value = obj?.property?.nested; // Optional chaining
const result = null ?? "default";    // Nullish coalescing

// ES2022 - Latest additions
class MyClass {
    #privateField = "secret";  // Private class fields
}

Setting Up Your Environment

One of the great things about JavaScript is how easy it is to get started. You already have everything you need if you have a web browser!

Using the Browser Console

Every modern browser includes Developer Tools with a JavaScript console. This is the fastest way to start experimenting with JavaScript.

To open the console:

Try typing this in your console and press Enter:

console
console.log("Hello, JavaScript!");

You should see Hello, JavaScript! printed in the console. Congratulations, you've just run your first JavaScript code!

Setting Up a Code Editor

For writing larger programs, you'll want a proper code editor. We recommend Visual Studio Code (VS Code) - it's free, powerful, and has excellent JavaScript support.

Download VS Code: https://code.visualstudio.com/

Recommended extensions for JavaScript:

VS Code Extensions Deep Dive

Let's explore the most important extensions in more detail:

ESLint

ESLint is a static code analysis tool that identifies problematic patterns in your JavaScript code. It helps you catch bugs early and maintain consistent code style across your project.

.eslintrc.json (Basic Configuration)
{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": "eslint:recommended",
    "rules": {
        "no-unused-vars": "warn",
        "no-console": "off",
        "semi": ["error", "always"]
    }
}

Prettier

Prettier is an opinionated code formatter that ensures your code looks consistent. It removes debates about code style by automatically formatting on save.

.prettierrc (Basic Configuration)
{
    "semi": true,
    "singleQuote": true,
    "tabWidth": 2,
    "trailingComma": "es5",
    "printWidth": 80
}

Live Server

Live Server launches a local development server with live reload capability. Every time you save a file, your browser automatically refreshes to show the changes.

Pro Tip: Enable Format on Save

In VS Code settings, enable "Format on Save" to automatically format your code with Prettier every time you save. Go to Settings → search "format on save" → check the box.

Additional Useful Extensions

Setting Up Node.js

While JavaScript started in browsers, Node.js allows you to run JavaScript on your computer outside the browser. This is essential for modern JavaScript development, enabling you to use build tools, package managers, and server-side JavaScript.

Installing Node.js

Download Node.js: https://nodejs.org/

Choose the LTS (Long Term Support) version for stability. The installer includes:

Verify Installation

Open your terminal (Command Prompt on Windows, Terminal on Mac/Linux) and run:

Terminal
node --version
# Should output something like: v18.17.0

npm --version
# Should output something like: 9.6.7

Running JavaScript with Node.js

Create a file called hello.js and run it directly:

hello.js
console.log("Hello from Node.js!");

// Node.js can access the file system (unlike browser JS)
const os = require('os');
console.log(`Your computer has ${os.cpus().length} CPU cores`);
console.log(`Platform: ${os.platform()}`);
console.log(`Home directory: ${os.homedir()}`);
Terminal
node hello.js

Browser vs Node.js

In browsers, JavaScript has access to the DOM (document) and browser APIs (window, fetch). In Node.js, you instead have access to system resources like the file system (fs), networking, and operating system info.

Browser Compatibility

Different browsers implement JavaScript features at different speeds. Understanding browser compatibility is crucial for writing code that works everywhere.

JavaScript Engines

Each browser uses a different JavaScript engine to execute code:

Checking Compatibility

Before using newer JavaScript features, check their browser support:

Handling Compatibility Issues

Feature Detection Example
// Check if a feature exists before using it
if ('IntersectionObserver' in window) {
    // Modern browsers - use IntersectionObserver
    const observer = new IntersectionObserver(callback);
} else {
    // Fallback for older browsers
    window.addEventListener('scroll', handleScroll);
}

// Check for optional chaining support
const supportsOptionalChaining = (() => {
    try {
        eval('const obj = {}; obj?.prop');
        return true;
    } catch {
        return false;
    }
})();

Babel & Transpilation

Tools like Babel can convert modern JavaScript (ES6+) into older versions that work in legacy browsers. This is called "transpilation" and is commonly used in professional projects. You'll learn more about this in the Build Tools topic.

Your First JavaScript File

Let's create a proper JavaScript project. Follow these steps:

Step 1: Create Project Files

Create a new folder called my-first-js and add two files:

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My First JavaScript</title>
</head>
<body>
    <h1>Welcome to JavaScript</h1>
    <p id="demo">This text will change.</p>
    <button onclick="changeText()">Click Me</button>

    <!-- JavaScript file linked at the bottom of body -->
    <script src="script.js"></script>
</body>
</html>
script.js
// This is a comment - it's ignored by JavaScript

// Log a message to the console
console.log("Script loaded successfully!");

// Function to change the text when button is clicked
function changeText() {
    // Find the element with id="demo"
    const paragraph = document.getElementById("demo");
    
    // Change its text content
    paragraph.textContent = "JavaScript is working!";
    
    // Log to console
    console.log("Text was changed!");
}

Step 2: Run Your Code

Open index.html in your browser (double-click the file or drag it into your browser). Click the button to see JavaScript in action!

Best Practice

Place your <script> tag at the end of the <body> so the HTML loads before the JavaScript runs. This prevents errors when trying to access elements that haven't loaded yet.

Three Ways to Include JavaScript

1. External File (Recommended)

Link to a separate .js file. This keeps your code organized and reusable.

HTML
<script src="script.js"></script>

2. Internal Script

Write JavaScript directly inside <script> tags in your HTML.

HTML
<script>
    console.log("This is internal JavaScript");
</script>

3. Inline (Avoid if Possible)

JavaScript directly in HTML attributes. This mixes concerns and is harder to maintain.

HTML
<button onclick="alert('Clicked!')">Click</button>

Avoid Inline JavaScript

While inline JavaScript works, it's considered bad practice because it mixes HTML structure with JavaScript behavior, making code harder to read, maintain, and debug.

Console Methods for Debugging

The console object provides several useful methods for debugging:

script.js
// Basic logging
console.log("Regular message");

// Informational message
console.info("Info message");

// Warning (yellow)
console.warn("This is a warning");

// Error (red)
console.error("This is an error");

// Display data as a table
console.table(["Apple", "Banana", "Cherry"]);

// Group related logs
console.group("User Details");
console.log("Name: John");
console.log("Age: 30");
console.groupEnd();

// Measure time
console.time("Loop");
for (let i = 0; i < 1000; i++) {
    // Some operation
}
console.timeEnd("Loop"); // Outputs: Loop: Xms

// Clear the console
console.clear();

Common Beginner Mistakes to Avoid

Learning JavaScript is exciting, but there are some common pitfalls that trip up beginners. Let's address them early so you can avoid frustration!

1. Forgetting Semicolons in Critical Places

JavaScript
// ❌ Problem: This can cause issues
const getName = () => {
    return
        "John"  // JavaScript inserts semicolon after "return"!
}
console.log(getName()); // undefined

// ✅ Solution: Keep return value on same line
const getName = () => {
    return "John";
}
// Or use parentheses for multi-line
const getUser = () => {
    return {
        name: "John",
        age: 30
    };
}

2. Using = Instead of === for Comparison

JavaScript
let score = 10;

// ❌ Wrong: This ASSIGNS the value, not compares!
if (score = 5) {  // Always true! score is now 5
    console.log("Score is 5");
}

// ✅ Correct: Use === for comparison
if (score === 5) {
    console.log("Score is 5");
}

// Also be careful with == vs ===
console.log("5" == 5);   // true (type coercion)
console.log("5" === 5);  // false (strict equality)

3. Forgetting That Arrays Are Zero-Indexed

JavaScript
const fruits = ["Apple", "Banana", "Cherry"];

// ❌ Common mistake
console.log(fruits[3]);  // undefined (no 4th item!)

// ✅ Remember: First item is at index 0
console.log(fruits[0]);  // "Apple"
console.log(fruits[2]);  // "Cherry" (3rd item)
console.log(fruits[fruits.length - 1]);  // Last item

4. Case Sensitivity Matters

JavaScript
// ❌ These are all DIFFERENT variables
let myVariable = 1;
let myvariable = 2;
let MYVARIABLE = 3;

// ❌ Common typos that cause errors
document.getElementById("demo");  // ✅ Correct
document.getElementByID("demo");  // ❌ Error! (ID not ID)
Document.getElementById("demo");  // ❌ Error! (lowercase d)

5. Trying to Access DOM Before It's Ready

JavaScript
// ❌ If this script is in <head>, elements don't exist yet!
const button = document.getElementById("myButton");
button.addEventListener("click", handleClick);  // Error!

// ✅ Solution 1: Put script at end of body

// ✅ Solution 2: Wait for DOM to be ready
document.addEventListener("DOMContentLoaded", function() {
    const button = document.getElementById("myButton");
    button.addEventListener("click", handleClick);
});

// ✅ Solution 3: Use defer attribute
// <script src="script.js" defer></script>

Debugging Tip

When something doesn't work, always check the browser console (F12) for error messages. JavaScript errors are usually descriptive and tell you exactly which line caused the problem!

Summary

In this introduction, you've learned:

Next Steps

You're ready to dive into JavaScript syntax! In the next topic, you'll learn about variables, data types, and operators - the building blocks of every program.