﻿---
title: Programming Languages Cheat Sheet
date: 2025-05-19
excerpt: A quick reference for data structures, basic syntax, and essential APIs in Lua, JavaScript, Go, Python, and Java.
tags:
  - Lua
  - JavaScript
  - Go
  - Python
  - Java
cover: https://assets.vluv.space/cover/Lang/Python/AnimeChillPool.webp
updated: 2026-07-08 21:23:52
lang: en
i18n:
  cn: /langs
  translation: 2
---

<script type="module" src="/js/components/tab.js"></script>

> [!tldr] Cheat Sheet
>
> A quick reference guide to data structures, basic syntax, and essential APIs across multiple languages.

## Data Structures

<x-tabs>

<x-tab title="Python" sync-id="python" active>

| Feature      | List          | Tuple         | Set           | Dict              | Queue              | Stack           |
| ------------ | ------------- | ------------- | ------------- | ----------------- | ------------------ | --------------- |
| Syntax       | `{python} []` | `{python} ()` | `{python} {}` | `{python} {k: v}` | `{python} Queue()` | `{python} list` |
| Mutability   | ✅             | ❌             | ✅             | ✅                 | ✅                  | ✅               |
| Ordered      | ✅             | ✅             | ❌             | ✅                 | ✅                  | ✅               |
| Duplicates   | ✅             | ✅             | ❌             | ❌                 | ✅                  | ✅               |
| Index access | ✅             | ✅             | ❌             | ❌                 | ❌                  | ✅               |
| Slicing      | ✅             | ✅             | ❌             | ❌                 | ❌                  | ✅               |

```python
# List - mutable list
my_list = [1, 2, 3]           # Create a list
my_list.append(4)             # Append an element
my_list[1] = 10               # Modify the element at index 1
subset = my_list[1:3]         # Slice: elements from index 1 to 3 (exclusive)

# Tuple - immutable tuple
my_tuple = (1, 2, 3)          # Create a tuple
item = my_tuple[0]            # Index access

# Set - deduplicated collection
my_set = {1, 2, 3}            # Create a set
my_set.add(4)                 # Add an element
union = set1 | set2           # Union
intersection = set1 & set2    # Intersection

# Dict - key-value pairs
my_dict = {"a": 1, "b": 2}    # Create a dict
value = my_dict.get("c", 0)   # Get a value, default to 0 if key missing
my_dict["d"] = 4              # Add or update a key-value pair
keys = my_dict.keys()         # Get all keys
```

</x-tab>

<x-tab title="Go" sync-id="go">

| Feature      | Slice      | Array       | Map            | Queue/Stack  |
| ------------ | ---------- | ----------- | -------------- | ------------ |
| Syntax       | `{go} []T` | `{go} [n]T` | `{go} map[K]V` | `{go} slice` |
| Mutability   | ✅          | ✅           | ✅              | ✅            |
| Ordered      | ✅          | ✅           | ❌              | ✅            |
| Duplicates   | ✅          | ✅           | ❌              | ✅            |
| Index access | ✅          | ✅           | ❌              | ✅            |

> [!NOTE] Go data structure syntax
> - `{go} []T`: Slice, a dynamic array with variable length; T is the element type
> - `{go} [n]T`: Array, fixed length; n is the length, T is the element type
> - `{go} map[K]V`: Map (hash table); K is the key type, V is the value type

