User Tools

Site Tools


public:programming:javascript:js-for-people-who-dont-know-anything-about-frontend-but-did-other-stuff

JavaScript basics for people who know some stuff about programming, but never did frontend development (nor do they want to)

Most information here comes from https://developer.mozilla.org/ and https://www.w3schools.com/

Also, I have no idea what I'm doing. I have never ever touched frontend development, I hate it, but as of writing this page, I kinda need it for personal project.


Variables

Immutability

Things may change, or they may not:

let variable = 123;
const constant = 123;

Types

And they might have type:

// Number
let x = 123;

// BigInt
let x = 1234567890123456789012345n;
let x = BigInt(1234567890123456789012345)

// Strings
let x = "abc";

// Boolean
let x = true;

// Undefined
let x;

// Null
let x = null;

// Symbol
// This thing is weird. It basically makes a unique value if I understand that correctly
const s = Symbol();
// So this is false:
Symbol("foo") == Symbol("foo");

typeof keyword

You can check for type comparing them to strings:

// true
typeof "John Doe" == "string";

Conditions

if (something) {
} else {
}

Also, == checks only between values, while === checks if both values AND types are the same.


Loops

for (let i = 0; i < 1000; i++) {
    console.log(i);
}

Functions

Function block doesn't need ; at the end (i think?)

function functionName(parameters) {
}

DOM Manipulation

DOM stands for Document Object Model, which is basically the representation of HTML elements for interaction with JS.

HTML:
<span id="elementId">Old Content</span>

JS:
const element = document.getElementById('elementId');
element.textContent = "New Content";

Events

The stuff that triggers on button click and whatnot

element.addEventListener('eventType', (event) => {
});

For example:

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

    <script>
        document.getElementById('myButton').addEventListener('click', () => {
            alert('Button clicked!');
        });
    </script>
</body>
</html>

Promises

Basically handle value of async function after it returns

const fetchData = () => {
    return new Promise((resolve, reject) => {
        // Perform async operation
    });
};

const asyncFunction = async () => {
    try {
        const result = await fetchData();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
};

From https://github.com/mdn/dom-examples/blob/main/web-crypto/export-key/pkcs8.js :

window.crypto.subtle.generateKey(
    {
      name: "RSA-PSS",
      // Consider using a 4096-bit key for systems that require long-term security
      modulusLength: 2048,
      publicExponent: new Uint8Array([1, 0, 1]),
      hash: "SHA-256",
    },
    true,
    ["sign", "verify"]
  ).then((keyPair) => {
    const exportButton = document.querySelector(".pkcs8");
    exportButton.addEventListener("click", () => {
      exportCryptoKey(keyPair.privateKey);
    });

  });

Modules (import from other JS files)

// In module.js
export const myFunction = () => {
    // code
};

// In main.js
import { myFunction } from './module.js';

Templates

Basically define one string in another

const name = "World";
const greeting = `Hello, ${name}!`;

Security

TLDR

shit is fucked, dont write any user generated HTML into anything that renders on screen

Also, Firefox doesn't support “Trusted Types API”… https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API

Materials

Templates for security

Input sanitization

function sanitizeInput(input) {
    const element = document.createElement('div');
    element.innerText = input;
    return element.innerHTML;
}
const userInput = "<script>alert('XSS');</script>";
const sanitizedInput = sanitizeInput(userInput);
console.log(sanitizedInput); 

Content Security Policy (CSP)

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://trusted-cdn.com;">

Cookies for HTTP only (not JS)

document.cookie = "sessionId=abc123; HttpOnly";

Cookies over HTTPS only

document.cookie = "sessionId=abc123; Secure";

Escape user input

<body>
    <h1>Escaping User Input Example</h1>
    <div id="output"></div>
    <script>
        function escapeHtml(unsafe) {
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // Example user input
        let userInput = '<script>alert("XSS Attack!");</script>';
    document.getElementById('output').innerHTML = escapeHtml(userInput);
    </script>
</body>

Cool stuff

Crypto library built in basically all the browsers: https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API

public/programming/javascript/js-for-people-who-dont-know-anything-about-frontend-but-did-other-stuff.txt · Last modified: by mdukat