React

JavaScript Fundamentals Tutorial for Beginners

A JavaScript fundamentals tutorial for beginners: ten steps from variables to async code, with tested examples and a small browser page you build at the end.

hello.js1const name = 'Ravi';2function greet(person) {3 return `Hello, ${person}!`;4}5console.log(greet(name));
  • JavaScript
  • Tutorial
  • Beginners

Quick answer: To learn JavaScript from zero, follow ten steps: set up your tools, then learn variables and types, operators, conditions, loops, functions, arrays, objects, the DOM and async code. Write and run a small program after each step. With one to two hours of daily practice, most beginners cover these fundamentals in about four to eight weeks.

This JavaScript fundamentals tutorial takes you from your first line of code to a small page that reacts to clicks. JavaScript is the language that runs in web browsers. With Node.js, it also runs on servers, so one language can take you a long way.

The tutorial has ten steps. Each one has an idea, code, the real output and a short task. Type the code yourself. Typing shows you the small errors that reading hides.

Before you start: how to learn JavaScript fundamentals

To learn JavaScript fundamentals well, use the same loop for every step:

  1. Read the idea.
  2. Guess the output before you run the code.
  3. Run it and compare.
  4. Change one thing and guess again.

If your guess was wrong, good. You have found exactly what to study. Our learning time guide has a week-by-week plan.

Note: This JavaScript fundamentals for beginners guide uses no libraries. Every example works in plain JavaScript.

Steps 1 to 3: Setup, variables and operators

Step 1: Set up and run your first program

Install Node.js (choose the LTS version) and VS Code. Make a file called hello.js:

console.log("Hello, JavaScript!"); // Hello, JavaScript!

Open the terminal in that folder and type node hello.js. The text after // is a comment. JavaScript ignores it, and in this tutorial it shows the output.

You can also press F12 in a browser, open the Console tab and type the line there.

Step 2: Store values in variables

A variable is a name for a value. Use const when the name will always point to the same value. Use let when you need to change it.

const college = "JNTU";
let marks = 72;
marks = 80;
const passed = true;

console.log(college, marks, passed); // JNTU 80 true
console.log(typeof college);         // string
console.log(typeof marks);           // number
console.log(typeof passed);          // boolean

The common types are string (text), number and boolean (true or false). undefined means "no value yet", and null means "empty on purpose".

Try it: Store your name, branch and year. Print all three on one line.

Step 3: Calculate and compare

const price = 400;
const quantity = 3;
const total = price * quantity;

console.log(total);            // 1200
console.log(17 % 5);           // 2
console.log(total > 1000);     // true
console.log("5" === 5);        // false
console.log(`Total: ₹${total}`); // Total: ₹1200

% gives the remainder. === checks that two values are the same and have the same type. Text in backticks can hold a variable inside ${}.

Try it: Use % to check whether a number is even. An even number has the remainder 0 when you divide by 2.

Common mistake: Using = to compare. One = stores a value. Three === compare two values. Our list of beginner mistakes has more traps like this.

Steps 4 and 5: Conditions and loops

Step 4: Make decisions with if

const score = 68;
let grade;

if (score >= 75) {
  grade = "Distinction";
} else if (score >= 60) {
  grade = "First class";
} else if (score >= 40) {
  grade = "Pass";
} else {
  grade = "Fail";
}
console.log(grade); // First class

JavaScript checks from top to bottom and stops at the first true condition. So the order matters. If you tested score >= 40 first, a score of 90 would print "Pass".

Join conditions with && (both must be true) and || (at least one must be true).

Try it: Print "Eligible" only when attendance is at least 75 and the fee is paid.

Step 5: Repeat work with loops

let sum = 0;
for (let i = 1; i <= 5; i++) {
  sum = sum + i;
}
console.log(sum); // 15

for (const subject of ["Maths", "Physics"]) {
  console.log(subject);
}
15
Maths
Physics

The for loop has three parts: where to start, when to continue and what to change each time. for...of is simpler when you need each item in a list.

Use while when you do not know the number of rounds in advance. Make sure something inside it changes, or the loop will never stop.

Try it: Print the multiplication table of 7.

Steps 6 to 8: Functions, arrays and objects

Step 6: Write functions

A function is a named block of code. It takes inputs, does one job and returns a result.

function simpleInterest(principal, rate, years) {
  return (principal * rate * years) / 100;
}
const square = (n) => n * n;

console.log(simpleInterest(10000, 8, 2)); // 1600
console.log(square(9));                   // 81

The second form is an arrow function. With no braces, it returns its result automatically. Inside braces, you must write return.

A function can remember variables from the place where it was made. This is called a closure:

function makeCounter() {
  let count = 0;
  return () => {
    count = count + 1;
    return count;
  };
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2

Nothing outside can change count directly, so the value is protected.

Try it: Write a function that returns the larger of two numbers.

Step 7: Work with lists using arrays

An array holds items in order. The first index is 0.

const marks = [45, 82, 67, 91, 38];

console.log(marks[0]);                    // 45
console.log(marks.length);                // 5
console.log(marks.filter((m) => m >= 60)); // [ 82, 67, 91 ]
console.log(marks.map((m) => m + 5));     // [ 50, 87, 72, 96, 43 ]
console.log(marks.reduce((a, b) => a + b, 0)); // 323
  • filter keeps the items that pass a test.
  • map changes every item and gives a new array.
  • reduce combines all items into one value.

None of these three changes the original array here. Methods such as push, splice and sort do.

Try it: Find the average of marks. Divide the total by the length.

Step 8: Describe things with objects

An object groups related values under names called keys.

const student = {
  name: "Divya",
  branch: "ECE",
  skills: ["HTML", "CSS"],
};
student.skills.push("JavaScript");
student.year = 3;

const { name, skills } = student;
console.log(name);             // Divya
console.log(skills.length);    // 3
console.log(student.city);     // undefined
console.log(student.address?.pin); // undefined

Taking values out with braces is called destructuring. The ?. operator avoids an error when address does not exist.

Real programs often use an array of objects, so practise that shape:

const students = [
  { name: "Divya", marks: 88 },
  { name: "Kiran", marks: 54 },
];
const top = students.filter((s) => s.marks > 60).map((s) => s.name);
console.log(top); // [ 'Divya' ]

Pro tip: Read chained methods from left to right. First keep students above 60, then take only their names.

Step 9: Change a web page with the DOM

The browser turns your HTML into a tree of objects called the DOM. JavaScript finds an element, waits for an event and then changes the page. Save this as index.html and open it in a browser:

<!doctype html>
<html lang="en">
  <body>
    <label for="amount">Bill amount</label>
    <input id="amount" type="number" min="0" />
    <button id="add">Add 18% tax</button>
    <p id="result"></p>

    <script>
      const input = document.querySelector("#amount");
      const button = document.querySelector("#add");
      const result = document.querySelector("#result");

      button.addEventListener("click", () => {
        const amount = Number(input.value);
        if (input.value === "" || amount < 0) {
          result.textContent = "Enter a valid amount.";
          return;
        }
        result.textContent = `Total: ₹${(amount * 1.18).toFixed(2)}`;
      });
    </script>
  </body>
</html>

Enter 100 and click the button. You should see Total: ₹118.00.

Notice three things. The input value is text, so Number() converts it. The code checks bad input before it calculates. And textContent shows plain text, which is safe for anything a user types.

Try it: Add a second button that clears the input and the result.

Step 10: Wait for data with async code

Some work takes time, such as getting data from a server. JavaScript does not freeze while it waits. It uses a promise, an object for a result that will arrive later.

const wait = (ms) => new Promise((done) => setTimeout(done, ms));

async function loadResult() {
  console.log("Loading...");
  await wait(50);
  return { name: "Divya", marks: 88 };
}

loadResult().then((data) => console.log(data.name));
console.log("The page still works");
Loading...
The page still works
Divya

await pauses only loadResult. The last line runs while it waits. In a browser, you use the same idea with fetch:

// Browser code: use a real API address here
async function getUser(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) throw new Error(`Status ${response.status}`);
    return await response.json();
  } catch (error) {
    console.error("Could not load:", error.message);
    return null;
  }
}

fetch does not treat a 404 as a failure, so you must check response.ok. try...catch handles network errors and the error you throw.

Interview note: Be ready to explain the order of the three output lines above. The synchronous code finishes first, and the code after await runs later.

After this JavaScript fundamentals tutorial

Do not jump straight to React. Spend three weeks using what you have learned. React code is full of arrow functions, array methods, objects and async calls. If you still need to look these up, every React lesson will feel twice as hard.

Week Goal Done when
1 Solve 15 small problems You can solve most without notes
2 Build two mini projects Both work and are on GitHub
3 Revise and explain You can teach closures and promises to a friend

A good test is to rebuild the tax page from Step 9 with an empty file and no notes. Then add one feature, such as a choice of tax rates. If you can do that in an hour, you are ready to move on.

For more JavaScript fundamentals examples, work through our practice problems with solutions. Then choose one of the JavaScript project ideas. The JavaScript developer roadmap shows what comes next.

If you prefer a guided path, the full stack developer course guide explains a full syllabus. At CodeBegun, weekday classes run for about four hours in morning, afternoon or evening batches, in Madhapur, Hyderabad or live online.

Frequently asked questions

Can I learn JavaScript without any coding background?

Yes. JavaScript needs no earlier language. You need a computer, a browser and regular practice. Start with values and variables, and do not move on until you can write each small example without copying.

Do I need to learn HTML and CSS before JavaScript?

Basic HTML and CSS help a lot, because JavaScript in the browser changes a page made from them. You can learn the language first with Node.js, then spend a few days on HTML and CSS before the DOM.

How long does it take to learn JavaScript fundamentals?

Most beginners need about four to eight weeks with one to two hours of practice a day. The time depends on how much code you write yourself. Watching videos without coding takes longer to turn into skill.

Which software do I need to practise JavaScript?

A browser and a code editor such as VS Code are enough for web pages. Install the current LTS version of Node.js to run files in a terminal. All three are free to use.

What should I learn after JavaScript fundamentals?

Build two or three small projects first. Then learn Git, more about working with APIs, and React for the frontend. After that, Node.js and Express let you use the same language on the server.


Want someone to check your code as you learn? Book a free demo class for the Full Stack Web Development programme. Batches are capped at 27, so you can ask questions and get your code reviewed.

Found this useful? Share it: LinkedIn Facebook WhatsApp

Written by

Siva Prasad Galaba

Staff Engineer & Founder, CodeBegun

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaching the next generation to code the way the industry actually works.

Back to all articles
Chat with us