JavaScript Basics: Variables and Functions
Adding Logic with JavaScript
JavaScript is the programming language of the web browser. It lets a page make decisions, calculate values, and respond to the user.
Declaring Variables
Modern JavaScript uses let for values that can change and const for values that stay fixed. Each statement ends with a semicolon.
let score = 0;
const collegeName = "Dhaka Commerce College";
score = 10; // allowed, score can change
// collegeName = "x"; // error, const cannot be reassignedData Types
- Number —
42or3.14(one type for all numbers). - String — text in quotes, e.g.
"hello". - Boolean —
trueorfalse. - Array — an ordered list, e.g.
[1, 2, 3].
Writing Functions
A function groups reusable code. Define it with the function keyword, then call it by name.
function greet(name) {
return "Hello, " + name + "!";
}
let message = greet("Ayesha");
console.log(message); // Hello, Ayesha!The console.log() function prints to the browser's developer console, which is your main tool for checking values while learning.
Conditionals
JavaScript uses if, else if, and else, with conditions in parentheses and the block in curly braces.
let marks = 78;
if (marks >= 80) {
console.log("Grade: A+");
} else if (marks >= 70) {
console.log("Grade: A");
} else {
console.log("Keep practising");
}Loops
A for loop repeats code a set number of times.
for (let i = 1; i <= 3; i++) {
console.log("Round " + i);
}The loop has three parts: a start (let i = 1), a condition to keep going (i <= 3), and a step (i++, which adds one each time).
Useconstby default and switch toletonly when you truly need the value to change. This makes your intentions clear to anyone reading the code.
Discussion
0No comments yet — be the first to leave one!