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"Stop writing legacy code. Master Arrow Functions, Async/Await and Destructuring that every senior dev uses today.
Language fundamentals for storage declaration and data type checking.
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"Declares a variable with block scope. It can be reassigned and its value can be changed during program execution.
let idade = 25Declares 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"Returns a string indicating the data type of the operand. For strings, it returns "string".
typeof "texto"Returns the string "number", indicating that the operand is an integer or floating-point number.
typeof 42Returns the string "boolean", indicating a true (truthy) or false (falsy) value.
typeof trueReturns the string "object". This is a historical bug in the JavaScript language specification that persists for compatibility.
typeof nullReturns the string "undefined", indicating that a variable was declared but not assigned a value.
typeof undefinedReturns the string "symbol". Creates a unique and immutable identifier, often used for object properties.
typeof Symbol()Returns the string "bigint". Allows representing arbitrary-precision integers.
typeof 42nConverts a string containing a number to the primitive type number (Float). If it fails, returns NaN.
Number("123")Converts any value to the primitive type string.
String(123)Converts a value to the boolean primitive type. Truthy values (like 1) become true.
Boolean(1)Reads the string and returns the first integer found up to the first non-numeric character.
parseInt("42px")Reads the string and returns the first decimal number found until the end of the string.
parseFloat("3.14")Essential operations for data list manipulation, including creation, mutation, and iteration.
Creates a new array instance with the elements provided as arguments.
const arr = [1, 2, 3]Creates a new array using the constructor function. Works similarly to the literal.
const arr = new Array(1, 2, 3)Creates a new array with elements passed as arguments, even if there is only one numeric argument.
const arr = Array.of(1, 2, 3)Creates an array of size 5 and fills all positions with the value 0.
const arr = Array(5).fill(0)Adds one or more elements to the end of the array and returns the new array length.
arr.push(4)Removes the last element from an array and returns that element.
arr.pop()Adds one or more elements to the beginning of the array and returns the new length.
arr.unshift(0)Removes the first element from an array and returns that element.
arr.shift()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)Change the contents of an array by adding new elements, removing existing elements, or both, without creating a new array.
arr.splice(1, 2)Executes a provided function once for each array element.
arr.forEach(item => console.log(item))Cria um novo array preenchido com os resultados da chamada de uma função fornecida em cada elemento.
arr.map(item => item * 2)Creates a new array with all elements that pass the test implemented by the provided function.
arr.filter(item => item > 2)Executes a reducer function on each array element, resulting in a single return value.
arr.reduce((acc, item) => acc + item, 0)Returns the value of the first element in the array that satisfies the provided test function.
arr.find(item => item > 2)Returns the index of the first element in the array that satisfies the provided test function.
arr.findIndex(item => item > 2)Returns true if at least one element in the array satisfies the condition of the passed test function.
arr.some(item => item > 2)Returns true if all elements in the array satisfy the condition of the passed test function.
arr.every(item => item > 0)Manipulation of key-value data structures, including dynamic properties and utility methods.
Creates a new object containing key-value pairs.
const obj = { nome: "João", idade: 25 }Creates a new object using the global Object constructor function.
const obj = new Object()Creates a new object with null as its prototype (it will not inherit properties from Object.prototype).
const obj = Object.create(null)Accesses the "nome" property of the obj object.
obj.nomeAccesses the "nome" property of the obj object using a string as a key.
obj["nome"]Accesses a property where the key name is stored in a variable.
obj.chaveDinamicaRemoves a property from an object and returns true if the property existed and was removed.
delete obj.idadeReturns an array containing the own enumerable properties of an object, in the same order as a for...in loop.
Object.keys(obj)Returns an array containing all the values of an object's own enumerable properties.
Object.values(obj)Returns an array of [key, value] pairs for each enumerable own property of an object.
Object.entries(obj)Copies all enumerable properties from one or more source objects to a target object.
Object.assign({}, obj1, obj2)Allows an object to be expanded into a set of arguments.
{ ...obj1, ...obj2 }Prevents new properties from being added, existing ones from being removed, or existing properties from being changed.
Object.freeze(obj)Prevents the addition of new properties and the removal of existing properties, but allows modification of existing property values.
Object.seal(obj)Allows defining the property name dynamically using an expression.
const obj = { [chave]: "valor" }Allows omitting the "function" keyword and the "function" keyword in the return when defining a method within an object.
metodo() { return "oi" }Defines a method that automatically returns a property when it is accessed.
get prop() { return this._prop }Defines a method that receives a value when the property is set, allowing data manipulation before assignment.
set prop(val) { this._prop = val }Advanced function declaration techniques, including arrow functions, currying, and parameter manipulation.
Declares a named function that can be called by name. It is "hoisted" in the global scope.
function soma(a, b) { return a + b }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 }Defines an anonymous function with shorter syntax. It does not have its own `this`, `arguments`, `super`, or `new.target`.
const soma = (a, b) => a + bUses 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 })Allows representing an indefinite number of arguments as an array.
function soma(...numeros) { return numeros.reduce((a, b) => a + b, 0) }Expands an array into a list of individual arguments to be passed to a function.
soma(...nums)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}!` }Transforms a function that takes multiple arguments into a series of functions that each take a single argument.
const multiplicar = fator => num => num * fatorA function that takes another function as an argument or returns a function.
const aplicar = (fn, valor) => fn(valor)Managing non-blocking operations, Promises, Async/Await, and Fetch API.
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) })Registers a callback function to be executed when the Promise is resolved with a value.
promise.then(result => console.log(result))Registers a callback function to be executed when the Promise is rejected with a reason.
promise.catch(error => console.error(error))Registers a callback function to be executed when the Promise is settled (either resolved or rejected).
promise.finally(() => console.log("Finalizado"))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") ... } }Returns a Promise that resolves when all of the promises in the iterable have resolved.
Promise.all([p1, p2, p3])Returns a Promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.
Promise.race([p1, p2])Returns a Promise that resolves when all of the given promises are settled (either resolved or rejected).
Promise.allSettled([p1, p2])Returns a Promise that resolves as soon as one of the promises in the iterable resolves.
Promise.any([p1, p2])Web interface for initiating asynchronous HTTP requests.
fetch('/api/users').then(res => res.json())Elegant syntax for extracting values from arrays and objects, and for spreading elements.
Extracts values from arrays and assigns them to corresponding variables.
const [a, b, c] = [1, 2, 3]Captures the first value into a variable and the rest into a new array.
const [primeiro, ...resto] = [1, 2, 3, 4]Ignores desired values at the initial position of destructuring.
const [, , terceiro] = [1, 2, 3]Sets a default value for a variable if the corresponding value in the array is undefined.
const [x = 0] = []Extracts properties from objects and assigns them to variables with same or different names.
const { nome, idade } = { nome: "João", idade: 25 }Allows the target variable to have a different name than the object property.
const { nome: userName, idade: age } = objDefines a default value for a property if the object does not have the property or the value is undefined.
const { nome = "Anônimo" } = {}Captures all remaining properties of the object into a new variable.
const { nome, ...resto } = objAllows extracting values from objects within other objects.
const { usuario: { nome } } = dataAllows creating a copy of an array or adding new elements.
const arr2 = [...arr1, 3, 4]Creates a copy of an object and allows overwriting properties.
const obj2 = { ...obj1, c: 3 }Creates a new object instance with identical properties.
const copia = { ...original }Creates a new object with properties from both, where obj2's properties overwrite obj1's.
const merged = { ...obj1, ...obj2 }Allows extracting properties directly from function arguments.
function processar({ nome, idade }) { ... }ECMAScript 2015+ features including templates, modules, and classes.
Allows multi-line strings and expression interpolation using backticks (`) instead of quotes.
const mensagem = `Olá, ${nome}!`Allows creating strings that span multiple lines without needing newline escape characters.
const multiline = `Linha 1Linha 2`Exports a specific function to be imported by name in another module.
const soma = (a, b) => a + bExports a default function for a module, which can be imported with any name.
export default function() {}Imports a specific function exported by name from a module.
import { soma } from './utils.js'Imports the default exported value from a module.
import utils from './utils.js'Imports all content from a module as a single object with properties.
import * as utils from './utils.js'Defines a class to create objects with properties and methods.
class Pessoa { constructor(nome) { this.nome = nome } }Allows creating a new class that inherits properties and methods from a parent class.
class Funcionario extends Pessoa { constructor(nome, cargo) { super(nome); ... } }Creates a symbolic and unique primitive value, which usually serves as a property key.
const id = Symbol('id')Allows iterating over data that implements the iterator protocol.
for (const val of obj) console.log(val)Interacting with HTML document and CSS structure.
Returns the element that matches the provided ID on the page.
document.getElementById('meu-id')Returns the first element within the document that matches the specified CSS selector.
document.querySelector('.classe')Returns a static NodeList with all elements that match the CSS selector.
document.querySelectorAll('div')Returns an HTMLCollection of elements with the provided class.
document.getElementsByClassName('classe')Returns an HTMLCollection of elements with the provided tag.
document.getElementsByTagName('p')Sets the text content of the node. Escapes HTML characters to prevent script injection.
element.textContent = "Texto"Sets the inner HTML of the element. Does not escape characters, allowing valid HTML.
element.innerHTML = "<strong>HTML</strong>"Sets the value of a form element (input, select, textarea).
element.value = "valor"Returns the value of a specified HTML attribute.
element.getAttribute('data-id')Sets the value of a specified HTML attribute.
element.setAttribute('data-id', '123')Sets the CSS style directly on the element as a style property.
element.style.color = 'red'Adds one or more CSS classes to the specified element.
element.classList.add('ativa')Removes one or more CSS classes from the specified element.
element.classList.remove('ativa')Adds the class if it doesn't exist, or removes it if it does.
element.classList.toggle('ativa')Returns true if the element has the specified class.
element.classList.contains('ativa')Creates a new HTML element with the specified tag.
const div = document.createElement('div')Adds a node as the last child of the parent element.
document.body.appendChild(div)Removes the element from the DOM.
element.remove()Registers a callback function to be executed whenever the event occurs.
element.addEventListener('click', (e) => { ... })Removes a previously registered event listener.
element.removeEventListener('click', handler)Console techniques and methods for diagnostics and performance analysis.
Logs a message to the debug console.
console.log('mensagem')Logs an error message to the console with a red icon.
console.error('erro')Logs a warning message to the console with a yellow icon.
console.warn('aviso')Registra uma mensagem informativa no console com ícone azul.
console.info('info')Displays a tabular data table in the console for easy viewing.
console.table([{a:1}, {a:2}])Starts a log group in the console for visual organization.
console.group('grupo')Ends the previously started log group.
console.groupEnd()Starts a timer in the console. The elapsed time is calculated from the call until `timeEnd`.
console.time('timer')Stops the timer and prints the elapsed time to the console.
console.timeEnd('timer')Pauses script execution and opens the browser's developer tools.
function debugar() { debugger }Returns a high-precision timestamp value (in milliseconds) since the epoch.
performance.now()Creates a high-level timestamp mark in the performance timeline.
performance.mark('start')Creates a measurement between two time marks.
performance.measure('diff', 'start', 'end')