```go
// Slice - dynamic array, variable length
slice := []int{1, 2, 3}        // Create and initialize a slice
slice = append(slice, 4)       // Append an element
slice[1] = 10                  // Modify the element at index 1
subset := slice[1:3]           // Slice: elements from index 1 to 3 (exclusive)

// Array - fixed-length array
arr := [3]int{1, 2, 3}         // Create an int array of length 3
arr[0] = 5                     // Modify an element

// Map - hash table, key-value storage
m := map[string]int{"a": 1, "b": 2}  // Create and initialize a map
value, exists := m["c"]              // Get value and existence flag by key
m["d"] = 4                           // Add or update a key-value pair
delete(m, "a")                       // Delete a key-value pair

// Stack operations (implemented with a slice)
stack := []int{}               // Create an empty stack
stack = append(stack, 1)       // push
top := stack[len(stack)-1]    // peek: view the top element
stack = stack[:len(stack)-1]  // pop

// Queue operations (implemented with a slice)
queue := []int{}              // Create an empty queue
queue = append(queue, 1)       // enqueue
front := queue[0]             // peek: view the front element
queue = queue[1:]             // dequeue
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

| Feature      | Array             | Object            | Set                      | Map                      | Queue                | Stack                |
| ------------ | ----------------- | ----------------- | ------------------------ | ------------------------ | -------------------- | -------------------- |
| Syntax       | `{javascript} []` | `{javascript} {}` | `{javascript} new Set()` | `{javascript} new Map()` | `{javascript} array` | `{javascript} array` |
| Mutability   | ✅                 | ✅                 | ✅                        | ✅                        | ✅                    | ✅                    |
| Ordered      | ✅                 | ❌                 | ✅                        | ✅                        | ✅                    | ✅                    |
| Duplicates   | ✅                 | ❌                 | ❌                        | ❌                        | ✅                    | ✅                    |
| Index access | ✅                 | ❌                 | ❌                        | ❌                        | ❌                    | ✅                    |

```javascript
// Array
const arr = [1, 2, 3];                 // Create an array
arr.push(4);                          // Append an element
arr[1] = 10;                          // Modify the element at index 1
const subset = arr.slice(1, 3);       // Slice: elements from index 1 to 3 (exclusive)
arr.forEach(x => console.log(x));     // Iterate over the array
const mapped = arr.map(x => x * 2);   // Map: transform each element
const filtered = arr.filter(x => x > 1); // Filter: keep matching elements

// Object
const obj = {a: 1, b: 2};             // Create an object
const value = obj.c || 0;             // Get a property, default if missing
obj.d = 4;                            // Add or update a property
const keys = Object.keys(obj);        // Get all keys
const values = Object.values(obj);    // Get all values

// Set - deduplicated collection
const set = new Set([1, 2, 2, 3]);    // Create a set
set.add(4);                           // Add an element
set.has(1);                           // Check whether an element exists
set.delete(1);                        // Delete an element

// Map - key-value mapping
const map = new Map([['a', 1], ['b', 2]]); // Create a map
map.set('c', 3);                       // Set a key-value pair
map.get('a');                          // Get a value
map.has('a');                          // Check whether a key exists
```

</x-tab>

<x-tab title="Java" sync-id="java">

| Feature      | List          | Array        | Set          | Map          | Queue          | Stack          |
| ------------ | ------------- | ------------ | ------------ | ------------ | -------------- | -------------- |
| Syntax       | `{java} List` | `{java} T[]` | `{java} Set` | `{java} Map` | `{java} Queue` | `{java} Stack` |
| Mutability   | ✅             | ❌            | ✅            | ✅            | ✅              | ✅              |
| Ordered      | ✅             | ✅            | ❌            | ❌            | ✅              | ✅              |
| Duplicates   | ✅             | ❌            | ❌            | ❌(key)       | ✅              | ✅              |
| Index access | ✅             | ✅            | ❌            | ❌            | ❌              | ✅              |

```java
// List (ArrayList)
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.set(1, 10);
List<Integer> subList = list.subList(0, 2);
list.remove(Integer.valueOf(1));

// Set (HashSet)
Set<Integer> set = new HashSet<>();
set.add(1);
set.contains(1);
set.remove(1);

// Map (HashMap)
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.getOrDefault("c", 0);
map.containsKey("a");
Set<String> keys = map.keySet();

// Queue (LinkedList)
Queue<Integer> queue = new LinkedList<>();
queue.offer(1);
Integer front = queue.poll();

// Stack (Stack)
Stack<Integer> stack = new Stack<>();
stack.push(1);
Integer top = stack.pop();
Integer peek = stack.peek();
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

| Feature      | Table(Array) | Table(Dict) |
| ------------ | ------------ | ----------- |
| Syntax       | `{lua} {}`   | `{lua} {}`  |
| Mutability   | ✅            | ✅           |
| Ordered      | ✅            | ❌           |
| Duplicates   | ✅            | ❌(key)      |
| Index access | ✅            | ❌           |

```lua
-- Table as Array
arr = {1, 2, 3}
table.insert(arr, 4)
arr[2] = 10
table.remove(arr, 1)

-- Table as Dictionary
dict = {a = 1, b = 2}
dict["c"] = 3
dict.d = 4
value = dict.a or 0

-- Common table operations
count = #arr
for i, v in ipairs(arr) do
    print(i, v)
end
for k, v in pairs(dict) do
    print(k, v)
end
```

</x-tab>

</x-tabs>

## Basic Syntax

### Common Syntax

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
# Variables
x = 10                      # Integer
name = "Python"             # String
is_active = True            # Boolean

