JavaScript – Basics, Programming, and Practical Examples

Imagine a web page where a button responds to a click, a menu opens when a user taps it, a form validates entered data, and content changes without reloading the page. All of this, and much more, is possible thanks to JavaScript.

JavaScript is a programming language that brings interactivity to web pages and enables them to respond to user actions. While HTML defines the structure of content and CSS controls its appearance, JavaScript makes page elements dynamic and functional.

Today, JavaScript extends far beyond simple web page effects. It is used to build complex frontend applications, server-side systems, API services, mobile and desktop applications, and even various automation tools.

In this guide, you will learn JavaScript from the ground up through clear explanations and practical code examples. You will discover how to declare variables, work with different data types, write conditions and loops, create functions, and handle events. Special attention will be given to connecting JavaScript with HTML documents, because that is where practical frontend development truly begins.

Whether you are just starting your programming journey or already have experience with HTML and CSS, this guide will help you understand how JavaScript works and how to apply it in your own projects.

What Is JavaScript and What Is It Used For?

JavaScript is a programming language that enables the execution of instructions, data processing, and control over application behavior. In web development, it is most commonly used to add interactivity to HTML pages and communicate with other services.

Unlike HTML, which describes the structure of content, and CSS, which defines its visual presentation, JavaScript allows something to happen in response to a specific action or event.

For example, JavaScript can:

  1. Respond when a user clicks a button.
  2. Open or close a navigation menu.
  3. Show or hide specific content.
  4. Validate whether a user has filled out a form correctly.
  5. Calculate a product price based on entered data.
  6. Filter and sort products in an online store.
  7. Load data from a server without reloading the entire page.
  8. Create dynamic galleries, cards, and interactive components.

Let's look at a simple example:

HTML

 

 

<button id="button">Click Here</button>

 

<p id="message">Waiting for your action.</p>

 

<script>

const button = document.querySelector("#button");

const message = document.querySelector("#message");

 

button.addEventListener("click", function() {

message.textContent = "You have successfully triggered JavaScript!";

});

</script>

 

When the user clicks the button, JavaScript detects the event and changes the text inside the paragraph. There is no need to reload the page.

This is one of JavaScript's key advantages: it transforms a web page from a static collection of information into an interactive environment that can respond to user needs and actions.

Ask Copilot

 

 

How Is JavaScript Connected to an HTML Document?

For JavaScript to interact with and control elements on a web page, it must be connected to the HTML document. There are two primary approaches: using an external JavaScript file or writing JavaScript directly inside the HTML document.

1. External JavaScript – Linking a Separate File

In larger projects, it is recommended to keep JavaScript code in separate .js files.

For example, create a file named script.js and connect it to your HTML document:

Error: CdnAliasUnresolved - Unresolved CDN references: 1

HTML

 

 

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

 

<title>JavaScript Example</title>

 

<script src="script.js" defer></script>

</head>

<body>

 

<h1>My First JavaScript Page</h1>

 

<button id="button">Click</button>

 

</body>

</html>

 

Console

 

 

Current preview

CdnAliasUnresolved - Unresolved CDN references: 1

Console content may be incorrect

Contents of the script.js file:

JavaScript

 

 

const button = document.querySelector("#button");

 

button.addEventListener("click", function() {

alert("JavaScript is working!");

});

The defer attribute tells the browser to download the JavaScript file immediately but delay its execution until the HTML document has been fully parsed. This is a practical and commonly recommended way to include scripts that interact with page elements.

2. Internal JavaScript – Code Inside the HTML Document

JavaScript can also be written directly within the HTML document using the <script> element.

HTML

 

 

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Internal JavaScript</title>

</head>

<body>

 

<h1>JavaScript Example</h1>

 

<script>

console.log("JavaScript has started!");

</script>

 

</body>

</html>

 

This approach is useful for small examples, demonstrations, and quick testing. However, for larger projects, using separate JavaScript files usually results in cleaner, more organized, and easier-to-maintain code.

JavaScript Variables – let, const, and var

Variables are used to store data that a program works with during execution. In JavaScript, variables can be declared using the keywords let, const, and var.

In modern JavaScript development, let and const are preferred, while var is mostly encountered in older codebases and certain legacy scenarios.

Declaring Variables with let

The let keyword is used when a variable's value may change during program execution.

JavaScript

 

 

let name = "Mark";

 

console.log(name);

 

name = "Peter";

 

console.log(name);

The first output displays Mark, while the second displays Peter, because the variable's value was reassigned.

Declaring Variables with const

The const keyword is used when you do not plan to reassign the variable to a different value.

JavaScript

 

 

const year = 2026;

 

console.log(year);

Attempting to assign a new value to the same const variable will result in an error.

It is important to understand that const prevents reassignment of the variable itself, but it does not guarantee that the contents of an object or array cannot be modified.

JavaScript

 

 

const user = {

name: "Mark",

age: 30

};

 

user.age = 31;

 

console.log(user.age);

