javascriptintermediate128 snippets

Modern JS (ES6+): The Essentials

Stop writing legacy code. Master Arrow Functions, Async/Await and Destructuring that every senior dev uses today.

Sections9
1

🔤 Variables and Types

15 snippets

Language 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.

javascript
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.

javascript
let idade = 25

Old 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`.

javascript
var antigo = "evitar"

Data Type Check

Returns a string indicating the data type of the operand. For strings, it returns "string".

javascript
typeof "texto"

Numeric Type Check

Returns the string "number", indicating that the operand is an integer or floating-point number.

javascript
typeof 42

Boolean Type Check

Returns the string "boolean", indicating a true (truthy) or false (falsy) value.

javascript
typeof true

Null Check (Historical Bug)

Returns the string "object". This is a historical bug in the JavaScript language specification that persists for compatibility.

javascript
typeof null

Undefined Check

Returns the string "undefined", indicating that a variable was declared but not assigned a value.

javascript
typeof undefined

Symbol Type Check

Returns the string "symbol". Creates a unique and immutable identifier, often used for object properties.

javascript
typeof Symbol()

BigInt Type Check

Returns the string "bigint". Allows representing arbitrary-precision integers.

javascript
typeof 42n

Convert to Number

Converts a string containing a number to the primitive type number (Float). If it fails, returns NaN.

javascript
Number("123")

Convert to String

Converts any value to the primitive type string.

javascript
String(123)

Boolean Conversion

Converts a value to the boolean primitive type. Truthy values (like 1) become true.

javascript
Boolean(1)

Integer Parsing (Floating Point)

Reads the string and returns the first integer found up to the first non-numeric character.

javascript
parseInt("42px")

Float Parsing (Decimal)

Reads the string and returns the first decimal number found until the end of the string.

javascript
parseFloat("3.14")
2

📋 Arrays and Methods

18 snippets

Essential operations for data list manipulation, including creation, mutation, and iteration.

Array Literal Declaration

Creates a new array instance with the elements provided as arguments.

javascript
const arr = [1, 2, 3]

Declaration via Constructor

Creates a new array using the constructor function. Works similarly to the literal.

javascript
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.

javascript
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.

javascript
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.

javascript
arr.push(4)

Remove from End

Removes the last element from an array and returns that element.

javascript
arr.pop()

Add to Start

Adds one or more elements to the beginning of the array and returns the new length.

javascript
arr.unshift(0)

Remove from Start

Removes the first element from an array and returns that element.

javascript
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.

javascript
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.

javascript
arr.splice(1, 2)

Iteration with Callback

Executes a provided function once for each array element.

javascript
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.

javascript
arr.map(item => item * 2)

Filtering

Creates a new array with all elements that pass the test implemented by the provided function.

javascript
arr.filter(item => item > 2)

Reduction (Reduce)

Executes a reducer function on each array element, resulting in a single return value.

javascript
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.

javascript
arr.find(item => item > 2)

Find Index

Returns the index of the first element in the array that satisfies the provided test function.

javascript
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.

javascript
arr.some(item => item > 2)

All Elements Satisfy

Returns true if all elements in the array satisfy the condition of the passed test function.

javascript
arr.every(item => item > 0)
3

🏗️ Objects and Properties

18 snippets

Manipulation of key-value data structures, including dynamic properties and utility methods.

Object Literal Declaration

Creates a new object containing key-value pairs.

javascript
const obj = { nome: "João", idade: 25 }

Declaration via Constructor

Creates a new object using the global Object constructor function.

javascript
const obj = new Object()

Object Without Prototype

Creates a new object with null as its prototype (it will not inherit properties from Object.prototype).

javascript
const obj = Object.create(null)

Dot Notation Access

Accesses the "nome" property of the obj object.

javascript
obj.nome

Bracket Notation Access

Accesses the "nome" property of the obj object using a string as a key.

javascript
obj["nome"]

Variable Access

Accesses a property where the key name is stored in a variable.

javascript
obj.chaveDinamica

Remove Property

Removes a property from an object and returns true if the property existed and was removed.

javascript
delete obj.idade

Get Keys

Returns an array containing the own enumerable properties of an object, in the same order as a for...in loop.

javascript
Object.keys(obj)

Get Values

Returns an array containing all the values of an object's own enumerable properties.

javascript
Object.values(obj)

Get Entries (Key and Value)

Returns an array of [key, value] pairs for each enumerable own property of an object.

javascript
Object.entries(obj)

Merge Objects

Copies all enumerable properties from one or more source objects to a target object.

javascript
Object.assign({}, obj1, obj2)

Spread Operator (Object)

Allows an object to be expanded into a set of arguments.

javascript
{ ...obj1, ...obj2 }

Freeze Object

Prevents new properties from being added, existing ones from being removed, or existing properties from being changed.

javascript
Object.freeze(obj)

Seal Object

Prevents the addition of new properties and the removal of existing properties, but allows modification of existing property values.

javascript
Object.seal(obj)

Computed Property

Allows defining the property name dynamically using an expression.

javascript
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.

javascript
metodo() { return "oi" }

Getter

Defines a method that automatically returns a property when it is accessed.

javascript
get prop() { return this._prop }

Setter

Defines a method that receives a value when the property is set, allowing data manipulation before assignment.

javascript
set prop(val) { this._prop = val }
4

⚡ Modern Functions

9 snippets

Advanced 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.

javascript
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.

javascript
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`.

