It is very abstract. JavaScript is a way to program things in the browser, it’s not for designing, for laying out things visually in a browser.
Browsers provide a whole host of functionality to manipulate how they work via JS, but this functionality is useless if you don’t know how to use JS. So learning how to use JS is a prerequisite, and yes, it will seem abstract. It is a programming language, it’s just a [complex] tool that, in this case, allows you to manipulate something much more complex (the browser itself).
For example, regex: HTML lets you validate form fields (eg if you use <input type="email"
and a user types something that isn’t an email, the browser will show the input field is invalid). But maybe you need something more robust – say you’re validating credit card input, and you want to tell the user what kind of card (Visa, MasterCard etc) they’re using based on what they’ve currently typed. So you write a small JS program, which takes a string as input, and returns a list of possible cards
// Given a string of digits, return an array
// or possible credit card issuers:
function iinChecker (input) {
// Helper function that returns true if current
// input matches a given regex pattern:
const test = (regexPattern) => regexPattern.test(input);
// If the test returns true, the current
// branch returns a list of possible CC issuers.
switch (true) {
case test(/^4/):
return ["Visa"]
case test(/^5/):
return ["Diners Club", "Maestro", "MasterCard"];
case test(/^5[45]/):
return ["Diners Club"];
case test(/^5[0678]/):
return ["Maestro"];
case test(/^5[1-5]/):
return ["MasterCard"];
// ...and so and so forth
}
}
This, by itself, doesn’t interface with anything you can see in the browser. So there is a second part, where I use the JS functions provided by the browser to allow me to access it:
// Grab some elements in the browser by
// selecting them by their class names;
// the input field itself + a place to put output:
const ccinput = document.querySelector(".ccinput");
const ccissuer = document.querySelector(".ccissuer");
// Every time a user types a character,
// print the current list of possible issuers:
ccinput.addEventListener("keyup", (e) => {
ccissuer.textContent = iinChecker(e.target.value).join(", ");
});
So that will have looked like gibberish, but it’s just an illustration of how you need to know how the programming language works. You’re currently working through learning regex: all the above is doing is running function that maps a string to an array of strings by testing the string using regex.