Javascript
Javascript
How to Javascript
This is the fastest way to reload the javascript shotgun, more weapon attachments are listed after.
Semicolons
Semicolons are optional in JavaScript, but itβs good practice to use them to avoid unexpected behavior.
let x = 10; // Semicolon used let y = 20 // Semicolon optional
Equality Checks
JavaScript has two types of equality checks: == (loose equality) and ===(strict equality). Always prefer ===.
console.log(5 == "5"); // true (loose equality) console.log(5 === "5"); // false (strict equality)
Functions
Functions can be declared using function, arrow functions , or as function expressions.
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
// Function expression
const add = function(a, b) {
return a + b;
};Hoisting
JavaScript hoists variable and function declarations to the top of their scope. This can lead to unexpected behavior.
console.log(x); // undefined (not an error) var x = 10;
Template Literals
Use backticks ( ` ) for template literals to embed variables and multi-line strings.
const name = "Alice";
console.log(`Hello, ${name}!`); // Hello, Alice!
// Multi-line string
const message = `
This is a
multi-line string
`;Promises and Async/Await
Promises and async/await are used to handle asynchronous operations.
// Using Promises
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Done!"), 1000);
});
promise.then(result => console.log(result)); // Done!
// Using async/await
async function fetchData() {
const result = await promise;
console.log(result); // Done!
}No system("cls")
JavaScript does not have a direct equivalent of system("cls"). Use console.clear() to clear the console.
console.clear(); // Clears the console
Modules
JavaScript uses import and export for modular code.
// Exporting
export const add = (a, b) => a + b;
// Importing
import { add } from './math.js';Destructuring
Destructuring allows you to unpack values from arrays or objects into variables.
// Array destructuring
const [a, b] = [1, 2];
// Object destructuring
const { name, age } = { name: "Alice", age: 25 };Spread and Rest Operators
The spread ( ... ) operator is used to expand elements, while the rest operator is used to collect them.
// Spread operator
const arr = [1, 2, 3];
const newArr = [...arr, 4]; // [1, 2, 3, 4]
// Rest operator
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}Syntax & Basics
Variables
// π¦ Variable declarations let mutableVar = 10; // Block-scoped, reassignable const immutableVar = 20; // Block-scoped, constant var functionScoped = 30; // β οΈ Avoid (hoisting, function scope)
Data Types
// π·οΈ Primitive types
const str = "text";
const num = 42;
const bool = true;
const nullVal = null;
const undefinedVal = undefined;
const symbol = Symbol('id');
// π§© Reference types
const obj = {a: 1};
const arr = [1, 2, 3];
const func = () => {};Conditionals
// π€ Decision making
if (score > 90) {
grade = 'A';
} else if (score > 75) {
grade = 'B';
} else {
grade = 'C';
}
// π Switch statement
switch(day) {
case 1: console.log('Monday'); break;
default: console.log('Unknown'); break;
}Loops
// π Iteration methods
for (let i=0; i<5; i++) { ... }
while (condition) { ... }
// π― Array operations
arr.forEach(item => { ... });
const newArr = arr.map(item => item * 2);Functions
// π Function types
function add(a, b) { return a + b; } // Declaration
const multiply = (a, b) => a * b; // Arrow function
// π Immediately Invoked
(() => { console.log('Running now!'); })();Template Literals
// π¨ String formatting
const name = 'Alice';
console.log(`Hello ${name}!`);
console.log(`Multi-line
string example`);Common Operations
DOM Manipulation
// π DOM interactions
const btn = document.querySelector('#submit');
const list = document.getElementById('items');
// βοΈ DOM modifications
btn.textContent = 'Click Me';
list.innerHTML = '<li>New Item</li>';Event Handling
// π±οΈ Event listeners
btn.addEventListener('click', handleClick);
// π― Delegation pattern
document.body.addEventListener('click', e => {
if (e.target.matches('.item')) {
handleItemClick(e.target);
}
});Client-Side Storage
// πΎ Storage methods
localStorage.setItem('key', JSON.stringify(data));
const saved = JSON.parse(localStorage.getItem('key'));
// πͺ Cookie handling
document.cookie = 'username=John; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/';Data Structures
Arrays
// πΆ Array operations const nums = [1, 2, 3]; nums.push(4); // [1,2,3,4] nums.splice(1, 1); // Remove at index 1 const sum = nums.reduce((acc, val) => acc + val, 0);
Sets
// π― Unique collections
const unique = new Set([1, 2, 2, 3]); // {1,2,3}Map
// πΊοΈ Key-value storage
const map = new Map();
map.set('key', 'value');Weak Collections
// πΈοΈ Garbage-collected maps
const weakMap = new WeakMap();
const objKey = {};
weakMap.set(objKey, 'private data');Object-Oriented JS
Classes
// ποΈ Class structure
class Person {
#privateField; // π Private field
constructor(name) {
this.name = name;
this.#privateField = 'secret';
}
static species = 'Homo sapiens'; // π§³ Static property
greet() {
console.log(`Hello ${this.name}`);
}
}Prototypes & Inheritance
// 𧬠Prototypal inheritance
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() { ... };
class Dog extends Animal {
bark() { ... }
}Context Binding
// π Binding context const boundFunc = obj.method.bind(obj); boundFunc.call(context); boundFunc.apply(context, args);
Asynchronous JS
Promises
// β³ Promise chain
fetch('url')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
.finally(() => cleanup());Async/Await
// π Async operations
async function fetchData() {
try {
const res = await fetch('url');
return await res.json();
} catch (err) {
handleError(err);
}
}Event Loop
β° Macrotasks: setTimeout, DOM events, I/O
Error Handling
try/catch
// π¨ Error handling
try {
riskyOperation();
} catch (err) {
console.error('Caught:', err.message);
} finally {
cleanup();
}Custom Errors
// π οΈ Custom error type
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}Why Solo Dev?
This reference website is not for beginners
Solo Dev is strictly for devs who already know the game and need a beautiful cheat sheet on their second monitor which looks better than GeeksforGeeks
this portion goes away when you shrink the screen ;)
