DOCODIVE
Beginner Free Learning Path

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.

3–4 weeks 20 lessons 3 projects 1 capstone No experience required
Start Learning
01

What 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.

javascript
console.log("Hello from JavaScript!");
console.log() is a built-in function that prints anything inside the parentheses to the console. The text "Hello from JavaScript!" is a string (a piece of text wrapped in quotes). The semicolon at the end marks the end of the statement.
console
Hello from JavaScript!
The console printed exactly the text we passed to console.log(). The quotes are not printed — they only tell JavaScript that this is a text value.
02

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.

javascript
// Inside an HTML file:
<script>
  console.log("Ready to code!");
</script>
The opening <script> tag tells the browser that JavaScript is starting. The console.log() line is the actual code. The closing </script> tag tells the browser the JavaScript section is done. The // lines are comments that JavaScript ignores — they are notes for humans.
console
Ready to code!
When the browser reads the script tag, it executes the console.log() statement and prints the text in the console. Comments produce no output because they are only notes.
03

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.

javascript
let name = "Ali";
const PI = 3.14;
var age = 25;
console.log(name, PI, age);
Line 1 creates a changeable variable 'name' with the value "Ali". Line 2 creates a constant 'PI' with the value 3.14 — this cannot be reassigned. Line 3 uses the old 'var' keyword to create 'age' with value 25. Line 4 prints all three values in one go, separated by spaces.
console
Ali 3.14 25
console.log() printed the three values in the same order they were passed, with spaces between them. The variable names (name, PI, age) are not printed — only their stored values.
04

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.

javascript
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);
Each let creates a value of a different type. 'und' is declared but not assigned, so it is undefined. The typeof operator returns the type of each value as a string. console.log() then prints all those type strings together.
console
string number boolean object undefined
str is a string, num is a number, bool is a boolean, nul is null (which typeof reports as 'object' — a famous JavaScript quirk), and und is undefined. These type names are printed in order.
05

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.

javascript
let a = 10;
let b = 3;
console.log(a + b, a - b, a * b, a / b, a % b, a === 10, a > b);
a + b adds (13), a - b subtracts (7), a * b multiplies (30), a / b divides (3.3333...), a % b gives remainder (1, because 10 divided by 3 leaves remainder 1). a === 10 checks equality (true), and a > b checks if 10 is greater than 3 (true).
console
13 7 30 3.3333333333333335 1 true true
Each expression is evaluated left to right and printed with spaces. Division of 10 by 3 gives a long decimal because JavaScript uses floating-point math. The modulo result is 1, and both comparisons return true.
06

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.

javascript
let name = "Ali";
let age = 25;
console.log(`My name is ${name} and I am ${age} years old.`);
Two variables are created. Inside the backtick string, ${name} is replaced with the value of the 'name' variable, and ${age} is replaced with the value of 'age'. The rest of the text stays as written.
console
My name is Ali and I am 25 years old.
The template literal inserted the variable values into the text exactly where ${} appeared. This is why we see 'Ali' and '25' in the final sentence instead of ${name} and ${age}.
07

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.

javascript
console.log(Math.round(4.7), Math.ceil(4.2), Math.floor(4.9), Math.max(1, 5, 9), Math.random());
Math.round(4.7) rounds 4.7 to 5. Math.ceil(4.2) rounds 4.2 up to 5. Math.floor(4.9) rounds 4.9 down to 4. Math.max(1, 5, 9) returns 9, the largest. Math.random() returns a random value like 0.73.
console
5 5 4 9 0.7315482394018274
The first four numbers are deterministic — they will always be 5, 5, 4, and 9. The last value from Math.random() changes every time you run the code, so you will see a different random decimal each time.
08

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.

javascript
let score = 85;
if (score >= 90) {
  console.log("A");
} else if (score >= 70) {
  console.log("B");
} else {
  console.log("C");
}
score is set to 85. The first if checks if 85 >= 90 — false, so it is skipped. The else if checks if 85 >= 70 — true, so "B" is printed. Because a match was found, the final else block is skipped.
console
B
Only the else if branch printed because 85 is not high enough for an A (needs 90+) but is high enough for a B (needs 70+). JavaScript runs only the first matching block.
09

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.

