JavaScript Beginner Guide
Master JavaScript from zero with 20 beginner lessons. Each topic includes a deep explanation, runnable code, line-by-line breakdown, exact output, and official MDN documentation links.
Start LearningWhat is JavaScript & Where It Runs
JavaScript is a programming language that runs inside web browsers. It makes web pages interactive — buttons, animations, form checks, and dynamic content. JavaScript can also run on servers using Node.js, but for beginners the browser console is the easiest place to start. You write JS code, the browser's JavaScript engine reads it, and it produces output instantly.
console.log("Hello from JavaScript!");
Setting Up: Console & <script> Tag
You can run JavaScript in two main ways: directly in the browser's Developer Console, or inside an HTML file using the <script> tag. The console is great for quick testing, while the <script> tag connects JavaScript to a real web page. When the browser loads the HTML, it runs the JavaScript inside the script tag.
// Inside an HTML file:
<script>
console.log("Ready to code!");
</script>
Variables: let, const, var
Variables are containers that store data. JavaScript has three ways to declare them: let (can be changed later), const (cannot be changed once set), and var (the older way, now mostly replaced by let). Use let when the value needs to change, and const when it should stay fixed.
let name = "Ali"; const PI = 3.14; var age = 25; console.log(name, PI, age);
Data Types
JavaScript values have different types. The main ones are: string (text), number (integers and decimals), boolean (true/false), null (intentionally empty), and undefined (variable declared but not assigned a value). Knowing the type helps you predict how values behave.
let str = "Hello"; let num = 42; let bool = true; let nul = null; let und; console.log(typeof str, typeof num, typeof bool, typeof nul, typeof und);
Operators
Operators perform actions on values. Arithmetic operators (+, -, *, /, %) do math. Comparison operators (===, >, <) compare values and return true or false. The % operator is modulo — it returns the remainder after division.
let a = 10; let b = 3; console.log(a + b, a - b, a * b, a / b, a % b, a === 10, a > b);
Strings & Template Literals
Strings can be created with single quotes, double quotes, or backticks. Backticks create template literals, which allow you to embed variables directly using ${}. This makes building dynamic text much easier than joining with the + operator.
let name = "Ali";
let age = 25;
console.log(`My name is ${name} and I am ${age} years old.`);
Numbers & Math
JavaScript has a built-in Math object with useful functions for working with numbers. Math.round() rounds to the nearest integer, Math.ceil() always rounds up, Math.floor() always rounds down, Math.max() returns the largest value, and Math.random() returns a random decimal between 0 and 1.
console.log(Math.round(4.7), Math.ceil(4.2), Math.floor(4.9), Math.max(1, 5, 9), Math.random());
Conditionals: if/else & switch
Conditionals allow your code to make decisions. if runs a block when a condition is true, else if checks another condition, and else runs when nothing else matched. switch is another way to compare one value against many possible cases.
let score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 70) {
console.log("B");
} else {
console.log("C");
}
Loops: for & while
Loops repeat a block of code multiple times. A for loop is great when you know how many times to repeat. A while loop keeps running as long as a condition stays true. Loops save you from writing the same line many times.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Functions: Declaration, Expression, Arrow
Functions are reusable blocks of code. There are three common ways to create them: function declarations (function name() {}), function expressions (const name = function() {}), and arrow functions (const name = () => {}). Arrow functions are a shorter modern syntax.
function greet(name) {
return "Hello " + name;
}
const greet2 = (name) => "Hi " + name;
console.log(greet("Ali"), greet2("Sara"));
Parameters & Return
Parameters are variables listed in a function definition that receive input values. The return statement sends a value back to where the function was called. A function can take multiple parameters and return a single computed result.
function add(a, b) {
return a + b;
}
console.log(add(5, 3));
Arrays: Basics
An array is a list of values stored in one variable. Arrays use square brackets and each item has an index starting from 0. You can access items with array[index], and the .length property tells you how many items are inside.
let fruits = ["apple", "banana", "mango"]; console.log(fruits.length, fruits[0], fruits[2]);
Array Methods: push, pop, map, filter
Arrays have built-in methods. push() adds to the end, pop() removes from the end. map() creates a new array by transforming every item, and filter() creates a new array with only items that pass a test. These methods make list work fast and readable.
let nums = [1, 2, 3]; nums.push(4); nums.pop(); let doubled = nums.map(n => n * 2); let even = nums.filter(n => n % 2 === 0); console.log(nums, doubled, even);
Objects: Basics
Objects store related data as key-value pairs. Each key is a property name, and each value is the data for that property. Objects are written with curly braces and are perfect for representing things like a person, a product, or a book.
let person = { name: "Ali", age: 25, isStudent: true };
console.log(person.name, person.age);
Object Access: Dot vs Bracket
You can access object properties in two ways: dot notation (object.key) and bracket notation (object["key"]). Dot notation is shorter, but bracket notation works when the key has special characters or spaces, or when the key is stored in a variable.
let car = { brand: "Toyota", "model year": 2020 };
console.log(car.brand, car["model year"]);
Scope: Global, Function, Block
Scope determines where a variable can be accessed. Global scope means the variable is available everywhere. Function scope means it is only available inside the function where it was declared. Block scope (let and const) means it is only available inside the nearest curly braces {}.
let global = "global";
function test() {
let local = "local";
console.log(local);
}
test();
console.log(global);
Hoisting
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope before execution. Function declarations can be used before they are written. Variables declared with var are hoisted but start as undefined, while let and const are not initialized.
console.log(x); var x = 10; console.log(x);
null vs undefined vs NaN
These three values are easy to confuse. undefined means a variable exists but has no assigned value. null means intentionally empty — you set it yourself. NaN stands for 'Not a Number' and is the result of invalid math like dividing text.
let a; let b = null; let c = "abc" / 2; console.log(a, b, c, typeof a, typeof b, Number.isNaN(c));
Type Coercion & === vs ==
== (loose equality) converts the two values to the same type before comparing, which can cause surprising results. === (strict equality) compares both value and type without converting. As a best practice, always use === to avoid bugs.
console.log(5 == "5", 5 === "5", 0 == false, 0 === false);
Beginner Recap + 3 Mini Projects
You now know variables, data types, operators, strings, numbers, conditionals, loops, functions, arrays, objects, scope, and type handling. Try three mini projects to practice: (1) Number Guessing Game — generate a random number and let the user guess it; (2) Temperature Converter — convert Celsius to Fahrenheit; (3) Simple To-Do List — add and remove items using arrays.
function celsiusToFahrenheit(c) {
return (c * 9/5) + 32;
}
console.log(celsiusToFahrenheit(0), celsiusToFahrenheit(100));
JavaScript Beginner Projects
Apply everything you've learned. Click each project to open its full guide.
About this project
The computer picks a secret number from 1 to 100. You get 7 attempts to find it. After each guess, the program tells you whether to go higher or lower.
What you'll practice
Step-by-step: How it works
Math.random()generates a decimal between 0 and 1.- Multiply by 100 and round up to get a secret number from 1 to 100.
- The loop runs while you still have attempts left.
- Each turn you type a guess using
prompt(). - The program says "too low" or "too high" and shows remaining attempts.
- If you guess correctly, the loop breaks and you win.
- When attempts reach 0, the game ends and reveals the secret number.
console.log("Number Guessing Game\n");
let secret = Math.floor(Math.random() * 100) + 1;
let maxGuesses = 7;
let usedGuesses = 0;
console.log("Guess the secret number between 1 and 100.");
console.log("You have " + maxGuesses + " attempts.\n");
while (usedGuesses < maxGuesses) {
usedGuesses++;
let guess = parseInt(prompt("Attempt " + usedGuesses + ": "));
if (guess === secret) {
console.log("\nCorrect! The secret number is " + secret + ".");
console.log("You found it in " + usedGuesses + " attempt(s).");
break;
}
let remaining = maxGuesses - usedGuesses;
if (guess < secret) {
console.log("Too low. " + remaining + " attempt(s) left.\n");
} else {
console.log("Too high. " + remaining + " attempt(s) left.\n");
}
}
if (usedGuesses === maxGuesses) {
console.log("Out of attempts! The secret number was " + secret + ".");
}
About this project
Convert temperatures between Celsius and Fahrenheit. You choose the direction, enter a value, and the program calculates the result instantly.
What you'll practice
Step-by-step: How it works
- The user picks a conversion direction: C to F or F to C.
- The user enters a temperature value.
parseFloat()converts the input text to a number.- The correct formula runs based on the chosen direction.
- The result is printed using a template literal with two decimal places.
function celsiusToFahrenheit(c) {
return (c * 9 / 5) + 32;
}
function fahrenheitToCelsius(f) {
return (f - 32) * 5 / 9;
}
console.log("Temperature Converter\n");
let choice = prompt("Convert (1) C to F or (2) F to C: ");
let temp = parseFloat(prompt("Enter temperature: "));
if (choice === "1") {
let result = celsiusToFahrenheit(temp);
console.log(`${temp}°C = ${result.toFixed(2)}°F`);
} else if (choice === "2") {
let result = fahrenheitToCelsius(temp);
console.log(`${temp}°F = ${result.toFixed(2)}°C`);
} else {
console.log("Invalid choice.");
}
About this project
Create a simple to-do list. You can add tasks, view all tasks, remove a task by number, and exit — all using arrays and a menu loop.
What you'll practice
Step-by-step: How it works
todosis an empty array that stores tasks.- A
while (true)loop shows the menu and reads the choice. - Choice 1 adds a task using
push(). - Choice 2 lists all tasks with their index numbers.
- Choice 3 removes a task using
splice(). - Choice 4 breaks the loop and exits.
let todos = [];
console.log("Simple To-Do List\n");
while (true) {
console.log("1. Add task");
console.log("2. View tasks");
console.log("3. Remove task");
console.log("4. Exit\n");
let choice = prompt("Choose an option: ");
if (choice === "1") {
let task = prompt("Enter task: ");
todos.push(task);
console.log(`"${task}" added!\n`);
} else if (choice === "2") {
console.log("Your tasks:");
todos.forEach((task, i) => console.log(`${i + 1}. ${task}`));
console.log("");
} else if (choice === "3") {
let num = parseInt(prompt("Task number to remove: "));
if (num > 0 && num <= todos.length) {
let removed = todos.splice(num - 1, 1);
console.log(`Removed: ${removed[0]}\n`);
} else {
console.log("Invalid task number.\n");
}
} else if (choice === "4") {
console.log("Goodbye!");
break;
} else {
console.log("Invalid option.\n");
}
}
Beginner Capstone Project
Put everything together. This capstone combines variables, arrays, loops, functions, conditionals, and object basics into one complete project.
About this project
Build an interactive quiz app with 5 questions. The app asks each question, checks the answer, keeps score, and shows the final result with a percentage and a custom message.
What you'll practice
Step-by-step: How it works
questionsis an array of objects — each object holds a question, options, and correct answer.- A
forloop goes through each question one by one. - The user picks an answer using
prompt(). - If the answer matches,
scoreincreases by 1. - After all questions, the score is converted to a percentage.
- A final message shows the score and percentage.
let questions = [
{
question: "Which keyword declares a constant?",
options: "1) let 2) const 3) var",
answer: "2"
},
{
question: "What does console.log() do?",
options: "1) Reads input 2) Prints output 3) Runs a loop",
answer: "2"
},
{
question: "Which symbol checks strict equality?",
options: "1) == 2) = 3) ===",
answer: "3"
},
{
question: "What does an array use to store items?",
options: "1) [ ] 2) { } 3) ( )",
answer: "1"
},
{
question: "Which loop runs while a condition is true?",
options: "1) for 2) while 3) switch",
answer: "2"
}
];
console.log("Interactive Quiz App\n");
let score = 0;
for (let i = 0; i < questions.length; i++) {
console.log(`Question ${i + 1}: ${questions[i].question}`);
console.log(questions[i].options);
let answer = prompt("Your answer (1, 2, or 3): ");
if (answer === questions[i].answer) {
console.log("Correct!\n");
score++;
} else {
console.log(`Wrong! Correct answer: ${questions[i].answer}\n`);
}
}
let percentage = (score / questions.length) * 100;
console.log(`Final Score: ${score} out of ${questions.length}`);
console.log(`Percentage: ${percentage}%`);
if (percentage === 100) {
console.log("Perfect score! You're a JavaScript master!");
} else if (percentage >= 60) {
console.log("Well done! Keep practicing to reach 100%.");
} else {
console.log("Review the beginner lessons and try again.");
}