# Operators
+, -, *, /, //, %, **       # Arithmetic: add, subtract, multiply, divide, floor divide, modulo, power
==, !=, >, <, >=, <=        # Comparison operators
and, or, not                # Logical operators
in, is                      # Membership test, identity test

# Functions
def greet(name):
    return f"Hello, {name}"
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// Variables
var x int = 10                           // Full declaration
var name string = "Go"
isActive := true                        // Short declaration (type inferred)

// Operators
+, -, *, /, %                           // Arithmetic operators
==, !=, >, <, >=, <=                   // Comparison operators
&&, ||, !                               // Logical operators

// Functions
func greet(name string) string {         // Parameter and return types
    return fmt.Sprintf("Hello, %s", name)
}
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// Variables
let x = 10;                           // Mutable variable
const name = "JavaScript";             // Immutable constant
let isActive = true;                   // Boolean

// Operators
+, -, *, /, %                         // Arithmetic operators
==, ===, !=, !==, >, <, >=, <=       // Comparison (== compares values, === compares type and value)
&&, ||, !                             // Logical operators
in, instanceof                        // Membership test, type test

// Functions
function greet(name) {
    return `Hello, ${name}`;
}
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// Variables
int x = 10;                      // int type
String name = "Java";             // String type
boolean isActive = true;          // boolean type

// Operators
+, -, *, /, %                    // Arithmetic operators
==, !=, >, <, >=, <=            // Comparison operators
&&, ||, !                        // Logical operators
instanceof                       // Type test

// Methods
public String greet(String name) {
    return "Hello, " + name;
}
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
-- Variables
globalVar = 10              -- Global variable
local localVar = 20         -- Local variable (recommended)
local name = "Lua"
local isActive = true

-- Operators
+, -, *, /, %, ^            -- Arithmetic operators (^ is power)
==, ~=, >, <, >=, <=        -- Comparison operators (~= is not-equal)
and, or, not                -- Logical operators

-- Functions
function greet(name)
    return "Hello, " .. name   -- .. is string concatenation
end
```

</x-tab>

</x-tabs>

## Control Flow

### Conditional Statements

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
# If-elif-else
if condition:
    pass
elif condition2:
    pass
else:
    pass

# Ternary operator
result = "yes" if condition else "no"

# Nested conditions
if outer_condition:
    if inner_condition:
        pass
    else:
        pass
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// If-else if-else
if condition {
} else if condition2 {
} else {
}

// If with initialization
if x := getValue(); x > 0 {
    fmt.Println("positive")
} else {
    fmt.Println("non-positive")
}

// Switch statement
switch value {
case 1:
    fmt.Println("one")
case 2:
    fmt.Println("two")
default:
    fmt.Println("other")
}
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// If-else if-else
if (condition) {
} else if (condition2) {
} else {
}

// Ternary operator
result = condition ? "yes" : "no";

// Switch statement
switch (value) {
    case 1:
        console.log("one");
        break;
    case 2:
        console.log("two");
        break;
    default:
        console.log("other");
}
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// If-else if-else
if (condition) {
} else if (condition2) {
} else {
}

// Ternary operator
result = condition ? "yes" : "no";

// Switch statement
switch (value) {
    case 1:
        System.out.println("one");
        break;
    case 2:
        System.out.println("two");
        break;
    default:
        System.out.println("other");
}

// Switch expressions (Java 14+)
String message = switch (value) {
    case 1 -> "one";
    case 2 -> "two";
    default -> "other";
};
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
-- If-elseif-else
if condition then
elseif condition2 then
else
end

-- Nested conditions
if outer_condition then
    if inner_condition then
    else
    end
end

-- No ternary operator in Lua
-- Use if-else or logical operators
result = condition and "yes" or "no"
```

</x-tab>

</x-tabs>

### Loop Statements

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
# For loop with range
for i in range(10):         # 0 to 9
    pass

for i in range(1, 11):     # 1 to 10
    pass

for i in range(0, 10, 2):  # 0, 2, 4, 6, 8
    pass

# For loop over iterable
for item in items:
    pass

for index, item in enumerate(items):
    pass

# While loop
while condition:
    pass

# Loop control
for i in range(10):
    if i == 5:
        break    # Exit loop
    if i == 3:
        continue # Skip to next iteration
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// Traditional for loop
for i := 0; i < 10; i++ {
}

// For range over slice/array
for index, item := range items {
}

// For range over map
for key, value := range m {
}

// While loop (Go only has for)
for condition {
}

// Infinite loop
for {
}