This example is valid because we are modifying a property of the object rather than assigning a completely new value to the user variable.

What About var?

var is the older way of declaring variables:

JavaScript

 

 

var message = "Welcome!";

 

console.log(message);

Although var still works, it behaves differently in terms of scope and can lead to unexpected behavior in larger applications.

For example:

JavaScript

 

 

if (true) {

var city = "London";

}

 

console.log(city);

The variable remains accessible outside the block.

With let:

JavaScript

 

 

if (true) {

let city = "London";

}

 

console.log(city);

This code produces an error because let is limited to the block in which it was declared.

When Should You Use Each One?

A common modern approach is:

  • Use const by default.
  • Use let when the value needs to change.
  • Avoid var in new projects unless you are maintaining older code.

Following this approach makes JavaScript code more predictable, easier to understand, and less prone to bugs.

JavaScript Data Types – Strings, Numbers, Booleans, and Objects

JavaScript can work with many different types of data. Understanding data types is important because they determine how the program stores values and performs operations.

The most common primitive data types are:

  1. String – textual values.
  2. Number – numeric values, including integers and decimal numbers.
  3. Boolean – logical values true and false.
  4. Undefined – a variable that has been declared but not assigned a value.
  5. Null – an intentional absence of a value.
  6. BigInt – integer values that are too large for the standard Number type.
  7. Symbol – unique values commonly used as property identifiers.

JavaScript also supports more complex data structures such as objects and arrays.

String – Text Data

JavaScript

 

 

const name = "Aleksandar";

const city = "Belgrade";

 

console.log("Hello, " + name + "!");

To combine text and variables more conveniently, JavaScript provides template literals, which use backticks:

JavaScript

 

 

const name = "Aleksandar";

const age = 35;

 

const message = `Hello, ${name}! You are ${age} years old.`;

 

console.log(message);

This approach is especially useful when multiple variables need to be included within a string.

Number – Numeric Values

JavaScript

 

 

const price = 2500;

const quantity = 3;

 

const total = price * quantity;

 

console.log(total);

The result is 7500 because JavaScript multiplies the price by the quantity.

Boolean – Logical Values

JavaScript

 

 

const isUserLoggedIn = true;

 

if (isUserLoggedIn) {

console.log("Welcome to your account!");

}

Boolean values are used to evaluate conditions and control program flow.

Undefined and Null

JavaScript

 

 

let result;

 

console.log(result); // undefined

 

const activeUser = null;

 

console.log(activeUser); // null

undefined typically indicates that a value has not yet been defined, while null is used when we intentionally want to represent the absence of a value.

Objects

Objects are used to store related data as key-value pairs.

JavaScript

 

 

const user = {

name: "Aleksandar",

age: 35,

city: "Belgrade"

};

 

console.log(user.name);

console.log(user.age);

Objects are one of the most important data structures in JavaScript and are widely used for representing users, products, settings, and application data.

Arrays

Arrays are used to store multiple values in a single variable.

JavaScript

 

 

const technologies = ["HTML", "CSS", "JavaScript"];

 

console.log(technologies[0]);

console.log(technologies[2]);

Output:

Plain Text

 

 

HTML

JavaScript

Arrays are commonly used for lists of products, articles, users, categories, and many other collections of data.

Checking Data Types

You can determine the type of a value using the typeof operator:

JavaScript

 

 

console.log(typeof "Hello"); // string

console.log(typeof 42); // number

console.log(typeof true); // boolean

console.log(typeof undefined); // undefined

console.log(typeof {}); // object

Understanding data types is essential because variables, conditions, functions, objects, arrays, and nearly every other part of JavaScript rely on them. Choosing the appropriate data type makes code easier to understand, maintain, and debug.

JavaScript Operators – Calculations, Comparisons, and Logical Conditions

Operators allow you to perform various operations on data. They are used for calculations, comparing values, evaluating conditions, and combining logical expressions.

Arithmetic Operators

The most common arithmetic operators are:

OperatorMeaningExample
+Addition10 + 5
-Subtraction10 - 5
*Multiplication10 * 5
/Division10 / 5
%Remainder (modulus)10 % 3
**Exponentiation2 ** 3

Practical example:

JavaScript

 

 

const price = 1500;

const discount = 200;

 

const finalPrice = price - discount;

 

console.log(finalPrice);

Comparison Operators

Comparison operators are used to compare values. The result of a comparison is always either true or false.

JavaScript

 

 

const age = 20;

 

console.log(age > 18); // true

console.log(age < 18); // false

console.log(age === 20); // true

console.log(age !== 20); // false

It is especially important to understand the difference between == and ===.

The == operator compares values and may perform automatic type conversion, whereas === compares both the value and the data type. In most cases, it is recommended to use strict equality (===) and strict inequality (!==).

Example:

JavaScript

 

 

console.log(5 == "5"); // true

console.log(5 === "5"); // false

 

In the first case, JavaScript converts the string "5" into a number. In the second case, the comparison fails because the data types are different.

Logical Operators

Logical operators allow you to combine multiple conditions:

  1. && – logical AND.
  2. || – logical OR.
  3. ! – logical NOT.

Example:

JavaScript

 

 

const age = 25;

const hasAccount = true;

 

if (age >= 18 && hasAccount) {

console.log("The user meets the requirements.");

}

The condition is fulfilled only if both checks are true.

Example using OR:

JavaScript

 

 

const isAdmin = false;

const isModerator = true;

 

if (isAdmin || isModerator) {

console.log("Access granted.");

}

 

The condition is fulfilled if at least one of the expressions is true.

Example using NOT:

JavaScript

 

 

const isLoggedIn = false;

 

if (!isLoggedIn) {

console.log("Please log in.");

}

The ! operator reverses a Boolean value, turning true into false and false into true.

Assignment Operators

Assignment operators are used to assign or update variable values.

JavaScript

 

 

let score = 10;

 

score += 5; // score = score + 5

score -= 2; // score = score - 2

score *= 3; // score = score * 3

 

console.log(score);

Common assignment operators include:

OperatorExampleEquivalent
=x = 5Assign value
+=x += 2x = x + 2
-=x -= 2x = x - 2
*=x *= 2x = x * 2
/=x /= 2x = x / 2

Understanding operators is essential because they are used throughout JavaScript for calculations, decision-making, validation, loops, functions, and virtually every type of application logic.

JavaScript Conditions – if, else, and switch

Programs often need to make decisions based on specific data. For example, they may need to check whether a user is logged in, whether a product is available, or whether a customer qualifies for a discount.

For these situations, JavaScript provides conditional statements.

if and else

The simplest way to evaluate a condition is with an if statement.

JavaScript

 

 

const age = 22;

 

if (age >= 18) {

console.log("Adult.");

} else {

console.log("Minor.");

}

If the condition is true, the first block of code is executed. Otherwise, the code inside the else block runs.

else if – Multiple Conditions

When there are several possible outcomes, you can use else if.

JavaScript

 

 

const grade = 4;

 

if (grade === 5) {

console.log("Excellent");

} else if (grade === 4) {

console.log("Very Good");

} else if (grade === 3) {

console.log("Good");

} else if (grade === 2) {

console.log("Satisfactory");

} else {

console.log("Unsatisfactory");

}

Each condition is checked in order until one of them evaluates to true.

switch – Selecting Between Multiple Values

When you need to compare a single variable against several specific values, a switch statement can make the code more organized and easier to read.

JavaScript

 

 

const day = 3;

 

switch (day) {

case 1:

console.log("Monday");

break;

 

case 2:

console.log("Tuesday");

break;

 

case 3:

console.log("Wednesday");

break;

 

default:

console.log("Unknown day");

}

The break statement stops execution of the current case and prevents the program from continuing into the following cases.

The default block runs when none of the defined cases match the value being tested.

Ternary Operator – A Short Form of if

For simple conditions, JavaScript also provides the ternary operator.

Instead of:

JavaScript

 

 

let message;

 

if (age >= 18) {

message = "Adult";

} else {

message = "Minor";

}

You can write:

JavaScript

 

 

const message = age >= 18 ? "Adult" : "Minor";

 

console.log(message);

The ternary operator is useful for short conditions and assignments, but for more complex logic, if and else statements are usually easier to read and maintain.

Conditional statements are a fundamental part of JavaScript because they allow programs to make decisions, respond to user actions, validate data, and control how an application behaves in different situations.

JavaScript Loops – for, while, and Repeating Instructions

Loops allow a section of code to be executed multiple times without having to write the same instruction repeatedly.

For example, if we want to display the numbers from 1 to 10, we can use a loop instead of writing ten separate statements.

for Loop

JavaScript

 

 

for (let i = 1; i <= 10; i++) {

console.log(i);

}

This loop consists of three main parts:

  1. The initial value of the variable i.
  2. A condition that determines how long the loop will run.
  3. An update to the variable after each iteration.

In this example, the loop starts at 1, continues while i is less than or equal to 10, and increases i by one after each iteration.

while Loop

The while loop executes code as long as a specified condition remains true.

JavaScript

 

 

let number = 1;

 

while (number <= 5) {

console.log(number);

number++;

}

This loop prints the numbers from 1 to 5.

It is important to update the variable used in the condition. Otherwise, the condition may never become false, resulting in an infinite loop.

for...of Loop

The for...of loop is commonly used to iterate through the values of an array.

JavaScript

 

 

const technologies = ["HTML", "CSS", "JavaScript"];

 

for (const technology of technologies) {

console.log(technology);

}

Output:

Plain Text

 

 

HTML

CSS

JavaScript

This approach is simple and readable when you need the value of each array element rather than its index.

forEach() Method

Another common way to process arrays is with the forEach() method.

JavaScript

 

 

const technologies = ["HTML", "CSS", "JavaScript"];

 