javascript
const soma = (a, b) => a + b

Arrow Function Object Return

Uses parentheses around the arrow to return an object literal, as curly braces {} are interpreted as the function body.

javascript
const soma = (a, b) => ({ resultado: a + b })

Rest Parameters

Allows representing an indefinite number of arguments as an array.

javascript
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.

javascript
soma(...nums)

Default Parameter

Defines a default value for a function parameter that will be used if the argument is not provided.

javascript
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.

javascript
const multiplicar = fator => num => num * fator

Higher-Order Function

A function that takes another function as an argument or returns a function.

javascript
const aplicar = (fn, valor) => fn(valor)
5

⏱️ Asynchronous Programming

10 snippets

Managing 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.

javascript
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.

javascript
promise.then(result => console.log(result))

Error Handling

Registers a callback function to be executed when the Promise is rejected with a reason.

javascript
promise.catch(error => console.error(error))

Finally Block

Registers a callback function to be executed when the Promise is settled (either resolved or rejected).

javascript
promise.finally(() => console.log("Finalizado"))

Asynchronous Function

Declares a function that can contain await expressions that pause execution until the Promise is resolved.

javascript
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.

javascript
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.

javascript
Promise.race([p1, p2])

Promise.allSettled

Returns a Promise that resolves when all of the given promises are settled (either resolved or rejected).

javascript
Promise.allSettled([p1, p2])

Promise.any

Returns a Promise that resolves as soon as one of the promises in the iterable resolves.

javascript
Promise.any([p1, p2])

Fetch API

Web interface for initiating asynchronous HTTP requests.

javascript
fetch('/api/users').then(res => res.json())
6

🎯 Destructuring & Spread

14 snippets

Elegant syntax for extracting values from arrays and objects, and for spreading elements.

Array Destructuring

Extracts values from arrays and assigns them to corresponding variables.

javascript
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.

javascript
const [primeiro, ...resto] = [1, 2, 3, 4]

Array Destructuring Ignoring

Ignores desired values at the initial position of destructuring.

javascript
const [, , terceiro] = [1, 2, 3]

Default Value

Sets a default value for a variable if the corresponding value in the array is undefined.

javascript
const [x = 0] = []

Object Destructuring

Extracts properties from objects and assigns them to variables with same or different names.

javascript
const { nome, idade } = { nome: "João", idade: 25 }

Renaming Property

Allows the target variable to have a different name than the object property.

javascript
const { nome: userName, idade: age } = obj

Default Value in Object

Defines a default value for a property if the object does not have the property or the value is undefined.

javascript
const { nome = "Anônimo" } = {}

Rest Operator in Object

Captures all remaining properties of the object into a new variable.

javascript
const { nome, ...resto } = obj

Nested Destructuring

Allows extracting values from objects within other objects.

javascript
const { usuario: { nome } } = data

Array Spread Operator

Allows creating a copy of an array or adding new elements.

javascript
const arr2 = [...arr1, 3, 4]

Object Spread Operator

Creates a copy of an object and allows overwriting properties.

javascript
const obj2 = { ...obj1, c: 3 }

Shallow Copy

Creates a new object instance with identical properties.

javascript
const copia = { ...original }

Object Merge

Creates a new object with properties from both, where obj2's properties overwrite obj1's.

javascript
const merged = { ...obj1, ...obj2 }

Parameter Destructuring

Allows extracting properties directly from function arguments.

javascript
function processar({ nome, idade }) { ... }
7

🚀 ES6+ Features

11 snippets

ECMAScript 2015+ features including templates, modules, and classes.

Template Literals