// Loop control
for i := 0; i < 10; i++ {
    if i == 5 {
        break    // Exit loop
    }
    if i == 3 {
        continue // Skip to next iteration
    }
}
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// Traditional for loop
for (let i = 0; i < 10; i++) {
}

// For...of loop (iterables)
for (const item of items) {
}

// For...in loop (object properties)
for (const key in obj) {
}

// While loop
while (condition) {
}

// Do-while loop
do {
} while (condition);

// Loop control
for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break;    // Exit loop
    }
    if (i === 3) {
        continue; // Skip to next iteration
    }
}
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// Traditional for loop
for (int i = 0; i < 10; i++) {
}

// Enhanced for loop
for (int item : items) {
}

// While loop
while (condition) {
}

// Do-while loop
do {
} while (condition);

// Loop control
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;    // Exit loop
    }
    if (i == 3) {
        continue; // Skip to next iteration
    }
}

// Labeled loops (for nested loops)
outer: for (int i = 0; i < 3; i++) {
    inner: for (int j = 0; j < 3; j++) {
        if (i == 1 && j == 1) {
            break outer; // Exit outer loop
        }
    }
}
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
-- Numeric for loop
for i = 1, 10 do          -- 1 to 10
end

for i = 1, 10, 2 do       -- 1, 3, 5, 7, 9
end

-- Generic for loop (ipairs for arrays)
for i, v in ipairs(arr) do
end

-- Generic for loop (pairs for dictionaries)
for k, v in pairs(dict) do
end

-- While loop
while condition do
end

-- Repeat until loop (like do-while)
repeat
until condition

-- Loop control
for i = 1, 10 do
    if i == 5 then
        break    -- Exit loop
    end
    if i == 3 then
        -- No continue in Lua, use if
    end
end
```

</x-tab>

</x-tabs>

### Language-Specific Syntax

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
# Lambda - anonymous function
add = lambda x, y: x + y

# Classes
class Person:
    def __init__(self, name):   # Constructor
        self.name = name

    def greet(self):             # Instance method
        return f"Hello, {self.name}"

# List Comprehension
squared = [x**2 for x in range(10)]  # Squares of 0-9
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// Multiple return values
func divide(a, b int) (int, error) {     // Return a result and an error
    if b == 0 {
        return 0, errors.New("division by zero")  // Return an error
    }
    return a / b, nil                   // Return the result, error is nil
}

// Structs
type Person struct {
    Name string                          // Struct fields
    Age  int
}

func (p Person) Greet() string {        // Method (value receiver)
    return fmt.Sprintf("Hello, %s", p.Name)
}

// Goroutines
go func() {                             // The go keyword starts a goroutine
    fmt.Println("goroutine")
}()

// Channels - communication between goroutines
ch := make(chan int)                    // Create a channel
go func() {
    ch <- 1                             // Send data into the channel
}()
value := <-ch                           // Receive data from the channel
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// Ternary operator
result = condition ? a : b;

// Arrow Function
const greet = (name) => `Hello, ${name}`;

// Objects
const person = {
    name: "John",
    greet() {                         // Object method
        return `Hello, ${this.name}`;
    }
};

// Array methods
items.forEach(item => console.log(item)); // Iterate over the array
const mapped = items.map(x => x * 2);     // Map the array
const filtered = items.filter(x => x > 1); // Filter the array
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// Ternary operator
result = condition ? a : b;

// Classes
public class Person {
    private String name;

    public Person(String name) {   // Constructor
        this.name = name;
    }

    public String greet() {
        return "Hello, " + name;
    }
}

// Lambda expressions
Runnable r = () -> System.out.println("Hello");
Predicate<Integer> isEven = x -> x % 2 == 0;
List<Integer> evens = list.stream()
    .filter(isEven)                // Filter with the Stream API
    .collect(Collectors.toList()); // Collect into a List
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
local greet = function(name)    -- Anonymous function
    return "Hello, " .. name
end

-- Multiple return values
function getCoordinates()
    return 10, 20
end

local x, y = getCoordinates()   -- Receive multiple return values

-- Tables as objects
local person = {
    name = "John",
    greet = function(self)
        return "Hello, " .. self.name
    end
}
person:greet()                  -- Call the method
```

</x-tab>

</x-tabs>

## Functions & Parameter Passing

### Function Definition & Calling

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
# Function definition
def greet(name, age=25):
    return f"Hello {name}, you are {age} years old"

# Positional arguments
result = greet("Alice", 30)

# Keyword arguments
result = greet(name="Bob", age=35)

# Default arguments
result = greet("Charlie")  # Uses default age=25