technologies.forEach(function(technology) {

console.log(technology);

});

With modern JavaScript, you will often see an arrow function used:

JavaScript

 

 

technologies.forEach(technology => {

console.log(technology);

});

Breaking Out of a Loop

The break statement immediately stops a loop.

JavaScript

 

 

for (let i = 1; i <= 10; i++) {

if (i === 5) {

break;

}

 

console.log(i);

}

Output:

Plain Text

 

 

1

2

3

4

Skipping an Iteration

The continue statement skips the current iteration and moves to the next one.

JavaScript

 

 

for (let i = 1; i <= 5; i++) {

if (i === 3) {

continue;

}

 

console.log(i);

}

Output:

Plain Text

 

 

1

2

4

5

The value 3 is skipped because the loop continues directly to the next iteration.

Practical Example

Displaying a list of products:

JavaScript

 

 

const products = [

"Laptop",

"Monitor",

"Keyboard",

"Mouse"

];

 

for (const product of products) {

console.log(product);

}

Loops are especially useful for processing large amounts of data, displaying products, filtering records, generating HTML elements dynamically, and automating repetitive tasks within applications.

JavaScript Functions – Organizing and Reusing Code

Functions are one of the most important parts of JavaScript. They allow you to group a specific section of a program into a reusable unit that can be called whenever needed.

Instead of repeating the same logic in multiple places, you can place it inside a function and reuse it throughout your code.

Example of a simple function:

JavaScript

 

 

function welcome() {

console.log("Welcome!");

}

 

welcome();

A function is defined using the function keyword, followed by the function name and the block of code that will be executed.

Functions with Parameters

Functions can receive data through parameters.

JavaScript

 

 

function greet(user) {

console.log(`Hello, ${user}!`);

}

 

greet("Mark");

greet("Jelena");

The same function can be reused with different values.

Functions That Return a Value

When you want a function to calculate something and return the result to the program, use the return statement.

JavaScript

 

 

function add(a, b) {

return a + b;

}

 

const result = add(10, 20);

 

console.log(result);

Arrow Functions

Modern JavaScript also supports a shorter way of writing functions using the => syntax.

JavaScript

 

 

const multiply = (a, b) => {

return a * b;

};

 

console.log(multiply(5, 4));

For simple functions that return a single expression, an even shorter syntax can be used:

JavaScript

 

 

const square = number => number * number;

 

console.log(square(6));

Functions help organize programs more effectively, reduce code duplication, and make applications easier to test and maintain.

JavaScript Arrays – Storing and Processing Multiple Values

Arrays are used to store multiple values within a single variable. They are commonly used to organize data such as product lists, users, categories, orders, or search results.

Example of an array:

JavaScript

 

 

const colors = ["red", "green", "blue"];

 

console.log(colors);

Each element in an array has its own index. Indexing starts at zero:

JavaScript

 

 

console.log(colors[0]); // red

console.log(colors[1]); // green

console.log(colors[2]); // blue

Adding and Removing Elements

JavaScript provides several methods for working with arrays.

JavaScript

 

 

const products = ["Laptop", "Monitor"];

 

products.push("Keyboard");

 

console.log(products);

The push() method adds an element to the end of the array.

To remove the last element, use pop():

JavaScript

 

 

products.pop();

To add or remove elements at the beginning of an array, use unshift() and shift().

Iterating Through an Array with forEach()

JavaScript

 

 

const languages = ["JavaScript", "PHP", "Python"];

 

languages.forEach(function(language) {

console.log(language);

});

 

Filtering Data with filter()

JavaScript

 

 

const prices = [500, 1200, 800, 2500, 300];

 

const expensiveProducts = prices.filter(function(price) {

return price > 1000;

});

 

console.log(expensiveProducts);

The result is a new array containing only values greater than 1000.

Transforming Elements with map()

JavaScript

 

 

const prices = [100, 200, 300];

 

const pricesWithTax = prices.map(function(price) {

return price * 1.2;

});

 

console.log(pricesWithTax);

The map() method creates a new array based on the results of a function applied to each element.

Arrays are indispensable in everyday JavaScript programming, especially when working with data received from a server or displaying data on a web page.

JavaScript Objects – Organizing Related Data

Objects allow you to store multiple related pieces of data within a single structure. Unlike an array, whose elements are typically accessed using numeric indexes, object properties have their own names.

Example of a user object:

JavaScript

 

 

const user = {

firstName: "Marko",

lastName: "Petrović",

age: 30,

city: "Belgrade"

};

Values can be accessed using either dot notation or bracket notation:

JavaScript

 

 

console.log(user.firstName);

 

console.log(user["city"]);

Object properties can be modified and new ones can be added:

JavaScript

 

 

user.age = 31;

 

user.email = "marko@example.com";

 

console.log(user);

Objects can also contain functions, which are referred to as methods in this context.

JavaScript

 

 

