DEV Community

Somadina
Somadina

Posted on

Breakdown of JavaScript cores concept in connection to html with examples

Introduction

Could you believe that these are the core concepts that make up the giant JavaScript programming language. The interconnection of these cores builds interactiity on webpage. It is the layer upon which frameworks like jquery tries to simplify. Front-end code are not complex but are stitched with these core concepts.Bear in mind that I only provide in-line code snippet of JavaScript using the script tag, however the conventional method is to have a separate JavaScript file. The snippet is meant to show you how JavaScript core idea is applied in html, which is one thing that scatters the mind of beginners when they are trying to understand the giant called JavaScript:

  • Syntax
  • Comments
  • Arithmetic Operators
  • Assignment Operators
  • Variables
  • Data types
  • Conditionals
  • Loops
  • Functions
  • Objects
  • Events
  • DOM Manipulation (In fact, DOM manipulation is the main tool that controls the behavior of web pages, creating the interactivity web developers often talk about).

## Concepts are:

  • Asynchrous Operations,
  • Modules
  • And finally, Library


If you know how to initiate these core concepts when programming, you can proudly call yourself a JavaScript guru. You can also easily learn other higher-level programming languages and start helping your fellow humans solve their digital problems. All these concepts are interrelated but somewhat subtle to detect, yet they exist deeply in your code if you have ever added JavaScript to your web page.

So don’t just read this content alone — use the ideas here to look at any JavaScript codebase. It will remove your phobia about seeing complex code structures as eyesores in your mind. Your life will also be a lot easier when debugging or trying to understand the connection between JavaScript, HTML, and CSS.

I don’t want to use anything aside from HTML as an example since that is what web development in connection with JavaScript entails. Creating examples about the core concepts of JavaScript without showing how they are used in HTML only makes you wonder about their applicability when reading. I don’t want that to happen. That’s why I’ve fused the core concepts with HTML itself. So, to benefit fully from this lesson, you at least need basic HTML knowledge.

Comments are a set of instructions written within your code that are ignored by the browser. Single-line and multi-line comments are the two main types. Examples: anything written after two forward slashes like // is a single-line comment, while anything written between /* and */ is a multi-line comment.

I have to define comments carefully from the onset because they will be used intensively within the code that demonstrates these core concepts. Study the comments within the code — think about them and connect them to the preview or highlights defining each concept.

Code snippet example of comments in action:


<script>
  // This is a single-line comment

  /* 
     This is a multi-line comment.
     It can span multiple lines.
  */

  let name = "John"; // store user's name
  console.log(name); // display name in console
</script>
Enter fullscreen mode Exit fullscreen mode

Unraveling The Core Concepts of JavaScript

Syntax:

It is the language of any programming system — the way you express your human intentions to the computer. Syntax is how you present the building blocks (e.g., variables, functions, and loops) to the computer through that specific language — in this case, JavaScript.

Variable:

A variable is memory space for storing values temporarily or permanently before referencing them.
Example:

<h1 id="siteTitle"></h1>
<script>
  let siteName = "TechWorld Blog";
  const yearEstablished = 2020;
  let titleElement = document.getElementById("siteTitle");
  titleElement.textContent = siteName + " - Since " + yearEstablished;
</script>
Enter fullscreen mode Exit fullscreen mode

Arithmetic and Assignment Operators:

Arithmetic operators (+, -, *, /) perform calculations, while Assignment Operators (=, +=, -=, *=, /=) store and update variable values.
Example:

<p id="mathResult"></p>
<script>
  let a = 10;
  let b = 5;

  // Arithmetic operations
  let sum = a + b;
  let diff = a - b;
  let prod = a * b;
  let div = a / b;

  // Assignment operations
  a += 2;
  b *= 3;

document.getElementById("mathResult").innerHTML = `
    Sum: ${sum}<br>
    Difference: ${diff}<br>
    Product: ${prod}<br>
    Division: ${div}<br>
    Updated a: ${a}<br>
    Updated b: ${b}
  `;
</script>
Enter fullscreen mode Exit fullscreen mode

Data Types:

Data types include Number, String, Boolean, Object, Array, Null, and Undefined. They are the basic units that make up everything your page displays. Without understanding data types, you’ll struggle with constructing or deconstructing assignments within your codebase.
Example:

<ul id="dataTypes"></ul>
<script>
  let siteName = "TechWorld Blog";                // String
  let visitorCount = 1345;                        // Number
  let isUserLoggedIn = true;                      // Boolean
  let userEmail;                                  // Undefined
  let currentAd = null;                           // Null
  let article = { title: "Intro to JS", author: "Jane Doe" }; // Object
  let categories = ["HTML", "CSS", "JavaScript"]; // Array
  let uniqueId = Symbol("userID");                // Symbol
  let totalUsers = 9876543210123456789n;          // BigInt

  let dataList = document.getElementById("dataTypes");
  dataList.innerHTML = `
    <li>String: ${siteName}</li>
    <li>Number: ${visitorCount}</li>
    <li>Boolean: ${isUserLoggedIn}</li>
    <li>Undefined: ${userEmail}</li>
    <li>Null: ${currentAd}</li>
    <li>Object: ${article.title} by ${article.author}</li>
    <li>Array: ${categories.join(", ")}</li>
    <li>Symbol: ${uniqueId.toString()}</li>
    <li>BigInt: ${totalUsers}</li>
  `;
