Lesson 3 of 5

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 reassigned

Data Types

  • Number — 42 or 3.14 (one type for all numbers).
  • String — text in quotes, e.g. "hello".
  • Boolean — true or false.
  • 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).

Use const by default and switch to let only when you truly need the value to change. This makes your intentions clear to anyone reading the code.
Next
How did you find this lesson?

Discussion

0
To join the discussion, comment and react, log in or create an account.

No comments yet — be the first to leave one!