Browse by Language

Find code snippets and examples in your favorite programming language.

JS

JavaScript

Web & Node.js

Arrays, async/await, DOM manipulation, fetch API, and modern ES6+ features.

Array Filter
const nums = [1, 2, 3, 4, 5]; const even = nums.filter(n => n % 2 === 0); // [2, 4]
Array Map
const nums = [1, 2, 3]; const doubled = nums.map(n => n * 2); // [2, 4, 6]
Array Reduce
const nums = [1, 2, 3, 4]; const sum = nums.reduce((a, b) => a + b, 0); // 10
Fetch API
const res = await fetch('/api/data'); const data = await res.json(); console.log(data);
Destructuring
const { name, age } = user; const [first, ...rest] = items;
Spread Operator
const merged = [...arr1, ...arr2]; const copy = { ...obj, newKey: val };
Async/Await
async function getData() { try { const res = await fetch(url); return await res.json(); } catch (e) { console.error(e); } }
Promise.all
const results = await Promise.all([ fetch('/api/1'), fetch('/api/2') ]);
Py

Python

General Purpose

Lists, dictionaries, file operations, list comprehensions, and data processing.

List Comprehension
squares = [x**2 for x in range(10)] evens = [x for x in nums if x % 2 == 0]
Dict Comprehension
squared = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Read File
with open('file.txt', 'r') as f: content = f.read() lines = f.readlines()
Write File
with open('file.txt', 'w') as f: f.write('Hello World')
Dictionary
user = {'name': 'John', 'age': 30} name = user.get('name', 'Unknown') user['email'] = '[email protected]'
Lambda Function
double = lambda x: x * 2 sorted_list = sorted(items, key=lambda x: x['name'])
Try/Except
try: result = risky_operation() except Exception as e: print(f"Error: {e}")
String Format
name = "World" msg = f"Hello, {name}!" formatted = "{:.2f}".format(3.14159)
PHP

PHP

Web Development

Arrays, string functions, file handling, and web development patterns.

Array Map
$nums = [1, 2, 3, 4, 5]; $squared = array_map(fn($n) => $n * $n, $nums); // [1, 4, 9, 16, 25]
Array Filter
$nums = [1, 2, 3, 4, 5]; $evens = array_filter($nums, fn($n) => $n % 2 === 0); // [2, 4]
Array Reduce
$nums = [1, 2, 3, 4]; $sum = array_reduce($nums, fn($a, $b) => $a + $b, 0); // 10
JSON Encode/Decode
$json = json_encode($data); $arr = json_decode($json, true);
String Functions
$lower = strtolower($str); $parts = explode(',', $csv); $joined = implode('-', $arr);
File Operations
$content = file_get_contents('file.txt'); file_put_contents('out.txt', $data);
Null Coalescing
$name = $_GET['name'] ?? 'Guest'; $value = $arr['key'] ?? $default;
Array Sort
sort($arr); // ascending rsort($arr); // descending usort($arr, fn($a, $b) => $a - $b);
Go

Go

Systems & Backend

Slices, goroutines, HTTP servers, error handling, and concurrent programming.

HTTP GET
resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body)
Goroutine
go func() { // concurrent work result <- processData() }()
Slice Operations
nums := []int{1, 2, 3} nums = append(nums, 4, 5) slice := nums[1:3] // [2, 3]
Map Operations
m := make(map[string]int) m["key"] = 42 val, ok := m["key"]
Error Handling
result, err := doSomething() if err != nil { return fmt.Errorf("failed: %w", err) }
JSON Marshal
data, _ := json.Marshal(obj) json.Unmarshal(data, &result)
Channel
ch := make(chan int, 10) ch <- 42 // send val := <-ch // receive
Defer
file, _ := os.Open("file.txt") defer file.Close() // file auto-closes when func returns
Ja

Java

Enterprise & Android

Collections, streams, lambda expressions, and object-oriented patterns.

Stream Filter
List<Integer> evens = nums.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList());
Stream Map
List<String> names = users.stream() .map(User::getName) .collect(Collectors.toList());
Lambda Expression
list.forEach(item -> { System.out.println(item); }); list.sort((a, b) -> a.compareTo(b));
Optional
Optional<String> opt = Optional.ofNullable(val); String result = opt.orElse("default"); opt.ifPresent(v -> process(v));
HashMap
Map<String, Integer> map = new HashMap<>(); map.put("key", 42); int val = map.getOrDefault("key", 0);
Try-with-resources
try (var reader = new FileReader("f.txt")) { // auto-closes } catch (IOException e) { e.printStackTrace(); }
String Operations
String[] parts = str.split(","); String joined = String.join("-", list); boolean contains = str.contains("test");
Stream Reduce
int sum = nums.stream() .reduce(0, Integer::sum); // or .reduce(0, (a, b) -> a + b)
Rb

Ruby

Web & Scripting

Blocks, iterators, hashes, and elegant object-oriented programming.

Array Select
evens = nums.select { |n| n.even? } odds = nums.reject { |n| n.even? }
Array Map
squares = nums.map { |n| n ** 2 } names = users.map(&:name)
Hash Operations
user = { name: 'John', age: 30 } name = user[:name] || 'Unknown' user.merge!(email: '[email protected]')
Block Iterator
5.times { |i| puts i } (1..10).each { |n| puts n } arr.each_with_index { |v, i| }
String Interpolation
name = "World" msg = "Hello, #{name}!" multi = <<~TEXT Multiple lines TEXT
Reduce/Inject
sum = nums.reduce(0) { |acc, n| acc + n } # or simply: nums.sum
C++

C / C++

Systems Programming

Vectors, pointers, memory management, and standard template library.

Vector Operations
vector<int> nums = {1, 2, 3}; nums.push_back(4); nums.pop_back(); int size = nums.size();
Range-based For
for (const auto& item : items) { cout << item << endl; }
Smart Pointer
auto ptr = make_unique<MyClass>(); auto shared = make_shared<MyClass>(); ptr->doSomething();
Lambda Expression
auto add = [](int a, int b) { return a + b; }; sort(v.begin(), v.end(), [](int a, int b) { return a < b; });
Map/Unordered Map
unordered_map<string, int> m; m["key"] = 42; if (m.find("key") != m.end()) { }
String Operations
string s = "hello"; s += " world"; size_t pos = s.find("world"); string sub = s.substr(0, 5);
SQL

SQL

Databases

Queries, joins, aggregations, subqueries, and database manipulation.

SELECT with JOIN
SELECT u.name, o.total FROM users u JOIN orders o ON u.id = o.user_id WHERE o.total > 100;
GROUP BY
SELECT category, COUNT(*) as count, SUM(price) as total FROM products GROUP BY category;
INSERT
INSERT INTO users (name, email) VALUES ('John', '[email protected]'); INSERT INTO users (name) VALUES ('A'), ('B'), ('C');
UPDATE
UPDATE users SET email = '[email protected]', updated_at = NOW() WHERE id = 1;
Subquery
SELECT * FROM users WHERE id IN ( SELECT user_id FROM orders WHERE total > 1000 );
CASE Statement
SELECT name, CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' END as grade FROM students;

Explore More Snippets

Browse code snippets organized by programming topic.

Browse by Topic