const product = {

name: "Laptop",

price: 85000,

 

displayInfo() {

console.log(`${this.name}: ${this.price} RSD`);

}

};

 

product.displayInfo();

 

In this example, the this keyword refers to the object in whose context the method is being executed.

Objects are extremely important in application development because they provide a structured way to represent real-world entities such as users, products, orders, articles, and other types of data.

JavaScript DOM – Manipulating HTML Elements

The DOM (Document Object Model) is the object representation of an HTML document. Based on the HTML content, the browser creates a structure whose elements can be accessed and manipulated by JavaScript.

Thanks to the DOM, JavaScript can find an HTML element, change its text, modify its CSS classes, add new content, or remove existing elements.

Finding HTML Elements

The most commonly used methods for finding elements are querySelector() and querySelectorAll().

HTML

 

 

<h1 id="title">Old Title</h1>

 

<p class="text">First paragraph</p>

<p class="text">Second paragraph</p>

 

JavaScript

 

 

const title = document.querySelector("#title");

 

const paragraphs = document.querySelectorAll(".text");

querySelector() returns the first element that matches the specified CSS selector, while querySelectorAll() returns a collection of all matching elements.

Changing Text and Content

JavaScript

 

 

const title = document.querySelector("#title");

 

title.textContent = "New Title";

This changes the text inside the HTML element.

When you need to insert HTML markup, you can use innerHTML, but it should be used with caution. Injecting untrusted user content through innerHTML can introduce security risks, including XSS attacks.

Changing CSS Classes

JavaScript

 

 

const card = document.querySelector(".card");

 

card.classList.add("active");

Other useful methods for working with classes include:

  1. classList.remove() – removes a class.
  2. classList.toggle() – adds a class if it does not exist, or removes it if it does.
  3. classList.contains() – checks whether an element has a specific class.

The DOM is one of the most important areas of frontend development because it connects JavaScript logic with the actual content of a web page.

JavaScript Events – Clicks, Text Input, and User Interactions

Events allow JavaScript to respond to various user actions or browser activities.

The most common events are:

  1. click – clicking an element.
  2. input – changing the value of an input field.
  3. change – changing the value of a specific form element.
  4. submit – submitting a form.
  5. keydown – pressing a key on the keyboard.
  6. mouseover – moving the mouse pointer over an element.
  7. load – fired when a resource or window has finished loading, depending on the target element.

Responding to a Click

HTML

 

 

<button id="button">Click</button>

<p id="result"></p>

 

JavaScript

 

 

const button = document.querySelector("#button");

const result = document.querySelector("#result");

 

button.addEventListener("click", function() {

result.textContent = "The button has been clicked!";

});

The addEventListener() method allows us to connect a specific event to a function that will execute when that event occurs.

Monitoring Text Input

HTML

 

 

<input type="text" id="name" placeholder="Enter your name">

 

<p id="output"></p>

 

JavaScript

 

 

const input = document.querySelector("#name");

const output = document.querySelector("#output");

 

input.addEventListener("input", function() {

output.textContent = `You entered: ${input.value}`;

});

In this example, the text changes every time the user modifies the contents of the input field.

Events are the foundation of many features we use every day on websites, from navigation menus and image galleries to forms, filters, and interactive controls.

JavaScript Forms – Validating and Processing User Input

Forms are an important part of almost every web project. They are used for contact requests, user registration, account login, search functionality, and submitting various types of data.

JavaScript can validate entered values and display appropriate messages to users before the data is submitted.

Example of a simple form:

HTML

 

 

<form id="contactForm">

 

<label for="name">Name:</label>

<input type="text" id="name" required>

 

<label for="email">Email:</label>

<input type="email" id="email" required>

 

<button type="submit">Submit</button>

 

</form>

 

<p id="message"></p>

 

JavaScript:

JavaScript

 

 

const form = document.querySelector("#contactForm");

const message = document.querySelector("#message");

 

form.addEventListener("submit", function(event) {

event.preventDefault();

 

const name = document.querySelector("#name").value.trim();

const email = document.querySelector("#email").value.trim();

 

if (name === "" || email === "") {

message.textContent = "Please fill in all required fields.";

return;

}

 

message.textContent = `Thank you, ${name}! The data is ready to be submitted.`;

});

The preventDefault() method prevents the form's default behavior, allowing us to process the data with JavaScript before it is submitted.

It is important to understand that client-side validation in the browser is not a replacement for server-side validation. Data should always be validated on the backend as well, since users can bypass JavaScript or send requests directly to the server.

JavaScript JSON – Exchanging Data Between Applications

JSON (JavaScript Object Notation) is a text-based data format commonly used for exchanging information between frontend and backend systems.

Although JSON was originally inspired by JavaScript object syntax, it is an independent format and is used across many different programming languages.

Example of JSON data:

JSON

 

 

{

"firstName": "Marko",

"lastName": "Petrovic",

"age": 30,

"active": true

}

JavaScript allows you to convert an object into a JSON string using the JSON.stringify() method:

