Modern JS (ES6+): The Essentials
Stop writing legacy code. Master Arrow Functions, Async/Await and Destructuring that every senior dev uses today.
Sections9
🔤 Variables and Types
15 snippetsLanguage fundamentals for storage declaration and data type checking.
Constant Declaration
Declares an immutable constant with value "João". It cannot be reassigned after declaration and must be initialized at the same time.
const nome = "João"Variable Declaration (Block Scope)
Declares a variable with block scope. It can be reassigned and its value can be changed during program execution.
let idade = 25Old Declaration (Function Scope)
Declares a variable with function scope. Due to unexpected hoisting behaviors, it is generally recommended to avoid its use in favor of `let` or `const`.
var antigo = "evitar"Data Type Check
Returns a string indicating the data type of the operand. For strings, it returns "string".
typeof "texto"Numeric Type Check
Returns the string "number", indicating that the operand is an integer or floating-point number.
typeof 42Boolean Type Check
Returns the string "boolean", indicating a true (truthy) or false (falsy) value.
typeof trueNull Check (Historical Bug)
Returns the string "object". This is a historical bug in the JavaScript language specification that persists for compatibility.
typeof nullUndefined Check
Returns the string "undefined", indicating that a variable was declared but not assigned a value.
typeof undefinedSymbol Type Check
Returns the string "symbol". Creates a unique and immutable identifier, often used for object properties.
typeof Symbol()BigInt Type Check
Returns the string "bigint". Allows representing arbitrary-precision integers.
typeof 42nConvert to Number
Converts a string containing a number to the primitive type number (Float). If it fails, returns NaN.
Number("123")Convert to String
Converts any value to the primitive type string.
String(123)Boolean Conversion
Converts a value to the boolean primitive type. Truthy values (like 1) become true.
Boolean(1)Integer Parsing (Floating Point)
Reads the string and returns the first integer found up to the first non-numeric character.
parseInt("42px")Float Parsing (Decimal)
Reads the string and returns the first decimal number found until the end of the string.
parseFloat("3.14")📋 Arrays and Methods
18 snippetsEssential operations for data list manipulation, including creation, mutation, and iteration.
Array Literal Declaration
Creates a new array instance with the elements provided as arguments.
const arr = [1, 2, 3]Declaration via Constructor
Creates a new array using the constructor function. Works similarly to the literal.
const arr = new Array(1, 2, 3)Static Declaration
Creates a new array with elements passed as arguments, even if there is only one numeric argument.
const arr = Array.of(1, 2, 3)Array Filled with Value
Creates an array of size 5 and fills all positions with the value 0.
const arr = Array(5).fill(0)Add to End
Adds one or more elements to the end of the array and returns the new array length.
arr.push(4)Remove from End
Removes the last element from an array and returns that element.
arr.pop()Add to Start
Adds one or more elements to the beginning of the array and returns the new length.
arr.unshift(0)Remove from Start
Removes the first element from an array and returns that element.
arr.shift()Array Slice (Copy)
Returns a copy of a portion of an array into a new array, without modifying the original. The end index is exclusive.
arr.slice(1, 3)Insert/Remove (Mutation)
Change the contents of an array by adding new elements, removing existing elements, or both, without creating a new array.
arr.splice(1, 2)Iteration with Callback
Executes a provided function once for each array element.
arr.forEach(item => console.log(item))Mapeamento (Transformação)
Cria um novo array preenchido com os resultados da chamada de uma função fornecida em cada elemento.
arr.map(item => item * 2)Filtering
Creates a new array with all elements that pass the test implemented by the provided function.
arr.filter(item => item > 2)Reduction (Reduce)
Executes a reducer function on each array element, resulting in a single return value.
arr.reduce((acc, item) => acc + item, 0)Find First
Returns the value of the first element in the array that satisfies the provided test function.
arr.find(item => item > 2)Find Index
Returns the index of the first element in the array that satisfies the provided test function.
arr.findIndex(item => item > 2)Some Element Satisfies
Returns true if at least one element in the array satisfies the condition of the passed test function.
arr.some(item => item > 2)All Elements Satisfy
Returns true if all elements in the array satisfy the condition of the passed test function.
arr.every(item => item > 0)🏗️ Objects and Properties
18 snippetsManipulation of key-value data structures, including dynamic properties and utility methods.
Object Literal Declaration
Creates a new object containing key-value pairs.
const obj = { nome: "João", idade: 25 }Declaration via Constructor
Creates a new object using the global Object constructor function.
const obj = new Object()Object Without Prototype
Creates a new object with null as its prototype (it will not inherit properties from Object.prototype).
const obj = Object.create(null)Dot Notation Access
Accesses the "nome" property of the obj object.
obj.nomeBracket Notation Access
Accesses the "nome" property of the obj object using a string as a key.
obj["nome"]Variable Access
Accesses a property where the key name is stored in a variable.
obj.chaveDinamicaRemove Property
Removes a property from an object and returns true if the property existed and was removed.
delete obj.idadeGet Keys
Returns an array containing the own enumerable properties of an object, in the same order as a for...in loop.
Object.keys(obj)Get Values
Returns an array containing all the values of an object's own enumerable properties.
Object.values(obj)Get Entries (Key and Value)
Returns an array of [key, value] pairs for each enumerable own property of an object.
Object.entries(obj)Merge Objects
Copies all enumerable properties from one or more source objects to a target object.
Object.assign({}, obj1, obj2)Spread Operator (Object)
Allows an object to be expanded into a set of arguments.
{ ...obj1, ...obj2 }Freeze Object
Prevents new properties from being added, existing ones from being removed, or existing properties from being changed.
Object.freeze(obj)Seal Object
Prevents the addition of new properties and the removal of existing properties, but allows modification of existing property values.
Object.seal(obj)Computed Property
Allows defining the property name dynamically using an expression.
const obj = { [chave]: "valor" }Shorthand Method
Allows omitting the "function" keyword and the "function" keyword in the return when defining a method within an object.
metodo() { return "oi" }Getter
Defines a method that automatically returns a property when it is accessed.
get prop() { return this._prop }Setter
Defines a method that receives a value when the property is set, allowing data manipulation before assignment.
set prop(val) { this._prop = val }⚡ Modern Functions
9 snippetsAdvanced function declaration techniques, including arrow functions, currying, and parameter manipulation.
Function Declaration
Declares a named function that can be called by name. It is "hoisted" in the global scope.
function soma(a, b) { return a + b }Function Expression
Defines a function and assigns it to a variable. It is not "hoisted" and only becomes available after the declaration line.
const soma = function(a, b) { return a + b }Arrow Function
Defines an anonymous function with shorter syntax. It does not have its own `this`, `arguments`, `super`, or `new.target`.
const soma = (a, b) => a + bArrow Function Object Return
Uses parentheses around the arrow to return an object literal, as curly braces {} are interpreted as the function body.
const soma = (a, b) => ({ resultado: a + b })Rest Parameters
Allows representing an indefinite number of arguments as an array.
function soma(...numeros) { return numeros.reduce((a, b) => a + b, 0) }Spread Operator (Args)
Expands an array into a list of individual arguments to be passed to a function.
soma(...nums)Default Parameter
Defines a default value for a function parameter that will be used if the argument is not provided.
function saudar(nome = "Visitante") { return `Olá, ${nome}!` }Currying
Transforms a function that takes multiple arguments into a series of functions that each take a single argument.
const multiplicar = fator => num => num * fatorHigher-Order Function
A function that takes another function as an argument or returns a function.
const aplicar = (fn, valor) => fn(valor)⏱️ Asynchronous Programming
10 snippetsManaging non-blocking operations, Promises, Async/Await, and Fetch API.
Promise Constructor
Creates a Promise that will be resolved or rejected at some point in the future.
const promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Sucesso!"), 1000) })Success Handling
Registers a callback function to be executed when the Promise is resolved with a value.
promise.then(result => console.log(result))Error Handling
Registers a callback function to be executed when the Promise is rejected with a reason.
promise.catch(error => console.error(error))Finally Block
Registers a callback function to be executed when the Promise is settled (either resolved or rejected).
promise.finally(() => console.log("Finalizado"))Asynchronous Function
Declares a function that can contain await expressions that pause execution until the Promise is resolved.
async function buscarDados() { try { const response = await fetch("/api/dados") ... } }Promise.all
Returns a Promise that resolves when all of the promises in the iterable have resolved.
Promise.all([p1, p2, p3])Promise.race
Returns a Promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.
Promise.race([p1, p2])Promise.allSettled
Returns a Promise that resolves when all of the given promises are settled (either resolved or rejected).
Promise.allSettled([p1, p2])Promise.any
Returns a Promise that resolves as soon as one of the promises in the iterable resolves.
Promise.any([p1, p2])Fetch API
Web interface for initiating asynchronous HTTP requests.
fetch('/api/users').then(res => res.json())🎯 Destructuring & Spread
14 snippetsElegant syntax for extracting values from arrays and objects, and for spreading elements.
Array Destructuring
Extracts values from arrays and assigns them to corresponding variables.
const [a, b, c] = [1, 2, 3]Array Destructuring with Rest
Captures the first value into a variable and the rest into a new array.
const [primeiro, ...resto] = [1, 2, 3, 4]Array Destructuring Ignoring
Ignores desired values at the initial position of destructuring.
const [, , terceiro] = [1, 2, 3]Default Value
Sets a default value for a variable if the corresponding value in the array is undefined.
const [x = 0] = []Object Destructuring
Extracts properties from objects and assigns them to variables with same or different names.
const { nome, idade } = { nome: "João", idade: 25 }Renaming Property
Allows the target variable to have a different name than the object property.
const { nome: userName, idade: age } = objDefault Value in Object
Defines a default value for a property if the object does not have the property or the value is undefined.
const { nome = "Anônimo" } = {}Rest Operator in Object
Captures all remaining properties of the object into a new variable.
const { nome, ...resto } = objNested Destructuring
Allows extracting values from objects within other objects.
const { usuario: { nome } } = dataArray Spread Operator
Allows creating a copy of an array or adding new elements.
const arr2 = [...arr1, 3, 4]Object Spread Operator
Creates a copy of an object and allows overwriting properties.
const obj2 = { ...obj1, c: 3 }Shallow Copy
Creates a new object instance with identical properties.
const copia = { ...original }Object Merge
Creates a new object with properties from both, where obj2's properties overwrite obj1's.
const merged = { ...obj1, ...obj2 }Parameter Destructuring
Allows extracting properties directly from function arguments.
function processar({ nome, idade }) { ... }🚀 ES6+ Features
11 snippetsECMAScript 2015+ features including templates, modules, and classes.
Template Literals
Allows multi-line strings and expression interpolation using backticks (`) instead of quotes.
const mensagem = `Olá, ${nome}!`Multiline Template
Allows creating strings that span multiple lines without needing newline escape characters.
const multiline = `Linha 1
Linha 2`Named Export
Exports a specific function to be imported by name in another module.
const soma = (a, b) => a + bDefault Export
Exports a default function for a module, which can be imported with any name.
export default function() {}Named Import
Imports a specific function exported by name from a module.
import { soma } from './utils.js'Default Import
Imports the default exported value from a module.
import utils from './utils.js'Namespace Import
Imports all content from a module as a single object with properties.
import * as utils from './utils.js'Class Definition
Defines a class to create objects with properties and methods.
class Pessoa { constructor(nome) { this.nome = nome } }Class Inheritance
Allows creating a new class that inherits properties and methods from a parent class.
class Funcionario extends Pessoa { constructor(nome, cargo) { super(nome); ... } }Unique Symbol
Creates a symbolic and unique primitive value, which usually serves as a property key.
const id = Symbol('id')Iterator (For...of)
Allows iterating over data that implements the iterator protocol.
for (const val of obj) console.log(val)🌐 DOM Manipulation
20 snippetsInteracting with HTML document and CSS structure.
Select by ID
Returns the element that matches the provided ID on the page.
document.getElementById('meu-id')Select by CSS Selector
Returns the first element within the document that matches the specified CSS selector.
document.querySelector('.classe')Select All
Returns a static NodeList with all elements that match the CSS selector.
document.querySelectorAll('div')Select by Class
Returns an HTMLCollection of elements with the provided class.
document.getElementsByClassName('classe')Select by Tag
Returns an HTMLCollection of elements with the provided tag.
document.getElementsByTagName('p')Set Safe Text
Sets the text content of the node. Escapes HTML characters to prevent script injection.
element.textContent = "Texto"Set HTML
Sets the inner HTML of the element. Does not escape characters, allowing valid HTML.
element.innerHTML = "<strong>HTML</strong>"Set Input Value
Sets the value of a form element (input, select, textarea).
element.value = "valor"Get Attribute
Returns the value of a specified HTML attribute.
element.getAttribute('data-id')Set Attribute
Sets the value of a specified HTML attribute.
element.setAttribute('data-id', '123')Set Inline Style
Sets the CSS style directly on the element as a style property.
element.style.color = 'red'Add Class
Adds one or more CSS classes to the specified element.
element.classList.add('ativa')Remove Class
Removes one or more CSS classes from the specified element.
element.classList.remove('ativa')Toggle Class
Adds the class if it doesn't exist, or removes it if it does.
element.classList.toggle('ativa')Check Class
Returns true if the element has the specified class.
element.classList.contains('ativa')Create Element
Creates a new HTML element with the specified tag.
const div = document.createElement('div')Add to DOM
Adds a node as the last child of the parent element.
document.body.appendChild(div)Remove Element
Removes the element from the DOM.
element.remove()Add Event
Registers a callback function to be executed whenever the event occurs.
element.addEventListener('click', (e) => { ... })Remove Event
Removes a previously registered event listener.
element.removeEventListener('click', handler)🐛 Debugging & Tools
13 snippetsConsole techniques and methods for diagnostics and performance analysis.
Basic Log
Logs a message to the debug console.
console.log('mensagem')Error Log
Logs an error message to the console with a red icon.
console.error('erro')Warning Log
Logs a warning message to the console with a yellow icon.
console.warn('aviso')Log de Informação
Registra uma mensagem informativa no console com ícone azul.
console.info('info')Data Table
Displays a tabular data table in the console for easy viewing.
console.table([{a:1}, {a:2}])Group Logs
Starts a log group in the console for visual organization.
console.group('grupo')Close Group
Ends the previously started log group.
console.groupEnd()Start Timer
Starts a timer in the console. The elapsed time is calculated from the call until `timeEnd`.
console.time('timer')End Timer
Stops the timer and prints the elapsed time to the console.
console.timeEnd('timer')Breakpoint
Pauses script execution and opens the browser's developer tools.
function debugar() { debugger }Precise Timestamp
Returns a high-precision timestamp value (in milliseconds) since the epoch.
performance.now()Performance Mark
Creates a high-level timestamp mark in the performance timeline.
performance.mark('start')Measure Performance
Creates a measurement between two time marks.
performance.measure('diff', 'start', 'end')Related cheatsheets
p { color: blue; }CSS3: The Visual Guide
Stop guessing display or position values. Master Flexbox, Grid and responsive layouts visually in seconds.
<!DOCTYPE html>HTML5: Semantic Tags & SEO
Google hates <div>. Use the right semantic structure to rank your site at the top without spending on ads.