Tips & Tricks

Discover practical programming and math tips to boost your productivity and problem-solving skills

50
Total Tips
25
Programming Tips
25
Math Tips
Programming Popular

Use Ternary Operators for Simple Conditions

Problem

Writing verbose if-else statements for simple conditions makes code harder to read and maintain.

Solution

Use the ternary operator (condition ? true : false) for single-line conditional assignments.

Benefit

Reduces code length by up to 70% and improves readability for simple conditions.

Code Example

// Instead of:
if (age >= 18) {
    status = 'adult';
} else {
    status = 'minor';
}

// Use:
status = age >= 18 ? 'adult' : 'minor';
Math Popular

Fast Multiplication by 11

Problem

Multiplying two-digit numbers by 11 using traditional methods takes time.

Solution

Add the two digits and place the sum between them. If sum > 9, carry the 1.

Benefit

Reduces calculation time by 80% and can be done mentally.

Example

23 × 11:
2 _ 3 → 2 (2+3) 3 → 253

67 × 11:
6 _ 7 → 6 (6+7) 7 → 6(13)7 → 737

89 × 11:
8 _ 9 → 8 (8+9) 9 → 8(17)9 → 979
Programming Popular

Use Array Destructuring

Problem

Extracting multiple values from arrays or objects requires writing repetitive assignment code.

Solution

Use destructuring syntax to extract multiple values in a single line.

Benefit

Makes code cleaner, reduces errors, and improves variable assignment efficiency.

Code Example

// Array destructuring
const [first, second, third] = [1, 2, 3];

// Object destructuring
const { name, age } = user;
Math Popular

Square Numbers Ending in 5

Problem

Squaring numbers ending in 5 using traditional multiplication is slow.

Solution

Take the first digit(s), multiply by (itself + 1), then append 25.

Benefit

Instant calculation without long multiplication, saves 90% of time.

Example

25² = 2×(2+1) = 2×3 = 6, append 25 → 625

75² = 7×(7+1) = 7×8 = 56, append 25 → 5625

105² = 10×(10+1) = 10×11 = 110, append 25 → 11025
Programming Popular

Use Array.map() Instead of Loops

Problem

Traditional for loops to transform arrays are verbose and error-prone with manual index management.

Solution

Use Array.map() to transform arrays in a functional, declarative way.

Benefit

Reduces code by 60%, eliminates off-by-one errors, and makes intent clearer.

Code Example

// Instead of:
const doubled = [];
for (let i = 0; i < numbers.length; i++) {
    doubled.push(numbers[i] * 2);
}

// Use:
const doubled = numbers.map(n => n * 2);
Math Popular

Multiply by 9 Using Fingers

Problem

Memorizing the 9 times table is difficult for many students.

Solution

Hold up 10 fingers. For 9×n, fold down the nth finger. Fingers left of fold = tens, right = ones.

Benefit

Visual method that works for all single-digit multiplications with 9.

Example

9 × 3:
Fold down 3rd finger → 2 fingers left, 7 fingers right → 27

9 × 7:
Fold down 7th finger → 6 fingers left, 3 fingers right → 63
Programming Popular

Use Template Literals for String Concatenation

Problem

String concatenation with + operator is hard to read and maintain, especially with multiple variables.

Solution

Use template literals with backticks and ${} syntax for cleaner string interpolation.

Benefit

Improves readability by 80% and supports multi-line strings without manual concatenation.

Code Example

// Instead of:
const msg = 'Hello ' + name + ', you are ' + age + ' years old.';

// Use:
const msg = `Hello ${name}, you are ${age} years old.`;
Math Popular

Multiply by 5 Quickly

Problem

Multiplying large numbers by 5 requires long multiplication.

Solution

Multiply by 10, then divide by 2. Or divide by 2, then multiply by 10.

Benefit

Converts difficult multiplication into simple division/multiplication by 10.

Example

86 × 5:
86 × 10 = 860
860 ÷ 2 = 430

Or: 86 ÷ 2 = 43
43 × 10 = 430
Programming

Use Object.keys() to Check Empty Objects

Problem

Checking if an object is empty requires iterating through its properties manually.

Solution

