JAVASCRIPT

What is JavaScript: Syntax, Usage, and Examples

JavaScript is a high-level, interpreted programming language that adds interactivity and dynamic functionality to websites. It allows you to manipulate web page content, control multimedia, and create complex applications, making it an essential tool for modern web development.

How to Use JavaScript

JavaScript runs inside web browsers, executing code when a page loads or in response to user actions. You can include JavaScript in an HTML document using the <script> tag or store it in an external file.

Inline JavaScript

You can embed JavaScript directly within an HTML file:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Example</title>
</head>
<body>
  <button onclick="greet()">Click me</button>
  <script>
    function greet() {
      alert("Hello, world!");
    }
  </script>
</body>
</html>

This code displays an alert message when the button is clicked.

External JavaScript

For better organization, store JavaScript in a separate file and link it inside the HTML document:

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

Inside script.js:

function greet() {
  alert("Hello, world!");
}

This keeps your code modular and reusable across multiple pages.

When to Use JavaScript

JavaScript is widely used across different areas of web development. Here are common scenarios where you should use JavaScript:

  1. Creating Interactive Web Pages – JavaScript allows you to build dynamic user interfaces with elements like image sliders, modals, and dropdown menus.
  2. Handling User Input and Validation – You can verify user input before sending data to the server, improving efficiency and user experience.
  3. Fetching and Displaying Data – JavaScript makes it possible to retrieve data from APIs and update the page without reloading.
  4. Building Single-Page Applications (SPAs)Frameworks like React, Vue, and Angular rely on JavaScript to load content dynamically.
  5. Developing Server-Side Applications – JavaScript runs outside the browser with Node.js, allowing you to create web servers and interact with databases.
  6. Enhancing Performance – JavaScript can pre-load assets, lazy-load images, and handle animations efficiently.

Examples of JavaScript

Modifying Web Page Content

JavaScript lets you change HTML elements dynamically.

<button onclick="changeText()">Change Text</button>
<p id="message">Original text</p>

<script>
  function changeText() {
    document.getElementById("message").innerHTML = "Text changed!";
  }
</script>

When clicked, the button updates the paragraph content without refreshing the page.

Form Validation

Use JavaScript to ensure users provide valid input before submitting a form.

<form onsubmit="return validateForm()">
  <input type="text" id="username" placeholder="Enter username">
  <button type="submit">Submit</button>
</form>

<script>
  function validateForm() {
    let username = document.getElementById("username").value;
    if (username === "") {
      alert("Username cannot be empty");
      return false;
    }
    return true;
  }
</script>

Fetching Data from an API

JavaScript enables asynchronous requests, allowing you to fetch data without page reloads.

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error fetching data:", error));

This fetches a post from an API and logs it to the console.

Learn More About JavaScript

What is JavaScript Used For?

JavaScript is versatile and powers many aspects of web development:

  • Web Development: JavaScript controls elements on a page, making sites more engaging.
  • Mobile Development: Frameworks like React Native let you build cross-platform apps.
  • Backend Development: With Node.js, JavaScript can create APIs and interact with databases.
  • Game Development: The Canvas API and WebGL allow you to develop browser-based games.
  • Machine Learning & AI: Libraries like TensorFlow.js enable browser-based AI applications.

JavaScript Variables and Data Types

JavaScript supports three ways to declare variables:

let name = "Alice";  // Block-scoped variable
const age = 25;      // Constant value
var city = "New York"; // Function-scoped variable (older syntax)

Data types include:

  • Strings: "Hello"
  • Numbers: 42, 3.14
  • Booleans: true, false
  • Objects: { name: "Alice", age: 30 }
  • Arrays: ["Apple", "Banana", "Cherry"]
  • Null & Undefined: Indicate missing values.

JavaScript Functions

Functions allow code reuse and modular programming.

function greet(name) {
  return `Hello, ${name}!`;
}
console.log(greet("Alice"));

Arrow functions provide a shorter syntax:

const greet = name => `Hello, ${name}!`;
console.log(greet("Alice"));

JavaScript Loops

Loops let you execute code multiple times.

for (let i = 1; i <= 5; i++) {
  console.log("Iteration:", i);
}

JavaScript Events

JavaScript listens for user interactions and triggers functions accordingly.

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

<script>
  document.getElementById("myButton").addEventListener("click", function() {
    alert("Button clicked!");
  });
</script>

JavaScript Objects and Arrays

Objects group related data.

const user = { name: "Alice", age: 30 };
console.log(user.name); // Alice

Arrays store multiple values.

let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[1]); // Banana

JavaScript Promises and Async/Await

Promises handle asynchronous operations.

const fetchData = () => {
  return new Promise(resolve => setTimeout(() => resolve("Data loaded"), 2000));
};

fetchData().then(data => console.log(data));

async/await makes this cleaner:

async function loadData() {
  let data = await fetchData();
  console.log(data);
}
loadData();

JavaScript Modules

Modules keep code modular and reusable.

// module.js
export function greet(name) {
  return `Hello, ${name}`;
}

// main.js
import { greet } from './module.js';
console.log(greet("Alice"));

JavaScript Frameworks and Libraries

Popular JavaScript frameworks and libraries include:

  • React.js: A library for building dynamic user interfaces.
  • Vue.js: A progressive framework for web applications.
  • Angular: A powerful framework for enterprise applications.
  • Node.js: Runs JavaScript on the server side.

JavaScript Performance Optimization

Writing efficient JavaScript can improve web page speed:

  • Minimize DOM Manipulation: Update elements efficiently instead of modifying them frequently.
  • Use Asynchronous Code: Fetch data asynchronously to avoid blocking the main thread.
  • Cache Results: Store frequently used values to reduce redundant calculations.
  • Debounce Input Events: Prevent excessive function calls on events like keypress or scroll.

JavaScript opens up endless possibilities, whether you’re enhancing a website, building a full-fledged application, or working with server-side code.

Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH