Maker.io main logo

A Beginner’s Guide to JavaScript

180

2026-08-10 | By Maker.io Staff

JavaScript is a popular language that transforms static websites into interactive web applications. It’s surprisingly approachable, and beginners can build simple applications within a short time. Read on to learn the core JavaScript basics you need to build and ship your first web application.

Image of A Beginner’s Guide to JavaScript

Where JavaScript Sits in the Modern Web

It’s worth establishing context before getting started with JavaScript. Interactive websites usually have three main components: HTML, which defines the page layout; CSS, which describes how elements look; and JavaScript, which adds interactivity. This is not an exhaustive list of technologies and approaches, and developers often mix, extend, or replace parts of this setup. Still, the basic three-part model remains useful for understanding how many web apps work.

It’s also important to outline what JavaScript can and cannot do. It’s mainly used for interacting with elements on a website, reading and processing user inputs, and updating a website dynamically. JavaScript can also access browser and device features, such as a smartphone's sensors or camera. However, for security reasons, JavaScript runs inside a web browser sandbox with very limited access to hardware and OS features.

Variables in JavaScript

Like in other programming languages, variables store values and assign them a meaningful name that can be used throughout the application. However, unlike most languages, variables in JavaScript have weak typing, meaning that they do not have a fixed type. Instead, the JavaScript interpreter assumes the type based on the value assigned to a variable. Furthermore, variables can change their type dynamically. However, it’s usually not a good idea to change types dynamically, since it usually makes the code harder to follow and can introduce bugs that are difficult to find.

There are three main ways to declare variables in JavaScript. However, we’ll only look at two of them, since they are the most interesting to newcomers. Variables can be declared with the let keyword, and constants with const:

Copy Code
let angleInDegrees = 72;
const pi = 3.1416;

Variables are only valid within the declaring block, like a function or an if-block, and all nested blocks. However, variables that are declared outside of functions or a specific block are valid globally:

Copy Code
// The entire script can access pi
const pi = 3.1416;

function func1() {
  // This is only valid in func1
  let angleInDegrees = 72;
}

function func2(a, b, operation) {
  // a, b, and operation are only valid in func2
  if (a < b) {
    let c = 2;
    // ...
  }
  // c no longer exists outside of the if-block
}

Similar to other programming languages, you cannot declare other variables with the same name in the same scope using let or const. Furthermore, the const keyword denotes constants, and their value and type cannot be changed once declared. However, as mentioned, it is possible to change the type of variables defined with let:

Copy Code
let angleInDegrees = 72;
let angleInRads = angleInDegrees * (Math.PI / 180);
angleInDegrees = 'This is now a string!';
return angleInRads;

The freedom of weak typing extends to JavaScript arrays. In JavaScript, arrays are not bound to a specific type or a fixed length. Instead, they are more like lists that can hold any data type and can grow and shrink as needed:

Copy Code
let data = [1, "hello", true, 42];

However, similar to regular variables, it’s not recommended that beginners mix types within a single array to avoid confusing code. Values can be added, removed, and retrieved dynamically:

Copy Code
let data = [1, "hello", true, 42];
let value = data.pop(); // Remove last
data.push("world"); // Append
let greeting = data[1] + “ “ + data[data.length - 1]; // Retrieve values

Note that the first value in the array has index zero and the last can be accessed using the array’s length minus one.

Branching and Loops

The if-block can be used to execute code and alternative paths based on conditions, such as boolean flags or numeric comparisons:

Copy Code
if (numberA > Math.PI) {
  // numberA is greater than 3.1416
} else if (numberA < 0) {
  // numberA is less than Pi and negative
} else {
  // numberA is at least zero and at most Pi
}

In this example, the code within the first block is only executed if the variable numberA is greater than Pi. You can add as many optional if-else blocks as you like, and they get evaluated from top to bottom until a condition is met. Lastly, the optional else-block runs if no other condition is met. Note that you can omit the curly brackets if a block contains only one statement, which can help improve the readability of simple statements:

Copy Code
if (firstNumber === "0") firstNumber = digit;
else if (firstNumber.length < 10) firstNumber += digit;

The while-loop is similar to the if-statement in the sense that code within the block runs as long as a condition is met:

Copy Code
let counter = 0;
while (counter < 10) {
    // Do something ten times
    // And don't forget to increase the counter
    // to prevent infinite loops!
    counter = counter + 1;
}

The while-loop is a general-purpose loop that continues as long as a condition is true, not just for numeric comparisons. When you’re working with simple counting loops, a for-loop can be a more readable alternative to the while-loop. As shown in the example, this is because it combines the initialization, condition, and update step in a single line:

Copy Code
for (let counter = 0; counter < 10; counter++) {
    // Do something ten times
    // No more danger of forgetting to increase the counter! :)
}

Basic Input and Output Operations in JavaScript

A program becomes much more useful once it can accept user input and display results. JavaScript lets users enter values in a few ways. The simplest ones are a pop-up prompt and the confirmation dialog.

Pop-up prompts can be created using the prompt() function. The function blocks the entire program until the user enters a value or dismisses the pop-up. It returns the entered value or null if nothing was entered:

Copy Code
const username = prompt("Please enter your name!");

Image of A Beginner’s Guide to JavaScript This image shows the result of making a prompt() call in JavaScript.

Use the confirm() function to display a yes/no dialog box. This function returns true if the user clicked the confirm button and false otherwise:

Copy Code
if (confirm("Another calculation?")) {
    // User clicked “OK”
} else {
    // User clicked “Cancel” or closed the dialog
}

Image of A Beginner’s Guide to JavaScript

JavaScript offers two simple ways to display output through browser pop-ups and the console. For example, you can use the alert() function to greet the user after they enter their name:

Copy Code
const username = prompt("Please enter your name!");
const greeting = "Hello, " + username + "!";
alert(greeting);

The result is a simple pop-up box like this:

Image of A Beginner’s Guide to JavaScript

You can also print values to the browser’s debugging console, which can typically be accessed via the developer tools (F12 in most modern browsers). Note that the browser may require you to enable the development tools as a security feature.

In either case, you can print console messages using the following functions:

Copy Code
const username = prompt("Please enter your name!");
const greeting = "Hello, " + username + "!";

console.log(greeting); // For simple debugging messages
console.warn("I am a teapot"); // Show warnings
console.error("Cannot brew coffee!"); // Show errors

Keep in mind that these messages are meant for developers to display errors, warnings, and debugging messages, and should not be used to communicate with users. Similarly, the pop-ups from before can be useful during debugging. However, they should be avoided in modern web applications. The reason is that they interrupt the user experience, cannot be styled to match the rest of a website, and offer very little control over behavior or accessibility.

Accessing HTML From JavaScript Code

JavaScript runs directly in the web browser and can access input fields on a website and interact with HTML content. This ability lets scripts read input values, update website contents, and add new elements directly without reloading the page.

Elements on a website can be retrieved in different ways. Usually, they are referenced from JavaScript code using the element ID or type. For example, assume that a website has the following input field:

Copy Code
<input type="text" id="usernameInput">

A script, referenced in the HTML document, can obtain this HTML element using:

Copy Code
const nameField = document.getElementById("usernameInput");

The script can then further read the data previously entered by a user:

Copy Code
const nameField = document.getElementById("usernameInput");
const name = nameField.value;
console.log(name);

All elements on a website can be accessed in a similar way. However, some might not have a value that can be read. In that case, the result will be undefined.

Existing data on a website can be modified using one of two attributes. The textContent attribute treats the modified data as pure text, and it ignores HTML tags contained in the data. This property makes it much more secure to use and less likely to break things:

Image of A Beginner’s Guide to JavaScript Setting the textContent does not result in the strong-tag being evaluated by the browser. The data is treated as simple text that replaces the existing text on an HTML element, in this case, a div.

In contrast, there are ways to directly modify the HTML of a website. The innerHTML attribute, for example, can be used to inject HTML tags into a website to update its contents or add new elements. Using this attribute, the browser treats the incoming data as HTML, and it evaluates all tags it contains:

Image of A Beginner’s Guide to JavaScript When using innerHTML, the browser evaluates HTML tags, which results in the text being printed in bold letters in this example.

Lastly, you can create and add new HTML elements using various approaches. However, it’s recommended to use the built-in createElement function and add the newly created HTML element to a parent with a well-defined ID to prevent errors. The following example creates a simple button and adds it to the website:

Image of A Beginner’s Guide to JavaScript The example in this screenshot demonstrates how to create a new button and add it to an existing div on a website.

Keeping JavaScript Programs Organized

Even though it’s possible to write JavaScript as one continuous block of code without much structure, it’s usually better to organize it into functions and smaller, meaningful parts. This makes the code easier to understand and maintain, and also helps avoid issues with things running at the wrong time, like when the page hasn’t fully loaded yet.

Like in other programming languages, functions in JavaScript can have parameters and return values. However, unlike many statically typed languages, the types for either parameters or return values are not fixed. Instead, the values passed into a function can be of any type, and a function can also return different types depending on the execution path:

Copy Code
function someFunction(parameterA, parameterB) {
    if (typeof parameterA === "number" && typeof parameterB === "number") {
        return "received two numbers!";
    }
    if (typeof parameterA === "string" && typeof parameterB === "string") {
        return "received two strings!";
    }
}

let result1 = someFunction(1, 2);
let result2 = someFunction("Hello", "World");
let result3 = someFunction(false, [1, 2, 3]);

console.log("Call 1: " + result1);
console.log("Call 2: " + result2);
console.log("Call 3: " + result3);

Like with variables, it’s recommended not to mix return and parameter types to keep the code easier to read and maintain. Instead, create overloads of functions with a short comment describing the expected parameter types and return type:

Copy Code
/*
 * Performs some task
 * Expects two string parameters
 * Returns a string
 */
function someStringFunction(parameterA, parameterB) {
    return "received two numbers!";
}

/*
 * Performs some task
 * Expects two integer parameters
 * Returns a string
 */
function someNumberFunction(parameterA, parameterB) {
    return "received two numbers!";
}

Reacting to Events in JavaScript

Besides taking in input values, calculating something, and showing users the result, programs should also be able to respond to events, such as user inputs or actions. For example, a website might perform a search whenever users type a character into a search bar, or it might calculate a value when users click a button. JavaScript programs can react to such events using regular functions. However, when used to respond to an event or trigger, these functions are commonly called event handlers.

The following short snippet creates a website with a div, a simple button, a text field, and a short event handler function that displays a greeting. Notice the onclick attribute on the button tag in the HTML. This attribute tells the browser to call the greetUser function in the JavaScript code whenever the button is clicked:

Copy Code
<html>
    <div id="greetingDiv">Please enter your name below!</div>
    <hr>
    <input type="text" id="nameTextField">
    <button onclick="greetUser()">Accept</button>
    <script>
        function greetUser() {
            const greetingDiv = document.getElementById("greetingDiv");
            const name = document.getElementById("nameTextField").value;
            greetingDiv.textContent = "Hello, " + name + "!";
        }
    </script>
</html>

Besides input fields and buttons, the website itself also emits events, such as when it finishes loading. The Mozilla Developer Web Docs contains an extensive list of events with further details and examples. You can also refer to this article for an in-depth look at event handlers.

Bringing It All Together

Now that you know the basics of JavaScript, it’s time to dive into a more useful example. Start by downloading the accompanying HTML and CSS file from here. Then, create a file named calculator.js in the same folder. Note that the HTML file imports calculator.js. If you want to name the file differently, make sure to update this line in the HTML file to match the new name:

Copy Code
<script src="calculator.js" defer></script>

Create the following global variables in the JavaScript file:

Copy Code
let firstNumber = "0";
let secondNumber = "0";
let operator = "+";
let step = 0;

These store the numbers that the user entered and the selected operation. The step variable keeps track of the application’s current state.

Open the HTML file and look at the body tag. It has an event handler tied to its onLoad event, meaning that the browser calls the start function when the document finishes loading. This is a common pattern to ensure that the script doesn’t start its initialization logic before the HTML data is complete. This is the start function:

Copy Code
function start() {
    const container = document.getElementById("numberPad");
    for (let i = 1; i <= 9; i++) {
        const newButton = document.createElement("button");
        newButton.textContent = i;
        newButton.addEventListener("click", function () {
            addDigit(i.toString());
        });
        container.appendChild(newButton);
    }
    updateDisplay();
}

