Introduction to JavaScript
Table of Contents
JavaScript is the programming language that makes websites interactive. While HTML gives a page its structure and CSS controls how it looks, JavaScript is what makes things happen — responding to clicks, updating content, validating forms, and much more. If you’ve ever clicked a button on a website and something changed without the page reloading, that was JavaScript at work.
In this tutorial, we’ll cover the fundamentals you need to start writing JavaScript. By the end, you’ll understand how to add JavaScript to a web page, work with variables and data types, write basic functions, and build a small interactive example.
Adding JavaScript to an HTML Page
There are three ways to include JavaScript in a web page. Let’s look at each one.
console.log() prints output to the browser’s developer console. You can open it with F12 or Ctrl+Shift+J (Windows/Linux) / Cmd+Option+J (macOS). It’s the easiest way to see what your code is doing while you learn.
Variables: var, let, and const
Variables store values so you can use them later. JavaScript has three keywords for declaring variables.
var name = "Alice"; // old way — function-scoped
let age = 25; // modern — block-scoped, can be reassigned
const country = "US"; // modern — block-scoped, cannot be reassigned
Use const by default. Switch to let when you need to reassign a value. Avoid var in new code — it has quirky scoping behavior that leads to bugs.
const greeting = "Hello";
let count = 0;
count = count + 1; // works fine — let allows reassignment
console.log(count); // 1
// greeting = "Hi"; // ERROR — const cannot be reassigned
var is function-scoped rather than block-scoped, which means it can leak out of if blocks and for loops in unexpected ways. Stick with let and const unless you’re working with legacy code.
Data Types
JavaScript has several built-in data types. Here are the ones you’ll use most often:
// String — text wrapped in quotes
const name = "Alice";
// Number — integers and decimals
const age = 25;
const price = 9.99;
// Boolean — true or false
const isLoggedIn = true;
// Null — intentionally empty
const selectedItem = null;
// Undefined — declared but not assigned
let score;
console.log(score); // undefined
// Array — an ordered list of values
const colors = ["red", "green", "blue"];
// Object — a collection of key-value pairs
const user = {
name: "Alice",
age: 25,
isLoggedIn: true
};
You can check a value’s type with the typeof operator:
console.log(typeof "hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof null); // "object" (a known JavaScript quirk)
Operators
JavaScript operators let you perform calculations, compare values, and combine conditions.
// Arithmetic
console.log(10 + 3); // 13
console.log(10 - 3); // 7
console.log(10 * 3); // 30
console.log(10 / 3); // 3.333...
console.log(10 % 3); // 1 (remainder)
// Comparison
console.log(5 === 5); // true (strict equality — checks value AND type)
console.log(5 === "5"); // false
console.log(5 == "5"); // true (loose equality — converts types first)
console.log(5 !== 3); // true
// Logical
console.log(true && false); // false (AND — both must be true)
console.log(true || false); // true (OR — at least one must be true)
console.log(!true); // false (NOT — flips the value)
=== (strict equality) instead of == (loose equality). Loose equality performs type coercion, which can produce surprising results like 0 == "" being true.
Functions
Functions let you group code into reusable blocks. JavaScript has two common ways to write them.
// Function declaration
function greet(name) {
return "Hello, " + name + "!";
}
// Arrow function (modern syntax)
const greetArrow = (name) => {
return "Hello, " + name + "!";
};
console.log(greet("Alice")); // "Hello, Alice!"
console.log(greetArrow("Bob")); // "Hello, Bob!"
If an arrow function has a single expression, you can write it even shorter:
const double = (n) => n * 2;
console.log(double(5)); // 10
Functions can take multiple parameters and use default values:
function introduce(name, role = "student") {
return name + " is a " + role;
}
console.log(introduce("Alice")); // "Alice is a student"
console.log(introduce("Bob", "developer")); // "Bob is a developer"
Control Flow: if/else
Control flow lets your program make decisions based on conditions.
const temperature = 30;
if (temperature > 35) {
console.log("It's really hot outside");
} else if (temperature > 20) {
console.log("Nice weather today");
} else {
console.log("It's a bit cold");
}
// Output: "Nice weather today"
You can combine conditions with logical operators:
const age = 20;
const hasTicket = true;
if (age >= 18 && hasTicket) {
console.log("Welcome to the event");
} else {
console.log("Entry denied");
}
// Output: "Welcome to the event"
Putting It All Together: An Interactive Example
Let’s combine everything into a complete, working example. This page has a text input and a button — when the user types their name and clicks the button, a personalized greeting appears.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Greeting App</title>
</head>
<body>
<h1>Greeting App</h1>
<label for="nameInput">Enter your name:</label>
<input type="text" id="nameInput" placeholder="Your name">
<button id="greetBtn">Greet Me</button>
<p id="output"></p>
<script>
const button = document.getElementById("greetBtn");
const input = document.getElementById("nameInput");
const output = document.getElementById("output");
function getGreeting(name) {
const hour = new Date().getHours();
if (hour < 12) {
return "Good morning, " + name + "!";
} else if (hour < 18) {
return "Good afternoon, " + name + "!";
} else {
return "Good evening, " + name + "!";
}
}
button.addEventListener("click", function () {
const name = input.value.trim();
if (name === "") {
output.textContent = "Please enter your name.";
} else {
output.textContent = getGreeting(name);
}
});
</script>
</body>
</html>
This example uses several concepts from this tutorial:
constandletfor variables- A function (
getGreeting) with a parameter and return value if/elsefor control flow- String concatenation to build the output
document.getElementById()to interact with HTML elements
Save this as an .html file and open it in your browser to try it out.
What’s Next?
You now have a solid foundation in JavaScript basics. From here, you can explore deeper topics like working with Node.js to run JavaScript outside the browser, or continue building on your web development fundamentals to understand how everything fits together.