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:
- Manipulate web page content - Change text, images, and styles dynamically
- Handle user interactions - Respond to clicks, keyboard input, form submissions
- Communicate with servers - Fetch and send data without page reloads
- Build complete applications - Create web apps, mobile apps, desktop apps, and servers
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
- 1995 - JavaScript created for Netscape Navigator by Brendan Eich in 10 days
- 1996 - Microsoft creates JScript for Internet Explorer, beginning the "browser wars"
- 1997 - ECMAScript standardization begins (ECMA-262)
- 1999 - ES3 released, forming the basis of JavaScript for the next decade
- 2005 - Ajax revolution begins (Gmail, Google Maps demonstrate JS capabilities)
- 2006 - jQuery released, simplifying DOM manipulation
- 2009 - Node.js brings JavaScript to servers; ES5 adds strict mode
- 2010 - AngularJS (by Google) and Backbone.js emerge
- 2013 - React.js released by Facebook
- 2014 - Vue.js created by Evan You
- 2015 - ES6 (ECMAScript 2015) revolutionizes the language with classes, modules, arrow functions
- 2016-Present - Annual ECMAScript releases (ES2016, ES2017, etc.)
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.
// 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:
- Chrome/Edge: Press
F12orCtrl + Shift + J(Windows) /Cmd + Option + J(Mac) - Firefox: Press
F12orCtrl + Shift + K(Windows) /Cmd + Option + K(Mac) - Safari: Enable Developer menu in Preferences, then
Cmd + Option + C
Try typing this in your console and press Enter:
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:
- ESLint - Catches errors and enforces code style
- Prettier - Automatically formats your code
- Live Server - Launches a local development server
- JavaScript (ES6) code snippets - Helpful code shortcuts
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.
{
"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.
{
"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
- Auto Rename Tag - Automatically renames paired HTML tags
- Bracket Pair Colorizer - Colors matching brackets for better readability
- GitLens - Supercharges Git capabilities in VS Code
- Path Intellisense - Autocompletes file paths in your code
- Error Lens - Shows errors and warnings inline in your code
- Console Ninja - Shows console.log output directly in your editor
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:
- Node.js runtime - Execute JavaScript outside the browser
- npm (Node Package Manager) - Install and manage JavaScript packages
- npx - Run packages without installing them globally
Verify Installation
Open your terminal (Command Prompt on Windows, Terminal on Mac/Linux) and run:
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:
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()}`);
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:
- V8 - Chrome, Edge, Node.js, Deno
- SpiderMonkey - Firefox
- JavaScriptCore (Nitro) - Safari
Checking Compatibility
Before using newer JavaScript features, check their browser support:
- Can I Use - Check browser support for any feature
- MDN Web Docs - Comprehensive docs with compatibility tables
- ECMAScript Compatibility Table - ES feature support by browser
Handling Compatibility Issues
// 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:
<!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>
// 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.
<script src="script.js"></script>
2. Internal Script
Write JavaScript directly inside <script> tags in your 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.
<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:
// 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
// ❌ 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
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
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
// ❌ 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
// ❌ 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:
- JavaScript is a versatile programming language for web development and beyond
- It was created by Brendan Eich in 1995 and standardized as ECMAScript
- Major milestones include ES6 (2015), Node.js (2009), and the rise of modern frameworks
- You can run JavaScript in the browser console for quick experiments
- VS Code is the recommended editor with essential extensions like ESLint and Prettier
- Node.js allows you to run JavaScript outside the browser and use npm packages
- Browser compatibility is important - use tools like "Can I Use" to check feature support
- External JavaScript files are the preferred way to organize your code
- The
consoleobject provides powerful debugging tools - Common mistakes include semicolon issues, comparison operators, and DOM timing
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.