JavaScript

 

 

const user = {

firstName: "Marko",

age: 30

};

 

const jsonData = JSON.stringify(user);

 

console.log(jsonData);

To convert a JSON string back into a JavaScript value, use JSON.parse():

JavaScript

 

 

const text = '{"firstName":"Marko","age":30}';

 

const user = JSON.parse(text);

 

console.log(user.firstName);

JSON is particularly important in modern web development because it is widely used for sending and receiving data through APIs.

JavaScript Asynchronous Programming – Promise, async, and await

Some operations do not complete immediately. For example, downloading data from a server, reading a file, or communicating with a remote service may take some time.

If JavaScript had to wait for each of these operations to finish before continuing execution, the user experience could be significantly worse.

That is why JavaScript supports asynchronous programming, which allows time-consuming operations to run without unnecessarily blocking the rest of the program.

Promise – A Promise That a Result Will Arrive

A Promise is an object that represents the result of an asynchronous operation. It can be in one of three states: pending, fulfilled, or rejected.

Example:

JavaScript

const request = new Promise((resolve, reject) => {

const successful = true;

if (successful) {

resolve("The operation completed successfully.");

} else {

reject("An error occurred.");

}

});

 

request

.then(result => {

console.log(result);

})

.catch(error => {

console.error(error);

});

 

Async and await – Cleaner Asynchronous Code

The async and await keywords make asynchronous code easier to write and understand.

JavaScript

 

 

async function displayData() {

const response = await fetch("/api/products");

 

const data = await response.json();

 

console.log(data);

}

 

displayData();

Here, fetch() sends an HTTP request, while await pauses execution until the associated Promise operation is completed before continuing with the function.

In real-world projects, it is important to handle potential errors as well:

JavaScript

 

 

async function displayData() {

try {

const response = await fetch("/api/products");

 

if (!response.ok) {

throw new Error("Error while retrieving data.");

}

 

const data = await response.json();

 

console.log(data);

 

} catch (error) {

console.error(error);

}

}

 

displayData();

Asynchronous programming is essential for developing modern web applications that communicate with servers and external services.

JavaScript Fetch API – Retrieving Data from a Server

The Fetch API allows JavaScript to send HTTP requests and communicate with servers and API services.

For example, a web application can retrieve a list of products from a server and display it to users without reloading the entire page.

Example:

JavaScript

 

 

async function loadProducts() {

try {

const response = await fetch("/api/products");

 

if (!response.ok) {

throw new Error("Data is not available.");

}

 

const products = await response.json();

 

console.log(products);

 

} catch (error) {

console.error("Error:", error.message);

}

}

 

loadProducts();

In this example:

  1. fetch() sends a request to the specified URL.
  2. await waits for the server response.
  3. response.ok checks whether the HTTP response was successful.
  4. response.json() converts the JSON response into JavaScript data.
  5. try...catch handles possible errors.

The Fetch API can also be used to send data to a server using a POST request:

JavaScript

 

 

async function sendData() {

const user = {

name: "Marko",

email: "marko@example.com"

};

 

try {

const response = await fetch("/api/users", {

method: "POST",

headers: {

"Content-Type": "application/json"

},

body: JSON.stringify(user)

});

 

if (!response.ok) {

throw new Error("Failed to send data.");

}

const result = await response.json();

console.log(result);

 

} catch (error) {

console.error(error);

}

}

This type of communication forms the foundation of many modern web applications, where the frontend displays data while the backend processes and stores it.

JavaScript ES6+ – Modern Features of the Language

JavaScript continues to evolve. Modern standards have introduced numerous features that make code easier to write, read, and maintain.

The term ES6 most commonly refers to ECMAScript 2015, a version that brought significant improvements to the language. Today, JavaScript continues to evolve through newer ECMAScript releases.

Among the most important features of modern JavaScript are:

Template Literals

JavaScript

 

 

const product = "Laptop";

const price = 85000;

 

console.log(`The product ${product} costs ${price} RSD.`);

Destructuring – Extracting Values

JavaScript

 

 

const user = {

name: "Marko",

city: "Belgrade"

};

 

const { name, city } = user;

 

console.log(name, city);

Spread Operator – Copying and Expanding Arrays

JavaScript

 

 

const firstArray = [1, 2, 3];

 

const secondArray = [...firstArray, 4, 5];

 

console.log(secondArray);

Modules – Organizing Code Across Multiple Files

In larger projects, code can be organized using modules.

File math.js:

JavaScript

 

 

export function add(a, b) {

return a + b;

}

File script.js:

JavaScript

 

 

import { add } from "./math.js";

 

console.log(add(10, 20));

To use modules in the browser, the main JavaScript file is linked using type="module":

Error: CdnAliasUnresolved - Unresolved CDN references: 1

HTML

<script type="module" src="script.js"></script>

Console

 

 

Current preview

CdnAliasUnresolved - Unresolved CDN references: 1

Console content may be incorrect