# Variable arguments
def func(*args, **kwargs):
    print(args)      # Tuple of positional args
    print(kwargs)    # Dict of keyword args

func(1, 2, 3, name="Alice", age=25)
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// Function definition
func greet(name string, age int) string {
    return fmt.Sprintf("Hello %s, you are %d years old", name, age)
}

// Named return values
func calculate(a, b int) (sum, diff int) {
    sum = a + b
    diff = a - b
    return  // Returns named variables
}

// Variadic function
func sum(numbers ...int) int {
    total := 0
    for _, num := range numbers {
        total += num
    }
    return total
}

result := greet("Alice", 30)
total := sum(1, 2, 3, 4, 5)
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// Function declaration
function greet(name, age = 25) {
    return `Hello ${name}, you are ${age} years old`;
}

// Arrow function
const greetArrow = (name, age = 25) => `Hello ${name}, you are ${age} years old`;

// Rest parameters
function func(...args) {
    console.log(args);  // Array of arguments
}

// Destructuring parameters
const greetPerson = ({name, age}) => `Hello ${name}, age ${age}`;

result = greet("Alice", 30);
func(1, 2, 3, "hello");
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// Method definition
public String greet(String name, int age) {
    return String.format("Hello %s, you are %d years old", name, age);
}

// Method overloading
public String greet(String name) {
    return greet(name, 25);  // Calls other method with default age
}

// Varargs method
public int sum(int... numbers) {
    int total = 0;
    for (int num : numbers) {
        total += num;
    }
    return total;
}

String result = greet("Alice", 30);
int total = sum(1, 2, 3, 4, 5);
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
-- Function definition
function greet(name, age)
    age = age or 25  -- Default value
    return "Hello " .. name .. ", you are " .. age .. " years old"
end

-- Multiple return values
function getPerson()
    return "Alice", 30
end

-- Variable arguments
function sum(...)
    local total = 0
    for i, v in ipairs({...}) do
        total = total + v
    end
    return total
end

result = greet("Alice", 30)
name, age = getPerson()  -- Multiple assignment
total = sum(1, 2, 3, 4, 5)
```

</x-tab>

</x-tabs>

### Parameter Passing Mechanisms

<x-tabs>

<x-tab title="Python" sync-id="python" active>

| Type                        | Passing Mechanism            | Behavior                     |
| --------------------------- | ---------------------------- | ---------------------------- |
| Immutable (int, str, tuple) | **Pass by object reference** | Cannot modify original       |
| Mutable (list, dict, set)   | **Pass by object reference** | Can modify original content  |
| Objects                     | **Pass by object reference** | Can modify object attributes |

```python
# Immutable types - cannot modify original
def modify_int(x):
    x = 10  # Only modifies local copy
    return x

num = 5
result = modify_int(num)  # num is still 5

# Mutable types - can modify original
def modify_list(lst):
    lst.append(4)  # Modifies original list
    return lst

my_list = [1, 2, 3]
modify_list(my_list)  # my_list is now [1, 2, 3, 4]

# To avoid modifying mutable types
def safe_modify(lst):
    new_lst = lst.copy()  # Create copy
    new_lst.append(4)
    return new_lst
```

</x-tab>

<x-tab title="Go" sync-id="go">

| Type                 | Passing Mechanism                   | Behavior                                |
| -------------------- | ----------------------------------- | --------------------------------------- |
| All types            | **Pass by value**                   | Copies value to function                |
| Pointers             | **Pass by reference**               | Can modify original via pointer         |
| Slices/Maps/Channels | **Pass by value (reference types)** | Copy header, can modify underlying data |

```go
// Value types - pass by copy
func modifyInt(x int) {
    x = 10  // Only modifies local copy
}

num := 5
modifyInt(num)  // num is still 5

// Pointer types - pass by reference
func modifyIntPtr(x *int) {
    *x = 10  // Modifies original value
}

num := 5
modifyIntPtr(&num)  // num is now 10

// Reference types (slice, map, channel)
func modifySlice(s []int) {
    s[0] = 10  // Modifies underlying array
    s = append(s, 4)  // Only modifies local slice header
}

slice := []int{1, 2, 3}
modifySlice(slice)  // slice[0] is now 10, but length unchanged
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

| Type                                  | Passing Mechanism     | Behavior                   |
| ------------------------------------- | --------------------- | -------------------------- |
| Primitives (number, string, boolean)  | **Pass by value**     | Copies value to function   |
| Objects (including arrays, functions) | **Pass by reference** | Can modify original object |