javascript
for (let i = 1; i <= 5; i++) {
  console.log(i);
}
The for loop has three parts: let i = 1 starts the counter at 1; i <= 5 keeps the loop running while i is 5 or less; i++ increases i by 1 after each iteration. Inside, console.log(i) prints the current value of i each time.
console
1 2 3 4 5
The loop ran five times. Each time it printed the current value of i (1, then 2, then 3, then 4, then 5), each on its own line because console.log() adds a new line after every call.
10

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.

javascript
function greet(name) {
  return "Hello " + name;
}
const greet2 = (name) => "Hi " + name;
console.log(greet("Ali"), greet2("Sara"));
The greet function is a declaration that takes 'name' and returns "Hello " plus the name. greet2 is an arrow function that returns "Hi " plus the name in one short line. Both are called in console.log() with different names.
console
Hello Ali Hi Sara
greet("Ali") returned "Hello Ali", and greet2("Sara") returned "Hi Sara". Both values were printed together, separated by a space. This shows the two function styles produce the same kind of result.
11

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.

javascript
function add(a, b) {
  return a + b;
}
console.log(add(5, 3));
The add function declares two parameters, a and b. When add(5, 3) is called, a becomes 5 and b becomes 3. The return statement sends back a + b, which is 8. That returned value is passed to console.log() and printed.
console
8
The function added its two inputs (5 and 3) and returned 8. console.log() then printed that returned value. The function does not print anything itself — it only returns the result.
12

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.

javascript
let fruits = ["apple", "banana", "mango"];
console.log(fruits.length, fruits[0], fruits[2]);
The array fruits holds three strings. fruits.length returns 3 because there are three items. fruits[0] accesses the first item (index 0) which is "apple". fruits[2] accesses the third item (index 2) which is "mango".
console
3 apple mango
The length is 3. Index 0 gives "apple" and index 2 gives "mango". Remember that arrays count from 0, so the last item is always at length - 1.
13

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.

javascript
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);
nums starts as [1,2,3]. push(4) adds 4, making [1,2,3,4]. pop() removes that 4, returning to [1,2,3]. map(n => n * 2) creates [2,4,6] by doubling each item. filter(n => n % 2 === 0) keeps only even numbers, giving [2].
console
[1, 2, 3] [2, 4, 6] [2]
After push and pop, nums is back to [1,2,3]. doubled is a new array with each original value multiplied by 2. even contains only 2 because it is the only even number in the original list.
14

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.

javascript
let person = { name: "Ali", age: 25, isStudent: true };
console.log(person.name, person.age);
The person object has three properties: name, age, and isStudent. person.name accesses the name property using dot notation and returns "Ali". person.age accesses the age property and returns 25.
console
Ali 25
Dot notation (person.name) pulled the value stored under the 'name' key. Only the two properties we accessed were printed — the isStudent property was not printed because it was not requested.
15

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.

javascript
let car = { brand: "Toyota", "model year": 2020 };
console.log(car.brand, car["model year"]);
The car object has two keys: 'brand' and 'model year'. car.brand uses dot notation because the key is a simple word. car["model year"] uses bracket notation because the key contains a space, which dot notation cannot handle.
console
Toyota 2020
Both access styles returned their values. Dot notation worked for 'brand', while bracket notation was required for 'model year' because a space in a key name makes dot notation invalid.
16

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 {}.

javascript
let global = "global";
function test() {
  let local = "local";
  console.log(local);
}
test();
console.log(global);
'global' is declared outside any function, so it is in global scope. 'local' is declared inside the test() function, so it only exists there. test() prints 'local' from inside, then the outer console.log() prints 'global' from outside.
console
local global
First, test() ran and printed 'local' because the variable exists inside the function. Then the last line printed 'global' because it was declared in global scope. If we tried to print 'local' outside the function, it would cause an error.
17

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.

javascript
console.log(x);
var x = 10;
console.log(x);
The first console.log(x) runs before x is assigned. Because var is hoisted, x exists but is undefined at that moment. Then var x = 10 assigns the value. The second console.log(x) now prints 10.
console
undefined 10
The first line printed undefined because hoisting moved the declaration 'var x' to the top, but the assignment (= 10) stayed where it was. After the assignment line, x holds 10, so the second print shows 10.
18

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.

javascript
let a;
let b = null;
let c = "abc" / 2;
console.log(a, b, c, typeof a, typeof b, Number.isNaN(c));
'a' is declared but not assigned, so it is undefined. 'b' is explicitly set to null. 'c' tries to divide text by 2, producing NaN. typeof shows the types, and Number.isNaN(c) checks if c is NaN (true).
console
undefined null NaN undefined object true
a is undefined, b is null (typeof says 'object' due to a JavaScript quirk), and c is NaN. typeof a is undefined, typeof b is object, and Number.isNaN(c) correctly returns true for the invalid math result.
19

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.

