• JavaScript
    • Beginner
    • Code

    JavaScript Basics for Beginners

    By Published Updated 4 min read

    Learn JavaScript basics: const and let, functions, the DOM, arrays and objects, with runnable examples and answers to common beginner questions.

    JavaScript (JS) is the programming language built into every major web browser, and it is what makes web pages interactive: responding to button clicks, validating forms and updating content without a reload. To get started you need five basics: variables, functions, the DOM, arrays and objects. This guide explains each one with code you can run right away.

    Key takeaways

    • Declare variables with const by default, and switch to let only when you need to reassign them.
    • Functions can be written as declarations or as arrow functions; both are modern and widely used.
    • The DOM is the browser's object model of your HTML, and JavaScript uses it to read and change the page.
    • Arrays hold ordered lists of values, and objects group related data as key-value pairs.

    What is JavaScript used for?

    JavaScript started in the browser, and it is still the language browsers run for page scripting. It is not the only code a browser can execute natively, though: WebAssembly also runs in modern browsers. WebAssembly is usually compiled from languages such as C, C++ or Rust, and it is designed to run alongside JavaScript rather than replace it. Outside the browser, runtimes such as Node.js run JavaScript on servers and in command-line tools.

    Modern JavaScript engines are fast and capable, but every expert still starts with the same basics.


    1. Variables: How do you store data?

    Older code uses var. Modern code uses let and const, which are block-scoped and behave more predictably. (The ES6 features guide explains the difference in detail.)

    let vs const

    • let: Use it when the variable will be reassigned later (for example, a score counter).
    • const: Use it when the variable should never be reassigned (for example, an app name). A const variable cannot point to a new value, but if it holds an object or array, the contents can still change, as MDN's const reference explains.
    // A variable that can be reassigned
    let uniqueUsers = 100;
    uniqueUsers = 101; // Valid
    
    // A constant that cannot be reassigned
    const appName = "WebFiddle";
    // appName = "OtherApp"; // Uncomment to see: TypeError: Assignment to constant variable.
    
    // The contents of a const object can still change
    const settings = { theme: "light" };
    settings.theme = "dark"; // Valid: the variable still points to the same object
    
    console.log(uniqueUsers, appName, settings.theme); // 101 WebFiddle dark
    

    Tip: Default to const. Change it to let only when you actually need to reassign the variable. That way, an accidental reassignment becomes an immediate error instead of a hidden bug.


    2. Functions: How do you write reusable code?

    A function is a reusable block of code that performs a particular task. There are two common ways to write one: a function declaration and an arrow function.

    // Function declaration
    function sayHello(name) {
        return "Hello " + name;
    }
    
    // Arrow function
    const greet = (name) => {
        return `Hello ${name}`;
    };
    
    console.log(sayHello("Atish")); // Hello Atish
    console.log(greet("Atish"));    // Hello Atish
    

    Both styles are valid modern JavaScript. Arrow functions are shorter and do not have their own this, which makes them handy for callbacks. Function declarations are hoisted, so you can call them before the line where they are defined. MDN's arrow function reference lists the remaining differences.

    Notice the ${name} syntax? That is a template literal: a string wrapped in backticks that can embed any expression. It is usually easier to read than joining strings with +.


    3. The DOM: How does JavaScript change a web page?

    The Document Object Model (DOM) is the browser's representation of your HTML as a tree of objects. JavaScript uses the DOM to read, change, add and remove elements while the page is open (MDN: Document Object Model).

    Imagine you have a button in HTML:

    <button id="myBtn">Click Me</button>
    <p id="message"></p>
    

    Here is how JavaScript interacts with it:

    // 1. Select the elements
    const btn = document.getElementById("myBtn");
    const msg = document.getElementById("message");
    
    // 2. Listen for clicks
    btn.addEventListener("click", () => {
        // 3. Change the page
        msg.textContent = "You clicked the button!";
        msg.style.color = "blue";
    });
    

    The DOM only exists in a browser, so this example will not work in a plain Node.js environment. Try it in the HTML, CSS & JavaScript editor: put the HTML in the HTML panel and the script in the JavaScript panel, then click the button in the live preview.


    4. Arrays and loops: How do you work with lists?

    An array stores an ordered list of values. The forEach method runs a function once for each item.

    const fruits = ["Apple", "Banana", "Orange"];
    
    // Add a new item to the end
    fruits.push("Mango");
    
    // Loop through the items
    fruits.forEach((fruit) => {
        console.log(`I like ${fruit}`);
    });
    

    An object groups related data as key-value pairs, also called properties.

    const user = {
        name: "Atish",
        role: "Developer",
        isLoggedIn: true,
        skills: ["HTML", "CSS", "JS"]
    };
    
    console.log(user.name);      // Atish
    console.log(user.skills[2]); // JS
    

    You will use objects everywhere. JSON, the data format many web APIs return, is based on JavaScript object and array syntax, so understanding objects also helps you read API data.


    Summary

    1. Use const by default and let when you need to reassign.
    2. Write functions as declarations or arrow functions (() => {}).
    3. Use document.getElementById to find elements on the page.
    4. Use addEventListener to react to users.

    Run the non-DOM examples (variables, functions, arrays and objects) in the Node.js sandbox, and the DOM example in the HTML preview editor. Once these basics feel comfortable, read 10 ES6 features every JavaScript developer uses, and learn the structure your scripts work with in HTML basics.

    Frequently asked questions

    Is JavaScript the only language that runs in the browser?

    No. JavaScript is the scripting language every major browser runs, but WebAssembly also runs natively in modern browsers. WebAssembly is usually compiled from languages such as C, C++ or Rust and works alongside JavaScript. For everyday interactivity and working with the DOM, JavaScript is still the language you write directly.

    Should I use let or const in JavaScript?

    Use const by default, and use let only when a variable must be reassigned, such as a loop counter or a running total. Avoid var in new code. Remember that const prevents reassignment, not mutation, so an object or array declared with const can still have its contents changed.

    What is the difference between JavaScript and Java?

    They are separate languages with different designs, despite the similar names. JavaScript is dynamically typed and runs in browsers and in runtimes such as Node.js. Java is a statically typed language compiled to bytecode for the Java Virtual Machine. General programming concepts carry over, but the syntax and ecosystems differ.

    Can I run JavaScript without installing anything?

    Yes. Every modern browser includes a JavaScript engine, so you can open the developer console and type code directly. For longer experiments, an online editor is more convenient: WebFiddle's HTML preview runs DOM code in a live page, and its Node.js sandbox runs plain JavaScript without any local setup.

    Try the examples yourself

    Open the Node.js sandbox to run and edit code from this article in your browser. There is nothing to install and no account to create.