```javascript
// Primitive types - pass by value
function modifyNum(x) {
    x = 10;  // Only modifies local copy
    return x;
}

let num = 5;
modifyNum(num);  // num is still 5

// Object types - pass by reference
function modifyArray(arr) {
    arr.push(4);  // Modifies original array
    return arr;
}

let myArray = [1, 2, 3];
modifyArray(myArray);  // myArray is now [1, 2, 3, 4]

// To avoid modifying objects
function safeModifyArray(arr) {
    const newArr = [...arr];  // Create copy
    newArr.push(4);
    return newArr;
}
```

</x-tab>

<x-tab title="Java" sync-id="java">

| Type                                    | Passing Mechanism             | Behavior                            |
| --------------------------------------- | ----------------------------- | ----------------------------------- |
| Primitives (int, double, boolean, etc.) | **Pass by value**             | Copies value to method              |
| Objects (including arrays)              | **Pass by value (reference)** | Copies reference, can modify object |

```java
// Primitive types - pass by value
public void modifyInt(int x) {
    x = 10;  // Only modifies local copy
}

int num = 5;
modifyInt(num);  // num is still 5

// Object types - pass by reference value
public void modifyArray(List<Integer> list) {
    list.add(4);  // Modifies original list
    list = new ArrayList<>();  // Only modifies local reference
}

List<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3));
modifyArray(myList);  // myList is now [1, 2, 3, 4]

// To avoid modifying objects
public void safeModifyArray(List<Integer> list) {
    List<Integer> newList = new ArrayList<>(list);  // Create copy
    newList.add(4);
}
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

| Type      | Passing Mechanism     | Behavior                                    |
| --------- | --------------------- | ------------------------------------------- |
| All types | **Pass by reference** | Tables passed by reference, others by value |

```lua
-- Numbers/strings - pass by value
function modifyNum(x)
    x = 10  -- Only modifies local copy
    return x
end

local num = 5
modifyNum(num)  -- num is still 5

-- Tables - pass by reference
function modifyTable(tbl)
    tbl.value = 10  -- Modifies original table
    return tbl
end

local myTable = {value = 5}
modifyTable(myTable)  -- myTable.value is now 10

-- To avoid modifying tables
function safeModifyTable(tbl)
    local newTbl = {}
    for k, v in pairs(tbl) do
        newTbl[k] = v
    end
    newTbl.value = 10
    return newTbl
end
```

</x-tab>

</x-tabs>

### Higher-Order Functions & Closures

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
# Higher-order function
def apply_operation(func, numbers):
    return [func(x) for x in numbers]

# Lambda functions
square = lambda x: x ** 2
result = apply_operation(square, [1, 2, 3, 4])

# Closures
def make_multiplier(factor):
    def multiplier(x):
        return x * factor  # Captures factor from outer scope
    return multiplier

times_three = make_multiplier(3)
result = times_three(5)  # Returns 15

# Decorators (higher-order functions)
def timer(func):
    import time
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"Function took {time.time() - start} seconds")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)
    return "Done"
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// Higher-order function
func applyOperation(func func(int) int, numbers []int) []int {
    result := make([]int, len(numbers))
    for i, num := range numbers {
        result[i] = func(num)
    }
    return result
}

// Function literals (closures)
func main() {
    square := func(x int) int { return x * x }
    result := applyOperation(square, []int{1, 2, 3, 4})

    // Closure capturing outer variable
    factor := 3
    multiplier := func(x int) int { return x * factor }
    result2 := applyOperation(multiplier, []int{1, 2, 3, 4})
}
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// Higher-order function
function applyOperation(func, numbers) {
    return numbers.map(func);
}

// Arrow functions
const square = x => x ** 2;
const result = applyOperation(square, [1, 2, 3, 4]);

// Closures
function makeMultiplier(factor) {
    return function(x) {
        return x * factor;  // Captures factor from outer scope
    };
}

const timesThree = makeMultiplier(3);
const result2 = timesThree(5);  // Returns 15

// Function methods (bind, call, apply)
const person = {name: "Alice"};
function greet(greeting) {
    return `${greeting}, ${this.name}`;
}

const boundGreet = greet.bind(person);
boundGreet("Hello");  // "Hello, Alice"
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// Functional interfaces (Java 8+)
import java.util.function.*;
import java.util.stream.Collectors;

// Higher-order function using streams
List<Integer> applyOperation(Function<Integer, Integer> func, List<Integer> numbers) {
    return numbers.stream()
        .map(func)
        .collect(Collectors.toList());
}

// Lambda expressions
Function<Integer, Integer> square = x -> x * x;
List<Integer> result = applyOperation(square, Arrays.asList(1, 2, 3, 4));

// Closures (effectively final variables)
public Function<Integer, Integer> makeMultiplier(int factor) {
    return x -> x * factor;  // Captures factor (must be effectively final)
}

Function<Integer, Integer> timesThree = makeMultiplier(3);
int result2 = timesThree.apply(5);  // Returns 15

// Method references
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<Integer> nameLengths = names.stream()
    .map(String::length)  // Method reference
    .collect(Collectors.toList());
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
-- Higher-order function
function applyOperation(func, numbers)
    local result = {}
    for i, num in ipairs(numbers) do
        result[i] = func(num)
    end
    return result
end

-- Anonymous functions
local square = function(x) return x * x end
local result = applyOperation(square, {1, 2, 3, 4})

-- Closures
function makeMultiplier(factor)
    return function(x)
        return x * factor  -- Captures factor from outer scope
    end
end

local timesThree = makeMultiplier(3)
local result2 = timesThree(5)  -- Returns 15

-- Functions as first-class citizens
local functions = {
    add = function(a, b) return a + b end,
    multiply = function(a, b) return a * b end
}

local sum = functions.add(5, 3)
```