javascript
console.log(5 == "5", 5 === "5", 0 == false, 0 === false);
5 == "5" uses loose equality, so the string is converted to a number and they match (true). 5 === "5" uses strict equality, so the number and string are different types (false). 0 == false converts false to 0 (true). 0 === false compares number vs boolean (false).
console
true false true false
Loose equality (==) returned true in both cases because it converted types to match. Strict equality (===) returned false in both cases because the types were different (number vs string, number vs boolean).
20

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.

javascript
function celsiusToFahrenheit(c) {
  return (c * 9/5) + 32;
}
console.log(celsiusToFahrenheit(0), celsiusToFahrenheit(100));
The celsiusToFahrenheit function takes a Celsius value and returns the Fahrenheit equivalent using the formula (c × 9/5) + 32. It is called twice, once with 0 and once with 100, and both results are printed.
console
32 212
0°C converts to 32°F (the freezing point of water), and 100°C converts to 212°F (the boiling point). Both returned values are printed in order. This is the Temperature Converter mini project in action.

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
Math.random() parseInt() while loop if / else prompt()
Step-by-step: How it works
  1. Math.random() generates a decimal between 0 and 1.
  2. Multiply by 100 and round up to get a secret number from 1 to 100.
  3. The loop runs while you still have attempts left.
  4. Each turn you type a guess using prompt().
  5. The program says "too low" or "too high" and shows remaining attempts.
  6. If you guess correctly, the loop breaks and you win.
  7. When attempts reach 0, the game ends and reveals the secret number.
javascript
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 + ".");
}
Sample Run
console
Number Guessing Game Guess the secret number between 1 and 100. You have 7 attempts. Attempt 1: 50 Too high. 6 attempt(s) left. Attempt 2: 25 Too low. 5 attempt(s) left. Attempt 3: 37 Correct! The secret number is 37. You found it in 3 attempt(s).

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
functions parameters & return parseFloat() if / else template literals
Step-by-step: How it works
  1. The user picks a conversion direction: C to F or F to C.
  2. The user enters a temperature value.
  3. parseFloat() converts the input text to a number.
  4. The correct formula runs based on the chosen direction.
  5. The result is printed using a template literal with two decimal places.
javascript
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.");
}
Sample Run
console
Temperature Converter Convert (1) C to F or (2) F to C: 1 Enter temperature: 0 0°C = 32.00°F

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
arrays push() splice() while loop switch
Step-by-step: How it works
  1. todos is an empty array that stores tasks.
  2. A while (true) loop shows the menu and reads the choice.
  3. Choice 1 adds a task using push().
  4. Choice 2 lists all tasks with their index numbers.
  5. Choice 3 removes a task using splice().
  6. Choice 4 breaks the loop and exits.
javascript
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");
    }
}
Sample Run
console
Simple To-Do List 1. Add task 2. View tasks 3. Remove task 4. Exit Choose an option: 1 Enter task: Learn JavaScript "Learn JavaScript" added! 1. Add task 2. View tasks 3. Remove task 4. Exit Choose an option: 2 Your tasks: 1. Learn JavaScript

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
array of objects functions for loop if / else score tracking
Step-by-step: How it works
  1. questions is an array of objects — each object holds a question, options, and correct answer.
  2. A for loop goes through each question one by one.
  3. The user picks an answer using prompt().
  4. If the answer matches, score increases by 1.
  5. After all questions, the score is converted to a percentage.
  6. A final message shows the score and percentage.
javascript
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.");
}
Sample Run
console
Interactive Quiz App Question 1: Which keyword declares a constant? 1) let 2) const 3) var Your answer (1, 2, or 3): 2 Correct! Question 2: What does console.log() do? 1) Reads input 2) Prints output 3) Runs a loop Your answer (1, 2, or 3): 2 Correct! ... Final Score: 5 out of 5 Percentage: 100% Perfect score! You're a JavaScript master!
You've completed all 20 lessons. Ready to continue?

Level up with JavaScript Intermediate, Advanced, and Practice resources.

📱 Scan this QR code with your phone camera to instantly open this page.

Works on iOS, Android, and any modern device. No app installation required.

Account Verified!

Your email has been verified successfully.