JavaScript Fundamentals — Values, Functions and the DOM
এই অধ্যায়ে যা শিখবেন
- Choose between let and const
- write functions and arrow functions
- read and change page content safely through the DOM
পূর্বশর্ত
- HTML basics
JavaScript is the programming language of the web browser. It also runs on servers (Node.js). This tutorial covers the core language and how scripts interact with a page.
Variables: let and const
const siteName = 'WAN Web Development'; // cannot be reassigned
let visits = 0; // can change
visits = visits + 1;
Prefer const; use let only when the value must change. Avoid the older var, which is function-scoped and easy to misuse.
Types
typeof 42; // "number"
typeof 'hello'; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof { a: 1 }; // "object"
typeof [1, 2]; // "object" — use Array.isArray([1, 2]) → true
Use strict equality ===, which does not convert types: '5' === 5 is false, while '5' == 5 is true.
Functions
function area(width, height) {
return width * height;
}
const square = (n) => n * n; // arrow function
area(3, 4); // 12
square(5); // 25
Arrays and objects
const scores = [72, 88, 95];
const passed = scores.filter((s) => s >= 80); // [88, 95]
const total = scores.reduce((a, b) => a + b, 0); // 255
const learner = { name: 'Nusrat', level: 'BEGINNER' };
learner.level = 'INTERMEDIATE';
const { name } = learner; // destructuring → "Nusrat"
Working with the DOM
<p id="greeting"></p>
<button id="hello">Say hello</button>
const out = document.getElementById('greeting');
document.getElementById('hello').addEventListener('click', () => {
out.textContent = 'Hello from JavaScript!';
});
Use textContent (not innerHTML) when inserting text that came from a user: innerHTML parses HTML, so untrusted input could inject scripts (cross-site scripting).
Exercises
- Write a function
average(numbers)that returns 0 for an empty array. - Build a counter: a number on the page and two buttons that increase and decrease it.
মন্তব্য (0)
মন্তব্য করতে লগইন করুন।