</x-tab>

</x-tabs>

## Important APIs

### String Operations

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
s = "hello"
s.upper()                    # To uppercase
s.lower()                    # To lowercase
s.strip()                    # Trim leading/trailing whitespace
s.split(',')                 # Split the string
s.startswith('prefix')       # Check prefix
s.endswith('suffix')         # Check suffix
s.replace('old', 'new')      # Replace a substring
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
s := "hello"
strings.ToUpper(s)           // To uppercase
strings.ToLower(s)           // To lowercase
strings.TrimSpace(s)         // Trim leading/trailing whitespace
strings.Split(s, ",")        // Split the string
strings.HasPrefix(s, "prefix")  // Check prefix
strings.HasSuffix(s, "suffix")  // Check suffix
strings.Replace(s, "old", "new", -1)  // Replace a substring
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
const s = "hello";
s.toUpperCase();              // To uppercase
s.toLowerCase();              // To lowercase
s.trim();                     // Trim leading/trailing whitespace
s.split(',');                 // Split the string
s.startsWith('prefix');       // Check prefix
s.endsWith('suffix');         // Check suffix
s.replace('old', 'new');      // Replace a substring
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
String s = "hello";
s.toUpperCase();              // To uppercase
s.toLowerCase();              // To lowercase
s.trim();                     // Trim leading/trailing whitespace
s.split(",");                 // Split the string
s.startsWith("prefix");       // Check prefix
s.endsWith("suffix");         // Check suffix
s.replace("old", "new");      // Replace a substring
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
s = "hello"
string.upper(s)              -- To uppercase
string.lower(s)              -- To lowercase
string.gsub(s, "pattern", "replacement")  -- Replace a pattern
string.find(s, "pattern")    -- Find a pattern
string.sub(s, 1, 3)          -- Extract a substring
string.format("%s %d", "hello", 42)  -- Format a string
```

</x-tab>

</x-tabs>

### File I/O

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
with open('file.txt', 'r') as f:
    content = f.read()       # Read a file

with open('file.txt', 'w') as f:
    f.write('content')       # Write to a file

from pathlib import Path
path = Path('file.txt')
path.exists()                # Check the path
path.read_text()             # Read file content
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
content, err := os.ReadFile("file.txt")          // Read a file
os.WriteFile("file.txt", []byte("content"), 0644)  // Write to a file

os.Stat("file.txt")          // Get file info
os.ReadDir(".")              // List directory contents
os.Mkdir("dir", 0755)        // Create a directory
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
fetch('file.txt')
    .then(res => res.text()) // Read a file

// Writing files requires the File API
const file = new File(["content"], "file.txt");
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
Files.readString(Path.of("file.txt"));           // Read a file
Files.writeString(Path.of("file.txt"), "content");  // Write to a file
Files.exists(Path.of("file.txt"));                // Check whether the file exists
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
local file = io.open("file.txt", "r")  -- Open a file for reading
local content = file:read("*a")        -- Read all content
file:close()

local file = io.open("file.txt", "w")  -- Open a file for writing
file:write("content")                  -- Write content
file:close()

os.remove("file.txt")                  -- Delete a file
```

</x-tab>

</x-tabs>

