A comprehensive guide to essential JavaScript functions and modern ES6+ features. Your one-stop reference for data manipulation, DOM interaction, asynchronous operations, and more.
Fundamental functions for scripting, data type conversion, and URI handling.
console.log("Hello, Debugger!");
parseInt("42.5em", 10); // Returns 42
parseFloat("3.14 is pi"); // Returns 3.14
isNaN("Hello"); // true
isFinite(1/0); // false
const uri = "my test.asp?name=ståle";\nconst encoded = encodeURI(uri);
const component = "https://example.com/?a=1&b=2";\nconst encodedComp = encodeURIComponent(component);
Functions for manipulating and inspecting strings.
const str = "hello";\nconsole.log(str.length); // 5
"JavaScript".slice(0, 4); // "Java"
"JavaScript".substring(4, 10); // "Script"
"apple,banana,cherry".split(","); // ["apple", "banana", "cherry"]
"Hello World".replace("World", "JavaScript");
"Hello".toUpperCase(); // "HELLO"
" hello ".trim(); // "hello"
"Hello World".includes("World"); // true
"filename.pdf".endsWith(".pdf"); // true
"5".padStart(2, "0"); // "05"
"hello".charAt(1); // "e"
Functions for working with numbers and performing mathematical operations.
const num = 123.456;\nnum.toFixed(2); // "123.46"
const num = 123.456;\nnum.toPrecision(4); // "123.5"
Math.round(4.7); // 5\nMath.ceil(4.2); // 5\nMath.floor(4.7); // 4
Math.random(); // e.g., 0.123456789
Math.max(10, 20, -5); // 20
Math.pow(2, 3); // 8
A comprehensive list of methods for iterating over and transforming arrays.
const arr = [1, 2];\narr.push(3); // arr is now [1, 2, 3]\narr.pop(); // returns 3, arr is [1, 2]
const arr = [1, 2];\narr.shift(); // returns 1, arr is [2]\narr.unshift(0); // arr is now [0, 2]
["a", "b"].forEach(item => console.log(item));
const doubled = [1, 2, 3].map(num => num * 2); // [2, 4, 6]
const evens = [1, 2, 3, 4].filter(num => num % 2 === 0); // [2, 4]
const sum = [1, 2, 3].reduce((total, num) => total + num, 0); // 6
const users = [{id:1, name:"John"}, {id:2, name:"Jane"}];\nusers.find(u => u.name === "Jane"); // {id:2, name:"Jane"}
[1, -5, 10].some(n => n < 0); // true\n[1, 5, 10].every(n => n > 0); // true
const fruits = ["apple", "banana", "cherry", "date"];\nfruits.slice(1, 3); // ["banana", "cherry"]
const arr = [1, 2, 5];\narr.splice(2, 0, 3, 4); // arr is now [1, 2, 3, 4, 5]
const arr1 = [1], arr2 = [2];\narr1.concat(arr2); // [1, 2]
["Hello", "World"].join(" "); // "Hello World"
const arr = [1, [2, 3]];\narr.flat(); // [1, 2, 3]\n\n[2, 3, 4].flatMap(x => [x, x*2]); // [2, 4, 3, 6, 4, 8]
Static methods for inspecting and manipulating objects.
Object.keys({a: 1, b: 2}); // ["a", "b"]
Object.values({a: 1, b: 2}); // [1, 2]
Object.entries({a: 1, b: 2}); // [["a", 1], ["b", 2]]
const target = {a: 1};\nconst source = {b: 2};\nObject.assign(target, source); // target is {a: 1, b: 2}
const obj = {prop: 42};\nObject.freeze(obj);\nobj.prop = 33; // Throws an error in strict mode
const person = {name: "John"};\nperson.hasOwnProperty("name"); // true
Modern JavaScript syntax for more readable, powerful, and asynchronous code.
const add = (a, b) => a + b;
const { name, age } = { name: "John", age: 30 };\nconst [first, second] = ["Apple", "Banana"];
const arr2 = [...arr1, 3, 4]; // Spread\nfunction sum(...numbers) { ... } // Rest
new Promise((resolve, reject) => { /* async code */ }) .then(result => { /* handle success */ }) .catch(error => { /* handle error */ }) .finally(() => { /* cleanup */ });
async function fetchData() {\n try {\n const response = await fetch(url);\n const data = await response.json();\n console.log(data);\n } catch (error) {\n console.error(error);\n }\n}
const street = user?.address?.street; // Returns undefined if user or address is null/undefined
const volume = null;\nconst safeVolume = volume ?? 50; // 50
class Car {\n constructor(brand) { this.brand = brand; }\n present() { return "I have a " + this.brand; }\n}\nconst myCar = new Car("Ford");
// In math.js export const add = (a, b) => a + b; // In main.js import { add } from './math.js';
Functions for interacting with the web page, handling user events, and using browser features.
const main = document.querySelector("#main");
myButton.addEventListener("click", handleClick);
element.classList.toggle("is-active");
link.setAttribute("href", "https://example.com");
const timerId = setTimeout(() => alert("Hi!"), 1000);
const intervalId = setInterval(() => console.log("tick"), 2000);
fetch("https://api.example.com/data")\n .then(response => response.json())\n .then(data => console.log(data));
localStorage.setItem("user", "John");\nconst user = localStorage.getItem("user");
Functions for parsing and creating JSON (JavaScript Object Notation) strings.
const user = { name: "John", id: 5 };\nconst jsonString = JSON.stringify(user); // '{"name":"John","id":5}'
const jsonString = '{"name":"John","id":5}';\nconst userObject = JSON.parse(jsonString);