Allows multi-line strings and expression interpolation using backticks (`) instead of quotes.

javascript
const mensagem = `Olá, ${nome}!`

Multiline Template

Allows creating strings that span multiple lines without needing newline escape characters.

javascript
const multiline = `Linha 1
Linha 2`

Named Export

Exports a specific function to be imported by name in another module.

javascript
const soma = (a, b) => a + b

Default Export

Exports a default function for a module, which can be imported with any name.

javascript
export default function() {}

Named Import

Imports a specific function exported by name from a module.

javascript
import { soma } from './utils.js'

Default Import

Imports the default exported value from a module.

javascript
import utils from './utils.js'

Namespace Import

Imports all content from a module as a single object with properties.

javascript
import * as utils from './utils.js'

Class Definition

Defines a class to create objects with properties and methods.

javascript
class Pessoa { constructor(nome) { this.nome = nome } }

Class Inheritance

Allows creating a new class that inherits properties and methods from a parent class.

javascript
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.

javascript
const id = Symbol('id')

Iterator (For...of)

Allows iterating over data that implements the iterator protocol.

javascript
for (const val of obj) console.log(val)
8

🌐 DOM Manipulation

20 snippets

Interacting with HTML document and CSS structure.

Select by ID

Returns the element that matches the provided ID on the page.

javascript
document.getElementById('meu-id')

Select by CSS Selector

Returns the first element within the document that matches the specified CSS selector.

javascript
document.querySelector('.classe')

Select All

Returns a static NodeList with all elements that match the CSS selector.

javascript
document.querySelectorAll('div')

Select by Class

Returns an HTMLCollection of elements with the provided class.

javascript
document.getElementsByClassName('classe')

Select by Tag

Returns an HTMLCollection of elements with the provided tag.

javascript
document.getElementsByTagName('p')

Set Safe Text

Sets the text content of the node. Escapes HTML characters to prevent script injection.

javascript
element.textContent = "Texto"

Set HTML

Sets the inner HTML of the element. Does not escape characters, allowing valid HTML.

javascript
element.innerHTML = "<strong>HTML</strong>"

Set Input Value

Sets the value of a form element (input, select, textarea).

javascript
element.value = "valor"

Get Attribute

Returns the value of a specified HTML attribute.

javascript
element.getAttribute('data-id')

Set Attribute

Sets the value of a specified HTML attribute.

javascript
element.setAttribute('data-id', '123')

Set Inline Style

Sets the CSS style directly on the element as a style property.

javascript
element.style.color = 'red'

Add Class

Adds one or more CSS classes to the specified element.

javascript
element.classList.add('ativa')

Remove Class

Removes one or more CSS classes from the specified element.

javascript
element.classList.remove('ativa')

Toggle Class

Adds the class if it doesn't exist, or removes it if it does.

javascript
element.classList.toggle('ativa')

Check Class

Returns true if the element has the specified class.

javascript
element.classList.contains('ativa')

Create Element

Creates a new HTML element with the specified tag.

javascript
const div = document.createElement('div')

Add to DOM

Adds a node as the last child of the parent element.

javascript
document.body.appendChild(div)

Remove Element

Removes the element from the DOM.

javascript
element.remove()

Add Event

Registers a callback function to be executed whenever the event occurs.

javascript
element.addEventListener('click', (e) => { ... })

Remove Event

Removes a previously registered event listener.

javascript
element.removeEventListener('click', handler)
9

🐛 Debugging & Tools

13 snippets

Console techniques and methods for diagnostics and performance analysis.

Basic Log

Logs a message to the debug console.

javascript
console.log('mensagem')

Error Log

Logs an error message to the console with a red icon.

javascript
console.error('erro')

Warning Log

Logs a warning message to the console with a yellow icon.

javascript
console.warn('aviso')

Log de Informação

Registra uma mensagem informativa no console com ícone azul.

javascript
console.info('info')

Data Table

Displays a tabular data table in the console for easy viewing.

javascript
console.table([{a:1}, {a:2}])

Group Logs

Starts a log group in the console for visual organization.

javascript
console.group('grupo')

Close Group

Ends the previously started log group.

javascript
console.groupEnd()

Start Timer

Starts a timer in the console. The elapsed time is calculated from the call until `timeEnd`.

javascript
console.time('timer')

End Timer

Stops the timer and prints the elapsed time to the console.

javascript
console.timeEnd('timer')

Breakpoint

Pauses script execution and opens the browser's developer tools.

javascript
function debugar() { debugger }

Precise Timestamp

Returns a high-precision timestamp value (in milliseconds) since the epoch.

javascript
performance.now()

Performance Mark

Creates a high-level timestamp mark in the performance timeline.

javascript
performance.mark('start')

Measure Performance

Creates a measurement between two time marks.

javascript
performance.measure('diff', 'start', 'end')

Get the latest articles delivered to your inbox.

Follow Us: