In this article · 10 sections
HTML builds the structure, CSS styles it, and JavaScript makes it interactive. These JavaScript basics cover what you need to start adding real features to websites: calculations, form checks, menus and live content.
Where JavaScript goes
<script src="/js/app.js" defer></script>
defer loads the file without blocking the page and runs it after the HTML is parsed.
Variables
const city = "Ludhiana"; // can't be reassigned
let fare = 3500; // can change
fare = fare + 200;
Use const by default and let when the value changes. Avoid the older var.
Data types
const name = "Joboo"; // string
const km = 310; // number
const isAC = true; // boolean
const cars = ["Dzire", "Innova"]; // array
const booking = { from: "Ludhiana", to: "Delhi", km: 310 }; // object
Functions
function calcFare(km, ratePerKm) {
return km * ratePerKm;
}
const total = calcFare(310, 12); // 3720
Arrow function version:
const calcFare = (km, rate) => km * rate;
Conditions and loops
if (km > 250) {
console.log("Long trip");
} else {
console.log("Short trip");
}
for (const car of cars) {
console.log(car);
}
Arrays: useful methods
const prices = [2500, 3200, 4100];
const withToll = prices.map(p => p + 300);
const cheap = prices.filter(p => p < 3500);
The DOM: changing the page
const btn = document.querySelector("#calc");
const out = document.querySelector("#result");
btn.addEventListener("click", () => {
const km = Number(document.querySelector("#km").value);
out.textContent = "Estimated fare: ₹" + calcFare(km, 12);
});
<input id="km" type="number" placeholder="Distance in km">
<button id="calc" type="button">Calculate</button>
<p id="result"></p>
Use textContent (not innerHTML) when inserting user input, to avoid XSS.
Debugging
Open DevTools (F12) → Console to see errors and use console.log(). See Chrome DevTools guide.
Next steps
- Load data without page reloads: fetch and AJAX tutorial
- Validate forms: form validation tutorial
- Build a mobile menu: responsive navbar tutorial
FAQs
Is JavaScript the same as Java?
No. They're different languages with different uses.
Should I learn jQuery?
It's useful for maintaining older sites, but modern JavaScript covers most of what jQuery was used for.
Was this article helpful?
Your answer helps us improve our guides