Modules allow a program to be divided into smaller, logically organized units, which is especially useful in larger applications.

JavaScript Errors and Debugging – How to Find Problems in Your Code

Errors are a natural part of programming. Even experienced developers regularly inspect their code and use debugging tools to identify and fix issues.

JavaScript errors can occur due to syntax mistakes, undefined variables, improper data handling, or problems communicating with a server.

Console – The First Tool for Checking Code

The console.log() method allows you to display values in the browser's console.

JavaScript

 

 

const price = 1500;

const quantity = 3;

 

console.log("Price:", price);

console.log("Quantity:", quantity);

console.log("Total:", price * quantity);

 

In addition to console.log(), the following methods are also useful:

  1. console.warn() – displays a warning message.
  2. console.error() – displays an error message.
  3. console.table() – displays data in a tabular format.

Try...catch – Error Handling

When there is a possibility that an operation may cause an error, you can use try...catch.

JavaScript

 

 

try {

const data = JSON.parse('{"name":"Marko"}');

 

console.log(data.name);

 

} catch (error) {

console.error("Invalid data:", error.message);

}

Developer Tools – Browser Development Tools

Chrome, Firefox, Edge, and other modern browsers include built-in Developer Tools.

Using these tools, you can:

  1. Inspect HTML structure and CSS styles.
  2. Monitor JavaScript errors.
  3. Set breakpoints.
  4. Execute code directly in the console.
  5. Inspect HTTP requests and server responses.
  6. Analyze page performance.

To open Developer Tools, you can usually press F12 or use the keyboard shortcut Ctrl + Shift + I.

The ability to find and fix errors is just as important as writing the code itself.

JavaScript Practical Project – Building an Interactive Counter

The best way to learn JavaScript is to create something that actually works. For this example, we will build a simple counter that allows the user to increase and decrease a value using buttons.

HTML:

Error: CdnAliasUnresolved - Unresolved CDN references: 1

HTML

 

 

<div class="counter">

<h2>JavaScript Counter</h2>

 

<p id="value">0</p>

 

<button id="decrease">-</button>

<button id="increase">+</button>

<button id="reset">Reset</button>

</div>

 

<script src="script.js" defer></script>

 

Console

 

 

Current preview

CdnAliasUnresolved - Unresolved CDN references: 1

Console content may be incorrect

JavaScript (script.js):

JavaScript

 

 

let count = 0;

 

const value = document.querySelector("#value");

const increase = document.querySelector("#increase");

const decrease = document.querySelector("#decrease");

const reset = document.querySelector("#reset");

 

increase.addEventListener("click", function() {

count++;

value.textContent = count;

});

 

decrease.addEventListener("click", function() {

count--;

value.textContent = count;

});

 

reset.addEventListener("click", function() {

count = 0;

value.textContent = count;

});

CSS (style.css):

CSS

 

 

.counter {

max-width: 350px;

margin: 40px auto;

padding: 30px;

text-align: center;

background-color: #f2f5f9;

border-radius: 12px;

}

 

.counter p {

font-size: 48px;

font-weight: 700;

}

 

.counter button {

padding: 10px 18px;

border: none;

border-radius: 6px;

background-color: #183b70;

color: white;

cursor: pointer;

}

 

.counter button:hover {

background-color: #28589a;

}

This small project demonstrates how JavaScript combines variables, DOM elements, and events into a functional application.

Once you complete it, you can try adding new features:

  1. Prevent the value from decreasing below zero.
  2. Change the color when the value exceeds a specific limit.
  3. Add a button that increases the value by ten.
  4. Store the most recent value in the browser using localStorage.

By doing this, you gradually move from simple examples to functionality commonly used in real-world web projects.

JavaScript and Frontend Development – How Is It Used in Modern Web Applications?

JavaScript is a core technology of frontend development. It enables HTML and CSS to be connected with application logic, data processing, and user interactions.

In simple projects, JavaScript can be written directly in a few files. In larger applications, developers often use additional tools, libraries, and frameworks that make code organization and development more efficient.

Among the well-known technologies built around JavaScript are:

  1. React – a library for building user interfaces.
  2. Vue.js – a progressive JavaScript framework for interface development.
  3. Angular – a platform and framework for building web applications.
  4. Node.js – a JavaScript runtime environment that allows JavaScript to run outside of a web browser.
  5. Express – a web framework for Node.js commonly used to develop server-side applications and APIs.

It is important to understand that these technologies do not replace knowledge of JavaScript itself. On the contrary, a solid understanding of the core language makes learning React, Vue, Angular, and other tools much easier.

Before moving on to advanced libraries and frameworks, you should have a good understanding of:

  • variables;
  • functions;
  • arrays;
  • objects;
  • the DOM;
  • events;
  • asynchronous programming.

These concepts form the foundation of modern frontend development and are essential for building interactive, responsive, and maintainable web applications.

Is JavaScript Used Only for Frontend Development?

JavaScript can also run on the server side. This means that the same programming language can be used to develop both the frontend and backend parts of an application.

Today, JavaScript is used for:

  1. Frontend web applications.
  2. Backend services and APIs.
  3. Data processing and exchange.
  4. Automation of various tasks.
  5. Development of certain mobile applications.
  6. Development of desktop applications.
  7. Tools and systems running in server environments.

This flexibility makes JavaScript one of the most widely used technologies in modern web development.

Once you have mastered the fundamentals of the language, you can decide whether you want to focus on frontend development, backend development, or full-stack development.

Common Beginner Mistakes in JavaScript

When you are just starting to learn JavaScript, some mistakes can seem confusing. The good news is that most of them are easy to understand once you become familiar with the basic rules of the language.

1. Using a Variable Before It Is Defined

Incorrect:

JavaScript

 

 

console.log(name);

 

const name = "Marko";

 

Correct:

JavaScript

 

 

const name = "Marko";

 

console.log(name);

let and const variables cannot be used before their declaration in the way shown in the incorrect example.

2. Confusing Assignment and Comparison Operators

Incorrect:

JavaScript

 

 

if (number = 10) {

console.log("The number is 10");

}

Correct:

JavaScript

 

 

if (number === 10) {

console.log("The number is 10");

}

The = operator assigns a value, while === checks for strict equality.

3. Forgetting That Arrays Start at Index Zero

JavaScript

 

 

const languages = ["HTML", "CSS", "JavaScript"];

 

console.log(languages[0]); // HTML

The first element has an index of 0, the second has 1, and the third has 2.

4. Attempting to Access an Element That Does Not Exist

JavaScript

 

 

const element = document.querySelector("#nonexistent");

 

console.log(element.textContent);

If the element does not exist, querySelector() returns null. Attempting to access one of its properties will cause an error.

A safer approach:

JavaScript

 

 

const element = document.querySelector("#title");

 

if (element) {

console.log(element.textContent);

}

5. Forgetting the Asynchronous Nature of Promise Operations

JavaScript

 

 

const response = fetch("/api/data");

 

console.log(response);

This code does not immediately display the data from the server. Instead, it logs a Promise object.

To process the result, you need to use then() or async/await.

JavaScript

 

 

async function load() {

const response = await fetch("/api/data");

const data = await response.json();

 

console.log(data);

}

6. Mixing JavaScript and HTML Without Clear Organization

Code that is difficult to read and maintain can quickly become a problem, even if it works correctly. Use meaningful variable names, separate functions, and dedicated JavaScript files when the project requires them.

Mistakes are not a reason to give up on programming. They are a normal part of the learning process and often provide the best opportunity to better understand how JavaScript works.

How to Continue Learning JavaScript and in What Order?

JavaScript offers a wide range of capabilities, which means that trying to learn everything at once can be overwhelming. A much more effective approach is to build your knowledge gradually through small, practical exercises.

A recommended learning path is:

  1. Understanding JavaScript and connecting it to an HTML document.
  2. Variables, constants, and data types.
  3. Operators and conditional statements.
  4. Loops and repetition.
  5. Functions and parameters.
  6. Arrays and data manipulation methods.
  7. Objects and their properties.
  8. The DOM and selecting HTML elements.
  9. Events and user interaction.
  10. Forms and processing user input.
  11. JSON and communication with APIs.
  12. Promises, async/await, and asynchronous programming.
  13. JavaScript modules and project organization.
  14. Introduction to libraries and frameworks.

Don't stop at simply reading examples. Try writing each example yourself, changing values, adding new functionality, and experimenting to see what happens when you modify different parts of the code.

It is through this kind of hands-on practice that you develop the problem-solving mindset required for programming.

A good way to reinforce your learning is to build small projects after each major topic, such as:

  • a calculator after learning operators;
  • a number guessing game after learning conditions and loops;
  • a to-do list after learning arrays and DOM manipulation;
  • a contact form after learning events and form handling;
  • a product catalog that retrieves data from an API after learning Fetch and asynchronous programming.

By gradually combining concepts into real projects, you'll move from understanding individual JavaScript features to building complete, interactive web applications.

Conclusion – JavaScript as the Foundation of Interactive Web Development

JavaScript is much more than a language for powering buttons and simple animations. It is one of the core technologies of modern web development, enabling the creation of interactive websites, dynamic user interfaces, and complex applications.

Once you understand variables, functions, conditions, loops, arrays, objects, and the DOM, you have a solid foundation for further growth as a developer. As your knowledge advances, new opportunities open up to work with APIs, asynchronous operations, modern frontend libraries, and server-side technologies.

The best approach is to learn JavaScript step by step through practical examples and small projects. You do not need to understand every advanced feature of the language right away. What matters most is understanding the core concepts and learning how to apply them independently.

HTML provides the structure, CSS shapes the appearance, and JavaScript enables interaction. When you begin using these three technologies together, you build the foundation required for creating modern, functional, and engaging web projects.