It gets the div from the HTML with the numberPad identifier. The script uses this div as a parent for nine numeric keypad buttons that it creates and adds to the container in the for-loop. The code uses the createElement and appendChild functions, as discussed above. However, it also adds an event listener to each of the newly created buttons so that when a user clicks the button, the browser calls the addDigit function with the number shown on the button. Initialization finishes by redrawing the user interface:

Copy Code
function updateDisplay() {
    document.getElementById("firstNumber").textContent = firstNumber;
    document.getElementById("secondNumber").textContent = secondNumber;
    document.getElementById("selectedOperator").textContent = operator;
}

All that this simple helper function does is bundle three getElementById calls to the three output divs in the user interface and update their text contents.

Remember that pressing one of the numeric buttons, created in the start function, calls the addDigit event handler, which looks as follows:

Copy Code
function addDigit(digit) {
    if (step === 0) {
        if (firstNumber === "0") firstNumber = digit;
        else if (firstNumber.length < 10) firstNumber += digit;
    } else {
        if (secondNumber === "0") secondNumber = digit;
        else if (secondNumber.length < 10) secondNumber += digit;
    }
    updateDisplay();
}

In step zero, the program updates the first user-entered number. In step one, it updates the second number. If the number to update is zero, the script replaces the old value with the number shown on the button that triggered the event. Otherwise, it appends the new digit to the existing number until it reaches ten digits of length. Lastly, the event handler calls the updateDisplay helper function.

Look at the HTML document, and notice that each of the operation buttons calls the following setOperation event handler:

Copy Code
function setOperation(op) {
    step = 1;
    operator = op;
    disableButton("plusButton", true);
    disableButton("minusButton", true);
    disableButton("timesButton", true);
    disableButton("equalsButton", false);
    updateDisplay();
}

This code sets the application state to one, which signals that the user has finished entering the first number. It also records the operation the user selected with one of the buttons. The function then calls the disableButton helper before updating the UI again:

Copy Code
function disableButton(buttonId, disable) {
    document.getElementById(buttonId).disabled = disable;
}

This simple helper gets the button with the specified ID and sets its disabled state flag to the value passed into the function.

Finally, the equals button in the UI also has an event handler attached to its click event:

Copy Code
function showResult() {
    const a = Number(firstNumber);
    const b = Number(secondNumber);
    const outputDisplay = document.getElementById("result");

    if (operator === '+') outputDisplay.textContent = a + b;
    else if (operator === '-') outputDisplay.textContent = a - b;
    else outputDisplay.textContent = a * b;

    step = 2;
    disableButton("equalsButton", true);
}

This event handler function converts the user-entered numbers into actual numeric variables that can be used in mathematical operations. Before that, the numbers were stored as strings to make appending digits easier. The function then gets the result div that it uses to show the calculation result. Next, the script determines which operand the user selected, and it applies the corresponding mathematical operation to the two numbers. Once done, the code shows the result in the outputDisplay HTML element, updates the internal state, and deactivates the equals button in the UI:

Image of A Beginner’s Guide to JavaScript This screenshot shows the finished calculator example.

Summary

HTML documents define a website’s layout, CSS files define how elements on a page look, and JavaScript transforms static websites into interactive web applications. JavaScript runs in a web browser, which means that it can interact with elements on a website to read user inputs, react to events, and dynamically change website content. However, the browser also limits script access to device features for security reasons.

Weak typing is one of JavaScript’s most notable features. Variables, declared with the let keyword, do not have a fixed type. Instead, their type is inferred from their current value. The value of constants created using the const keyword cannot change once assigned. Both constants and variables are only valid within the declaring block and its nested blocks. Variables declared outside of a specific block are valid globally.

Functions are used to organize longer scripts into self-contained functional blocks. Like variables, their return type and parameter types are not fixed. However, it’s recommended to add comments that explain what types a function expects and what it returns. JavaScript further defines functional blocks, most notably the if-else block, the while-loop, and the for-loop.

Have questions or comments? Continue the conversation on TechForum, DigiKey's online community and technical resource.