JavaScript is a high-level, interpreted programming language that makes web pages interactive. It runs in the browser and is one of the three core technologies of the web alongside HTML and CSS.
You can add JavaScript directly inside HTML elements using event attributes:
<button onclick="alert('Hello!')">Click Me</button>
Place code inside a <script> tag in the <head> or before the closing </body>:
<script>
console.log("Hello from internal JS");
</script>
Link a separate .js file using the src attribute:
<script src="app.js"></script>
JavaScript provides several ways to display output:
// Console output — great for debugging
console.log("This goes to the browser console");
// Write directly to the document
document.write("This appears on the page");
// Show a popup dialog
alert("This is an alert box");
JavaScript statements end with a semicolon (optional but recommended). The language ignores whitespace, making it flexible in formatting.
// This is a single-line comment
/*
This is
a multi-line
comment
*/
Use var, let, or const to declare variables:
// var — function-scoped, avoid in modern code
var name = "Alice";
// let — block-scoped, can be reassigned
let age = 25;
age = 26;
// const — block-scoped, cannot be reassigned
const birthYear = 1998;
const by default and use let only when you need to reassign. Avoid var in modern JavaScript.
let sum = 10 + 5; // 15
let diff = 10 - 5; // 5
let product = 10 * 5; // 50
let quotient = 10 / 5; // 2
let mod = 10 % 3; // 1
let exp = 2 ** 3; // 8
let x = 10;
x += 5; // x = 15
x -= 3; // x = 12
x *= 2; // x = 24
x /= 4; // x = 6
5 == "5" // true (loose equality)
5 === "5" // false (strict equality)
5 != "5" // false
5 !== "5" // true
5 > 3 // true
5 <= 5 // true
let a = true, b = false;
a && b // false (AND)
a || b // true (OR)
!a // false (NOT)
myVariable and myvariable are two different identifiers. Use camelCase for variable names by convention.
firstName and lastName, combines them into a full name using the + operator, and logs the result to the console. Then use alert() to display the full name.