</script>
Enter fullscreen mode Exit fullscreen mode

Conditionals:

Conditionals apply Boolean logic — true or false — to trigger specific code when a condition is met.
Example:

<p id="result"></p>
<script>
  let score = 75;
  if (score >= 80) {
    document.getElementById("result").textContent = "Excellent!";
  } else if (score >= 50) {
    document.getElementById("result").textContent = "Good job!";
  } else {
    document.getElementById("result").textContent = "Keep trying!";
  }
</script>
Enter fullscreen mode Exit fullscreen mode

Loops:

Loops repeat code a set number of times. Use a for loop when you know how many times to run, and a while loop when you don’t.
Example:

<ul id="list"></ul>
<script>
  let output = "";
  for (let i = 1; i <= 3; i++) {
    output += "<li>For loop count: " + i + "</li>";
  }

  let j = 1;
  while (j <= 3) {
    output += "<li>While loop count: " + j + "</li>";
    j++;
  }

  document.getElementById("list").innerHTML = output;
</script>
Enter fullscreen mode Exit fullscreen mode

Inner workings of the for and while loops:

Both loops add list items three times each. The for loop runs a fixed number of iterations, while the while loop continues as long as the condition is true.

Functions:

Two methods — the standard function keyword or the arrow () => method.
Example:

<button onclick="greetUser()">Click to Greet</button>
<p id="message"></p>
<script>
  function greetUser() {
    let name = "Visitor";
    document.getElementById("message").textContent = "Welcome, " + name + "!";
  }
</script>
Enter fullscreen mode Exit fullscreen mode

Arrow function method of creating functions:

<button id="greetBtn">Click to Greet</button>
<p id="message"></p>
<script>
  const greetUser = () => {
    let name = "Visitor";
    document.getElementById("message").textContent = "Welcome, " + name + "!";
  };
  document.getElementById("greetBtn").addEventListener("click", greetUser);
</script>
Enter fullscreen mode Exit fullscreen mode

Objects:

Objects are key–value pairs. The value of the variable is structured data accessed using dot notation.

<p id="userInfo"></p>
<script>
  let user = {
    name: "Jane Doe",
    role: "Admin",
    email: "jane@techworld.com"
  };
  document.getElementById("userInfo").textContent =
    user.name + " (" + user.role + ") - " + user.email;
</script>
Enter fullscreen mode Exit fullscreen mode

Events:

Events respond to user actions like clicks or input changes.

<button id="changeBtn">Change Color</button>
<script>
  let btn = document.getElementById("changeBtn");
  btn.addEventListener("click", () => {
    document.body.style.backgroundColor = "lightblue";
  });
</script>
Enter fullscreen mode Exit fullscreen mode

DOM Manipulation:

DOM stands for Document Object Model — the main way JavaScript interacts with HTML elements.

<h2 id="pageTitle">Welcome!</h2>
<button id="updateBtn">Update Title</button>
<script>
  document.getElementById("updateBtn").addEventListener("click", () => {
    let title = document.getElementById("pageTitle");
    title.textContent = "JavaScript DOM Manipulation in Action!";
    title.style.color = "green";
  });
</script>
Enter fullscreen mode Exit fullscreen mode

Asynchronous JavaScript:

Handles delays with callbacks, promises, and async/await.

<p id="output">Starting...</p>
<script>
  setTimeout(() => {
    document.getElementById("output").textContent = "setTimeout: Runs after 2s";
  }, 2000);

  let count = 0;
  let timer = setInterval(() => {
    count++;
    console.log("setInterval count:", count);
    if (count === 3) clearInterval(timer);
  }, 1000);

  let loadData = new Promise((resolve) => {
    setTimeout(() => resolve("Promise: Data loaded!"), 3000);
  });

  async function showData() {
    try {
      let result = await loadData;
      document.getElementById("output").textContent = result;
    } catch (error) {
      document.getElementById("output").textContent = "Error occurred!";
    }
  }

  showData();
</script>
Enter fullscreen mode Exit fullscreen mode

Modules:

Reusable JS files imported/exported.

// message.js
export function greet(name) {
  return `Welcome, ${name}!`;
}

// main.js
import { greet } from "./message.js";
document.getElementById("msg").textContent = greet("Jane");

<p id="msg"></p>
<script type="module" src="main.js"></script>
Enter fullscreen mode Exit fullscreen mode

Libraries:

Prebuilt JavaScript code used to simplify tasks — often added via CDN, locally, or through npm.
Example using Lodash:

<p id="result"></p>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script>
  let numbers = [10, 20, 30, 40];
  let sum = _.sum(numbers);
  document.getElementById("result").textContent = "Total: " + sum;
</script>
Enter fullscreen mode Exit fullscreen mode

Output:

javascript
Total: 100

We’ve come to the end of this short but detailed lesson. I hope you had a good time studying this guide. If you have questions about programming, feel free to reach out. I’ll also welcome your suggestions. Programming should be simple, and I’m doing my best to make sure that idea becomes a reality for everyone.

Top comments (0)