Use Object.keys(obj).length === 0 to quickly check if an object has no properties.

Benefit

One-line solution that is faster and more reliable than manual iteration.

Code Example

// Check if object is empty
const isEmpty = Object.keys(myObj).length === 0;

// Get all object keys
const keys = Object.keys(user); // ['name', 'age', 'email']
Math Popular

Quick Percentage Calculation

Problem

Calculating percentages like 15% or 18% requires complex mental math.

Solution

Break percentages into easy parts: 10%, 5%, 1%. Then combine them.

Benefit

Calculate any percentage mentally by breaking it into simple components.

Example

15% of 80:
10% = 8
5% = 4
15% = 8 + 4 = 12

18% of 200:
10% = 20
5% = 10
1% = 2
3% = 6
18% = 20 + 10 + 10 - 6 = 36
Programming

Use Array.filter() to Remove Falsy Values

Problem

Removing null, undefined, 0, false, NaN from arrays requires complex conditional logic.

Solution

Use Array.filter(Boolean) to remove all falsy values in one line.

Benefit

Eliminates 10+ lines of conditional logic and handles all falsy values automatically.

Code Example

const arr = [0, 1, false, 2, '', 3, null, undefined, NaN];

// Remove all falsy values
const clean = arr.filter(Boolean);
// Result: [1, 2, 3]
Math

Divisibility Rule for 3

Problem

Testing if large numbers are divisible by 3 requires actual division.

Solution

Sum all digits. If the sum is divisible by 3, the number is divisible by 3.

Benefit

Instant divisibility test without performing division.

Example

Is 2,847 divisible by 3?
2 + 8 + 4 + 7 = 21
21 ÷ 3 = 7 ✓
Yes, 2847 is divisible by 3

Is 5,923 divisible by 3?
5 + 9 + 2 + 3 = 19
19 is not divisible by 3 ✗
Programming Popular

Use Default Parameters

Problem

Functions need fallback values when parameters are not provided, requiring manual checks.

Solution

Use default parameter syntax to automatically assign fallback values in function signatures.

Benefit

Reduces defensive coding by 50% and makes function interfaces self-documenting.

Code Example

// Instead of:
function greet(name) {
    name = name || 'Guest';
    return `Hello ${name}`;
}

// Use:
function greet(name = 'Guest') {
    return `Hello ${name}`;
}
Math

Divisibility Rule for 9

Problem

Checking divisibility by 9 for large numbers requires long division.

Solution

Sum all digits. If the sum is divisible by 9, the number is divisible by 9.

Benefit

Quick mental check for divisibility by 9 without calculation.

Example

Is 7,362 divisible by 9?
7 + 3 + 6 + 2 = 18
18 ÷ 9 = 2 ✓
Yes, 7362 is divisible by 9

(In fact: 7362 ÷ 9 = 818)
Programming Popular

Use Spread Operator to Clone Arrays

Problem

Copying arrays with traditional methods can accidentally create references instead of new arrays.

Solution

Use the spread operator [...arr] to create a shallow copy of an array.

Benefit

Prevents mutation bugs and creates independent copies in one simple syntax.

Code Example

const original = [1, 2, 3];

// Clone array
const copy = [...original];

// Merge arrays
const merged = [...arr1, ...arr2];
Math

Fast Square Root Estimation

Problem

Finding square roots mentally for non-perfect squares is difficult.

Solution

Find the two perfect squares it falls between, then estimate proportionally.

Benefit

Get accurate estimates (±0.5) of square roots mentally in seconds.

Example

√50:
49 < 50 < 64
7 < √50 < 8
50 is close to 49, so √50 ≈ 7.1
(Actual: 7.07)

√80:
64 < 80 < 81
8 < √80 < 9
80 is very close to 81, so √80 ≈ 8.9
(Actual: 8.94)
Programming Popular

Use Array.includes() for Multiple Conditions

Problem

Checking multiple OR conditions creates long, repetitive comparison chains.

Solution

Use Array.includes() to check if a value matches any item in an array of possibilities.

Benefit

Reduces condition complexity by 70% and makes code more maintainable.

Code Example

// Instead of:
if (status === 'active' || status === 'pending' || status === 'approved') {
    // ...
}

