JavaScript шпаргалка — это быстрый справочник по современному JavaScript (ES6+). Здесь собраны самые полезные конструкции для фронтенд и бэкенд разработки.
Основной синтаксис ES6+
Переменные и объявления
// Переменные
let name = 'Иван'; // Изменяемая
const age = 30; // Константа
var old = 'не использовать'; // Устаревший
// Шаблонные строки
const message = Привет, ${name}! Тебе ${age} лет;
// Стрелочные функции
const sum = (a, b) => a + b;
const square = x => x * x;
const greet = (name) => {
return Hello, ${name};
};
// Деструктуризация
const user = { name: 'Иван', age: 30 };
const { name, age } = user;
const arr = [1, 2, 3];
const [first, second] = arr;
// Spread и Rest
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1,2,3,4]
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // {a:1,b:2,c:3}
const rest = (...args) => args; // Rest параметры
Работа с массивами
// Создание
const arr = [1, 2, 3];
const arr2 = new Array(5).fill(0); // [0,0,0,0,0]
// Добавление/удаление
arr.push(4); // [1,2,3,4] - в конец
arr.unshift(0); // [0,1,2,3,4] - в начало
arr.pop(); // Удаляет последний
arr.shift(); // Удаляет первый
// Поиск
arr.indexOf(2); // 1
arr.includes(2); // true
arr.find(x => x > 2); // 3
arr.findIndex(x => x > 2); // 2
// Фильтрация
const filtered = arr.filter(x => x > 1); // [2,3,4]
// Преобразование
const doubled = arr.map(x => x * 2); // [0,2,4,6,8]
const sum = arr.reduce((acc, x) => acc + x, 0); // 10
// Проверка
const allPositive = arr.every(x => x >= 0); // true
const hasPositive = arr.some(x => x > 0); // true
// Сортировка
arr.sort((a, b) => a - b); // По возрастанию
arr.sort((a, b) => b - a); // По убыванию
// Итерация
arr.forEach(x => console.log(x));
for (const item of arr) {
console.log(item);
for (const [index, item] of arr.entries()) {
console.log(index, item);
// Уникальные значения
const unique = [...new Set([1,2,2,3])]; // [1,2,3]
Работа с объектами
// Создание
const obj = { name: 'Иван', age: 30 };
const key = 'name';
const obj2 = { [key]: 'Иван' }; // Вычисляемые свойства
// Доступ
obj.name; // 'Иван'
obj['name']; // 'Иван'
const { name, age } = obj;
// Добавление/удаление
obj.city = 'Moscow';
delete obj.city;
// Проверка
'name' in obj; // true
obj.hasOwnProperty('name'); // true
// Преобразование
const keys = Object.keys(obj); // ['name','age']
const values = Object.values(obj); // ['Иван',30]
const entries = Object.entries(obj); // [['name','Иван'],['age',30]]
const fromEntries = Object.fromEntries(entries); // obj
// Копирование
const copy = { ...obj };
const copy2 = Object.assign({}, obj);
// Итерация
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key, obj[key]);
Object.entries(obj).forEach(([key, value]) => {
console.log(key, value);
});
Работа с DOM
// Поиск элементов
const el = document.getElementById('id');
const els = document.querySelectorAll('.class');
const first = document.querySelector('.class');
const byClass = document.getElementsByClassName('class');
// Создание элементов
const div = document.createElement('div');
div.textContent = 'Привет';
div.innerHTML = 'Привет';
div.className = 'container';
div.classList.add('active');
div.classList.remove('hidden');
div.classList.toggle('visible');
div.id = 'unique-id';
div.setAttribute('data-attr', 'value');
div.dataset.attr = 'value'; // data-attr
// Вставка элементов
document.body.appendChild(div);
document.body.prepend(div);
document.body.insertBefore(div, referenceNode);
referenceNode.replaceWith(div);
// Удаление
div.remove();
// Работа с содержимым
div.innerHTML = 'Текст';
div.textContent = 'Только текст';
const html = div.innerHTML;
const text = div.textContent;
// Стили
div.style.color = 'red';
div.style.backgroundColor = 'blue';
div.style.display = 'none';
// События
element.addEventListener('click', (event) => {
console.log('Clicked!', event.target);
});
element.removeEventListener('click', handler);
// Популярные события
'click', 'submit', 'input', 'change', 'focus', 'blur'
'mousedown', 'mouseup', 'mouseover', 'mouseout'
'keydown', 'keyup', 'keypress'
'scroll', 'resize', 'load', 'DOMContentLoaded'
Промисы и асинхронность
// Создание промиса
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Успех');
// reject('Ошибка');
}, 1000);
});
// Использование
promise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log('Завершено'));
// Promise.all - все промисы
const p1 = fetch('/api/users');
const p2 = fetch('/api/products');
Promise.all([p1, p2])
.then(([res1, res2]) => console.log(res1, res2));
// Promise.race - первый завершённый
Promise.race([p1, p2])
.then(result => console.log(result));
// Promise.allSettled - все завершённые
Promise.allSettled([p1, p2])
.then(results => console.log(results));
// Async/Await
async function fetchData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Ошибка:', error);
throw error;
// Использование
const data = await fetchData();
Работа с JSON
// Преобразование
const json = JSON.stringify({ name: 'Иван', age: 30 });
const obj = JSON.parse(json);
// Форматирование
const pretty = JSON.stringify(obj, null, 2);
// Обработка ошибок
try {
const data = JSON.parse(malformedJson);
} catch (error) {
console.error('Invalid JSON', error);
Работа с датами
// Создание
const now = new Date();
const date = new Date('2026-07-19');
const timestamp = new Date(2026, 6, 19, 14, 30);
// Получение
const year = now.getFullYear();
const month = now.getMonth(); // 0-11
const day = now.getDate();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const dayOfWeek = now.getDay(); // 0-6 (воскресенье=0)
const timestamp = now.getTime();
// Форматирование
const formatted = now.toLocaleDateString('ru-RU'); // 19.07.2026
const datetime = now.toLocaleString('ru-RU');
const iso = now.toISOString(); // 2026-07-19T11:30:00.000Z
// Временные метки
const past = new Date(now.getTime() - 24 * 60 * 60 * 1000); // вчера
const future = new Date(now.setDate(now.getDate() + 7)); // через неделю
// Разница
const diff = future - now;
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
Работа с localStorage
// Сохранение
localStorage.setItem('key', 'value');
localStorage.setItem('user', JSON.stringify({ name: 'Иван' }));
// Чтение
const value = localStorage.getItem('key');
const user = JSON.parse(localStorage.getItem('user'));
// Удаление
localStorage.removeItem('key');
localStorage.clear();
// SessionStorage (аналогично, но до закрытия вкладки)
sessionStorage.setItem('key', 'value');
Работа с Fetch API
// GET запрос
fetch('https://api.example.com/users')
.then(response => {
if (!response.ok) {
throw new Error('HTTP error ' + response.status);
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
// POST запрос
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
},
body: JSON.stringify({ name: 'Иван', email: 'ivan@example.com' })
})
.then(response => response.json())
.then(data => console.log(data));
// С async/await
async function fetchUsers() {
const response = await fetch('/api/users');
if (!response.ok) throw new Error('Network error');
const data = await response.json();
return data;
Полезные сниппеты
// Дебаунс
function debounce(fn, delay) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
// Троттлинг
function throttle(fn, limit) {
let inThrottle;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
};
// Глубокое копирование
const deepCopy = obj => JSON.parse(JSON.stringify(obj));
// Генерация случайного ID
const randomId = () => Math.random().toString(36).substring(2, 10);
// Проверка на пустой объект
const isEmpty = obj => Object.keys(obj).length === 0;
// Задержка (sleep)
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
// Копирование в буфер обмена
navigator.clipboard.writeText('text');
// Открытие в новой вкладке
window.open('https://example.com', '_blank');
// Прокрутка к элементу
element.scrollIntoView({ behavior: 'smooth' });
Итог
Эта шпаргалка покрывает все основные конструкции современного JavaScript. Используйте её как быстрый справочник в повседневной работе.