### JSON Processing

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
import json
json.dumps(obj)               # Object to JSON string
json.loads(json_str)          # JSON string to object
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
json.Marshal(obj)             // Object to JSON bytes
json.Unmarshal(data, &obj)     // JSON bytes to object
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
JSON.stringify(obj);          // Object to JSON string
JSON.parse(jsonStr);          // JSON string to object
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// Jackson
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(obj);  // Object to JSON
MyClass obj = mapper.readValue(json, MyClass.class);  // JSON to object
```

</x-tab>

</x-tabs>

### HTTP Requests

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
import requests
response = requests.get('https://api.example.com')
data = response.json()        # Parse the JSON response
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
resp, err := http.Get("https://api.example.com")
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
fetch('https://api.example.com')
    .then(res => res.json())
    .then(data => console.log(data));
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com"))
    .build();
HttpResponse<String> response = client.send(request,
    HttpResponse.BodyHandlers.ofString());
```

</x-tab>

</x-tabs>

### Date/Time

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
from datetime import datetime
now = datetime.now()
formatted = now.strftime('%Y-%m-%d')  # Format the date
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
now := time.Now()
formatted := now.Format("2006-01-02")  // Format the date (Go's reference layout)
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
const now = new Date();
const formatted = now.toISOString();   // Convert to an ISO string
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
LocalDateTime now = LocalDateTime.now();
String formatted = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
os.time()                     -- Get the current timestamp
os.date()                     -- Format the date
```

</x-tab>

</x-tabs>

### Random & Math

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
import random
random.randint(1, 10)         # Random integer in [1, 10]
random.choice(['a', 'b', 'c'])  # Random choice
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
rand.Intn(10)                // Random integer in [0, 10)
rand.Intn(len(arr))          // Random index
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
Math.random();               // Random number in [0, 1)
Math.floor(Math.random() * 10);  // Random integer in [0, 10)
Math.max(1, 2, 3);           // Maximum
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
math.random(1, 10)           -- Random integer in [1, 10]
math.floor(3.14)             -- Round down
math.ceil(3.14)              -- Round up
math.max(1, 2, 3)            -- Maximum
```

</x-tab>

</x-tabs>

### Collections (Array/List/Table)

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
arr = [1, 2, 3]
arr.append(4)                # Append to the end
arr.remove(1)                # Remove an element
1 in arr                     # Check whether an element exists
arr.index(2)                 # Find the index of an element
[x for x in arr if x > 1]    # List comprehension
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// Slice
arr := []int{1, 2, 3}
arr = append(arr, 4)         // Append to the end

// Map
m := make(map[string]int)
m["key"] = 1                 // Add a key-value pair
val, ok := m["key"]          // Get a value
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
arr = [1, 2, 3]
arr.push(4);                 // Append to the end
arr.pop();                   // Remove the last element
arr.shift();                 // Remove the first element
arr.includes(2);             // Check whether an element exists
arr.indexOf(2);              // Find the index of an element
arr.filter(x => x > 1);      // Filter the array
arr.map(x => x * 2);         // Map the array
arr.reduce((acc, x) => acc + x, 0);  // Reduce
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// ArrayList
List<Integer> list = new ArrayList<>();
list.add(1);                 // Add an element
list.remove(Integer.valueOf(1));  // Remove an element (by value)
list.contains(1);            // Check whether an element exists
list.get(0);                 // Get an element

// HashMap
Map<String, Integer> map = new HashMap<>();
map.put("key", 1);           // Add a key-value pair
map.get("key");              // Get a value
map.containsKey("key");     // Check whether a key exists
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
-- Table
arr = {1, 2, 3}
table.insert(arr, 1, value)  -- Insert a value at index 1
table.remove(arr, 1)         -- Remove the element at index 1
table.sort(arr)              -- Sort
table.concat(arr, ",")       -- Join into a string
table.unpack(arr)            -- Unpack
```

</x-tab>

</x-tabs>

### Async Operations

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
import asyncio

async def fetch_data():
    async with aiohttp.ClientSession() as session:
        async with session.get('url') as response:
            return await response.json()

asyncio.run(fetch_data())
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
ch := make(chan int)
go func() {
    ch <- 1                   // Send data into the channel
}()

select {                      // Multiplexing
case v := <-ch:
    fmt.Println(v)           // Receive data
case <-time.After(time.Second):
    fmt.Println("timeout")   // Timeout
}
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// Promise
Promise.resolve(1).then(x => console.log(x));

// Async/Await
async function fetchData() {
    const res = await fetch('url');
    const data = await res.json();
    return data;
}

// setTimeout
setTimeout(() => console.log('delayed'), 1000);
```

</x-tab>

</x-tabs>