// Use:
if (['active', 'pending', 'approved'].includes(status)) {
    // ...
}
Math

Multiply Two 2-Digit Numbers Ending in Same Digit

Problem

Multiplying numbers like 23×27 or 41×49 requires full multiplication.

Solution

When tens digit is same and ones add to 10: Multiply tens×(tens+1), then ones×ones.

Benefit

Special case shortcut that saves 80% of calculation time.

Example

23 × 27 (same tens 2, ones add to 10: 3+7=10):
Tens: 2 × (2+1) = 2 × 3 = 6
Ones: 3 × 7 = 21
Answer: 621

41 × 49:
Tens: 4 × 5 = 20
Ones: 1 × 9 = 09
Answer: 2009
Programming Popular

Use Optional Chaining for Nested Properties

Problem

Accessing deeply nested object properties requires multiple null/undefined checks.

Solution

Use optional chaining (?.) to safely access nested properties without explicit null checks.

Benefit

Eliminates 90% of null checking code and prevents "Cannot read property" errors.

Code Example

// Instead of:
const city = user && user.address && user.address.city;

// Use:
const city = user?.address?.city;
Math

Add Fractions with Different Denominators

Problem

Adding fractions requires finding least common denominator which is time-consuming.

Solution

Use cross-multiplication: (a/b + c/d) = (ad + bc) / (bd)

Benefit

Universal method that works for any fraction addition without finding LCD.

Example

2/3 + 3/4:
(2×4 + 3×3) / (3×4)
(8 + 9) / 12
17/12 = 1 5/12

1/5 + 2/7:
(1×7 + 2×5) / (5×7)
(7 + 10) / 35
17/35
Programming Popular

Use Array.find() Instead of filter()[0]

Problem

Using filter() to find a single item processes the entire array unnecessarily.

Solution

Use Array.find() which stops at the first match, improving performance.

Benefit

Up to 100x faster for large arrays and makes intent clearer.

Code Example

const users = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}];

// Inefficient:
const user = users.filter(u => u.id === 2)[0];

// Efficient:
const user = users.find(u => u.id === 2);
Math

Multiply by 99 Trick

Problem

Multiplying by 99 requires long multiplication with carrying.

Solution

Multiply by 100 and subtract the original number.

Benefit

Converts difficult multiplication into simple subtraction.

Example

46 × 99:
46 × 100 = 4600
4600 - 46 = 4554

73 × 99:
73 × 100 = 7300
7300 - 73 = 7227
Programming Popular

Use Set to Remove Array Duplicates

Problem

Removing duplicates from arrays requires nested loops or complex filter logic.

Solution

Convert array to Set (which only stores unique values) then back to array.

Benefit

One-line solution that is 50x faster than traditional approaches.

Code Example

const numbers = [1, 2, 2, 3, 3, 3, 4];

// Remove duplicates
const unique = [...new Set(numbers)];
// Result: [1, 2, 3, 4]
Math Popular

Calculate Tip Percentage Quickly

Problem

Calculating 15% or 20% tips at restaurants requires mental math under pressure.

Solution

10% = move decimal left. 20% = double that. 15% = 10% + half of 10%.

Benefit

Calculate common tip percentages in 3 seconds without calculator.

Example

Bill: $84.50
10% = $8.45
20% tip = $8.45 × 2 = $16.90

15% tip = $8.45 + $4.23 = $12.68

Bill: $42.00
10% = $4.20
15% tip = $4.20 + $2.10 = $6.30
Programming

Use Array.reduce() for Powerful Transformations

Problem

Complex array transformations require multiple passes and intermediate variables.

Solution

Use Array.reduce() to transform arrays into any shape (sum, object, grouped data).

Benefit

Single-pass solution that handles complex transformations efficiently.

Code Example

const numbers = [1, 2, 3, 4, 5];

// Sum array
const sum = numbers.reduce((acc, n) => acc + n, 0);

// Group by property
const grouped = items.reduce((acc, item) => {
    acc[item.category] = acc[item.category] || [];
    acc[item.category].push(item);
    return acc;
}, {});
Math

Convert Celsius to Fahrenheit Quickly

Problem

The exact formula (C × 9/5) + 32 is difficult to calculate mentally.

Solution

Double the Celsius, subtract 10%, then add 32.

Benefit

Estimates Fahrenheit within ±1 degree using simple mental math.

Example

20°C to °F:
20 × 2 = 40
40 - 4 = 36
36 + 32 = 68°F
(Exact: 68°F)

30°C to °F:
30 × 2 = 60
60 - 6 = 54
54 + 32 = 86°F
(Exact: 86°F)
Programming

Use console.table() for Debugging

Problem

Debugging arrays of objects with console.log() makes data hard to read and compare.

Solution

Use console.table() to display arrays and objects in a formatted table.

Benefit

Makes debugging 10x faster with clear, sortable table visualization.

Code Example

const users = [
    {id: 1, name: 'John', age: 30},
    {id: 2, name: 'Jane', age: 25}
];

// Display as table
console.table(users);
Math

Check Multiplication with 9s Trick

Problem

Verifying multiplication results requires recalculating the entire problem.

Solution

Use casting out nines: Sum digits of each number repeatedly until single digit, then verify.

Benefit

Quick verification method that catches 90% of calculation errors.

Example

Verify: 234 × 56 = 13,104

234: 2+3+4=9 → 9
56: 5+6=11 → 1+1=2
9 × 2 = 18 → 1+8=9

13,104: 1+3+1+0+4=9 ✓
Answer is likely correct!
Programming

Use Nullish Coalescing for Default Values

Problem

Using || for defaults treats 0 and false as falsy, causing unexpected behavior.

Solution

Use ?? (nullish coalescing) which only triggers for null/undefined, not 0/false.

Benefit

Prevents bugs when working with 0, false, or empty strings as valid values.

Code Example

const count = 0;

// Wrong: count becomes 10 (unexpected)
const value1 = count || 10;

// Correct: count stays 0
const value2 = count ?? 10;
Math

Subtract from 1000 Quickly

Problem

Subtracting from 1000 with borrowing is error-prone.

Solution

Subtract each digit from 9, except the last digit which you subtract from 10.

Benefit

No borrowing needed, eliminates most common subtraction errors.

Example

1000 - 456:
9-4=5
9-5=4
10-6=4
Answer: 544

1000 - 723:
9-7=2
9-2=7
10-3=7
Answer: 277
Programming Popular

Use Arrow Functions for Shorter Callbacks

Problem

Traditional function syntax in callbacks adds unnecessary verbosity.

Solution

Use arrow functions (=>) for concise callback syntax with implicit returns.

Benefit

Reduces callback code by 40% and automatically binds this context.

Code Example

// Traditional
numbers.map(function(n) {
    return n * 2;
});

// Arrow function
numbers.map(n => n * 2);
Math

Multiply by 15 Shortcut

Problem

Multiplying by 15 requires multiple steps with traditional methods.

Solution

Multiply by 10, then add half of that result.

Benefit

Reduces complex multiplication to simple addition.

Example

24 × 15:
24 × 10 = 240
240 ÷ 2 = 120
240 + 120 = 360

36 × 15:
36 × 10 = 360
360 ÷ 2 = 180
360 + 180 = 540
Programming Popular

Use Object.assign() to Clone Objects

Problem

Assigning objects creates references, causing accidental mutations.

Solution

Use Object.assign({}, obj) or spread {...obj} to create shallow copies.

Benefit

Prevents mutation bugs and allows safe object manipulation.

Code Example

const original = {name: 'John', age: 30};

// Clone object
const copy1 = Object.assign({}, original);
const copy2 = {...original};

// Merge objects
const merged = {...obj1, ...obj2};
Math

Square Numbers Near 50

Problem

Squaring numbers like 48 or 52 requires long multiplication.

Solution

Use (50-a)² = 2500 - 100a + a² or (50+a)² = 2500 + 100a + a²

Benefit

Converts difficult squares into simple arithmetic around 2500.

Example

48² (50-2):
2500 - 200 + 4 = 2304

52² (50+2):
2500 + 200 + 4 = 2704

47² (50-3):
2500 - 300 + 9 = 2209
Programming

Use Array.some() and Array.every()

Problem

Checking if any/all items meet a condition requires manual loops with break statements.

Solution

Use Array.some() to check if any item matches, Array.every() for all items.

Benefit

More readable and stops execution early for better performance.

Code Example

const numbers = [1, 2, 3, 4, 5];

// Check if any number > 3
const hasLarge = numbers.some(n => n > 3); // true

// Check if all numbers > 0
const allPositive = numbers.every(n => n > 0); // true
Math

Divisibility Rule for 4

Problem

Testing divisibility by 4 for large numbers requires division.

Solution

Check only the last two digits. If they form a number divisible by 4, the whole number is.

Benefit

Instantly test any number for divisibility by 4.

Example

Is 5,328 divisible by 4?
Check last 2 digits: 28
28 ÷ 4 = 7 ✓
Yes!

Is 7,862 divisible by 4?
Check last 2 digits: 62
62 ÷ 4 = 15.5 ✗
No!
Programming

Use Array.flat() to Flatten Nested Arrays

Problem

Flattening nested arrays requires recursive functions or complex reduce logic.

Solution

Use Array.flat(depth) to flatten arrays to specified depth in one line.

Benefit

Eliminates 20+ lines of recursive flattening code.

Code Example

const nested = [1, [2, 3], [4, [5, 6]]];

// Flatten one level
const flat1 = nested.flat(); // [1, 2, 3, 4, [5, 6]]

// Flatten all levels
const flat2 = nested.flat(Infinity); // [1, 2, 3, 4, 5, 6]
Math

Divisibility Rule for 6

Problem

Checking divisibility by 6 requires checking both 2 and 3 separately.

Solution

Number must be even AND sum of digits divisible by 3.

Benefit

Combines two simple rules for quick divisibility check.

Example

Is 426 divisible by 6?
Even? Yes (ends in 6)
Digit sum: 4+2+6=12, 12÷3=4 ✓
Yes, divisible by 6!

Is 534 divisible by 6?
Even? Yes
Digit sum: 5+3+4=12, 12÷3=4 ✓
Yes!
Programming Popular

Use Promise.all() for Parallel Async Operations

Problem

Sequential await calls waste time when operations could run in parallel.

Solution

Use Promise.all() to execute multiple async operations simultaneously.

Benefit

Can reduce execution time by 70% for independent async operations.

Code Example

// Sequential (slow): 3 seconds total
const user = await fetchUser();
const posts = await fetchPosts();
const comments = await fetchComments();

// Parallel (fast): 1 second total
const [user, posts, comments] = await Promise.all([
    fetchUser(),
    fetchPosts(),
    fetchComments()
]);
Math Popular

Multiply by 25 Instantly

Problem

Multiplying by 25 requires complex long multiplication.

Solution

Divide by 4 and multiply by 100 (or multiply by 100 and divide by 4).

Benefit

Converts multiplication into simple division by 4.

Example

32 × 25:
32 ÷ 4 = 8
8 × 100 = 800

48 × 25:
48 ÷ 4 = 12
12 × 100 = 1200
Programming

Use Array.from() to Convert Iterables

Problem

Converting NodeLists, Sets, or strings to arrays requires complex manual conversion.

Solution

Use Array.from() to convert any iterable into an array with optional mapping.

Benefit

Universal conversion solution that works with all iterable types.

Code Example

// Convert NodeList to Array
const divs = Array.from(document.querySelectorAll('div'));

// Create array from string
const chars = Array.from('hello'); // ['h','e','l','l','o']

// Create array with mapping
const squares = Array.from({length: 5}, (_, i) => i * i);
// [0, 1, 4, 9, 16]
Math

Day of Week Algorithm (Mental Calendar)

Problem

Figuring out what day of the week a date falls on requires a calendar.

Solution

Use Zeller's congruence simplified: Learn anchor days for each month and count forward/backward.

Benefit

Impress others by calculating any date's day of week mentally.

Example

For 2024 (leap year):
Jan 1 = Monday (anchor)
Feb 1 = Thursday (+31 days = +3 days)
Mar 1 = Friday (+29 days = +1 day)

What day is Feb 14, 2024?
Feb 1 is Thursday
14-1 = 13 days forward
13 ÷ 7 = 1 week + 6 days
Thursday + 6 = Wednesday
Programming Popular

Use Short-Circuit Evaluation

Problem

Conditional execution often requires verbose if statements for simple cases.

Solution

Use && for conditional execution and || for fallback values in one line.

Benefit

Reduces simple conditionals from 5 lines to 1 line.

Code Example

// Execute if condition is true
isLoggedIn && redirectToDashboard();

// Use fallback value
const name = userName || 'Guest';

// Chain conditions
user && user.isAdmin && showAdminPanel();
Math

Compound Interest Rule of 72

Problem

Calculating how long it takes for investment to double requires complex formulas.

Solution

Divide 72 by the interest rate to get approximate years to double.

Benefit

Quick investment doubling time calculation without formulas or calculators.

Example

6% annual return:
72 ÷ 6 = 12 years to double

9% annual return:
72 ÷ 9 = 8 years to double

12% annual return:
72 ÷ 12 = 6 years to double
Programming

Use JSON.parse() with Reviver Function

Problem

Parsing JSON with dates or special types requires manual post-processing.

Solution

Use the reviver parameter in JSON.parse() to transform values during parsing.

Benefit

Automates type conversion and eliminates separate transformation loops.

Code Example

const json = '{"date":"2024-01-01T00:00:00.000Z","count":"42"}';

const data = JSON.parse(json, (key, value) => {
    // Convert date strings to Date objects
    if (key === 'date') return new Date(value);
    // Convert numeric strings to numbers
    if (key === 'count') return parseInt(value);
    return value;
});
Math

Estimate Cube Roots

Problem

Finding cube roots mentally is extremely difficult.

Solution

Memorize cubes 1-10, then find which two cubes the number falls between.

Benefit

Estimate cube roots within ±0.5 by knowing 10 reference points.

Example

Cubes to memorize:
1³=1, 2³=8, 3³=27, 4³=64, 5³=125
6³=216, 7³=343, 8³=512, 9³=729, 10³=1000

∛200:
125 < 200 < 216
5 < ∛200 < 6
200 is closer to 216, so ∛200 ≈ 5.8
(Actual: 5.85)
Programming Popular

Use Object Shorthand Properties

Problem

Creating objects from variables requires repetitive key-value pairs.

Solution

Use ES6 shorthand to omit the value when key and variable name are the same.

Benefit

Reduces object creation code by 50% and improves readability.

Code Example

const name = 'John';
const age = 30;
const city = 'NYC';

// Instead of:
const user1 = {name: name, age: age, city: city};

// Use:
const user2 = {name, age, city};
Math Popular

Percentage Increase/Decrease Formula

Problem

Calculating percentage change between two values is confusing and error-prone.

Solution

((New - Old) / Old) × 100. Positive = increase, negative = decrease.

Benefit

Universal formula for all percentage change calculations.

Example

Price increased from $50 to $65:
((65 - 50) / 50) × 100
(15 / 50) × 100 = 30% increase

Price decreased from $80 to $60:
((60 - 80) / 80) × 100
(-20 / 80) × 100 = -25% decrease
Programming

Use console.time() for Performance Measurement

Problem

Measuring code execution time requires manual Date.now() calculations.

Solution

Use console.time() and console.timeEnd() to measure execution time easily.

Benefit

Simple, accurate performance measurement without manual timestamp math.

Code Example

console.time('Array processing');

const result = largeArray.map(item => {
    // Complex processing
    return processItem(item);
});

console.timeEnd('Array processing');
// Output: Array processing: 234.56ms
Math

Add Long Columns of Numbers Quickly

Problem

Adding long lists of numbers one at a time is slow and error-prone.

Solution

Look for pairs that sum to 10, group numbers that are easy to add (like 25+75=100).

Benefit

Speeds up mental addition by 50% by reducing the number of operations.

Example

Add: 8 + 14 + 2 + 6 + 25 + 75

Group strategically:
(8 + 2) = 10
(14 + 6) = 20
(25 + 75) = 100

10 + 20 + 100 = 130

No tips found matching your search

Try a different search term or filter

ES
Edrees Salih
5 hours ago

We are still cooking the magic in the way!