Inspirational Education

208 ways to do JavaScript coding

JavaScript is a versatile programming language that is primarily used for front-end web development but can also be employed on the server-side (Node.js) and for mobile app development (React Native, Ionic).

Basics:

Example 1: Image Slider

This example creates a simple image slider that changes images when buttons are clicked.

1. Alert a Message

alert(“Hello, World!”);

2. Add Two Numbers

function add(a, b) {
return a + b;
}
console.log(add(5, 10)); // Output: 15

3. Change HTML Content

document.getElementById(“myElement”).innerHTML = “New Content!”;

4. Get Current Date

let today = new Date();
console.log(today);

5. Loop Through an Array

const fruits = [“Apple”, “Banana”, “Cherry”];
fruits.forEach(fruit => {
console.log(fruit);
});

6. Simple If Statement

let age = 18;
if (age >= 18) {
console.log(“You are an adult.”);
} else {
console.log(“You are a minor.”);
}

7. Create a Basic Function

function greet(name) {
return Hello, ${name}!;
}
console.log(greet(“Alice”)); // Output: Hello, Alice!

8. Event Listener

document.getElementById(“myButton”).addEventListener(“click”, function() {
alert(“Button clicked!”);
});

Some basic javascript

1. Variables

let name = “Alice”; // mutable
const age = 30; // immutable

2. Data Types

JavaScript supports several data types:

  • String: Text
  • Number: Integers or floats
  • Boolean: true or false
  • Array: List of values
  • Object: Key-value pairs

let isActive = true; // Boolean
let scores = [90, 85, 80]; // Array
let person = { name: “Alice”, age: 30 }; // Object

3. Functions

function greet(name) {
return “Hello, ” + name + “!”;
}

console.log(greet(“Alice”)); // Outputs: Hello, Alice!

4. Conditional Statements

let score = 75;

if (score >= 90) {
console.log(“A”);
} else if (score >= 80) {
console.log(“B”);
} else {
console.log(“C”);
}

5. Loops

For Loop:

for (let i = 0; i < 5; i++) {
console.log(i); // Outputs: 0, 1, 2, 3, 4
}

While Loop:

let count = 0;
while (count < 5) {
console.log(count);
count++;
}

6. Events

<button id=”myButton”>Click Me!</button>

<script> document.getElementById(“myButton”).addEventListener(“click”, function() { alert(“Button clicked!”); }); </script>

7. DOM Manipulation

document.getElementById(“myElement”).innerText = “New Text!”;
document.getElementById(“myElement”).style.color = “blue”;

8. Basic Example: Simple Calculator

function add(a, b) {
return a + b;
}

function subtract(a, b) {
return a – b;
}

console.log(add(5, 3)); // Outputs: 8
console.log(subtract(5, 3)); // Outputs: 2

9. Objects and Object Methods

let car = {
brand: “Toyota”,
model: “Corolla”,
year: 2021,
getDetails: function() {
return ${this.brand} ${this.model}, ${this.year};
}
};

console.log(car.getDetails()); // Outputs: Toyota Corolla, 2021

10. Array Methods

  • push(): Add an item to the end of an array.

let fruits = [“Apple”, “Banana”];
fruits.push(“Cherry”);
console.log(fruits); // Outputs: [“Apple”, “Banana”, “Cherry”]

  • pop(): Remove the last item from an array.

fruits.pop();
console.log(fruits); // Outputs: [“Apple”, “Banana”]

  • map(): Create a new array by applying a function to each element.

let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Outputs: [2, 4, 6]

11. Error Handling

try {
let result = riskyFunction(); // Some function that may throw an error
} catch (error) {
console.error(“An error occurred: ” + error.message);
} finally {
console.log(“This runs regardless of the outcome.”);
}

12. Asynchronous JavaScript

Using Promises:

function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(“Data received!”);
}, 2000);
});
}

fetchData().then(data => console.log(data)); // Outputs after 2 seconds: Data received!

Using async/await:

async function getData() {
let data = await fetchData();
console.log(data);
}

getData(); // Outputs after 2 seconds: Data received!

13. JSON (JavaScript Object Notation)

  • Parsing JSON:

let jsonString = ‘{“name”: “Alice”, “age”: 30}’;
let jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name); // Outputs: Alice

Stringifying Objects:

let person = { name: “Alice”, age: 30 };
let jsonString = JSON.stringify(person);
console.log(jsonString); // Outputs: {“name”:”Alice”,”age”:30}

14. Higher-Order Functions

function greet(name) {
return function() {
console.log(“Hello, ” + name);
};
}

let greetAlice = greet(“Alice”);
greetAlice(); // Outputs: Hello, Alice

15. Scope

let globalVar = “I’m global!”;

function myFunction() {
let localVar = “I’m local!”;
console.log(globalVar); // Accessible
console.log(localVar); // Accessible
}

myFunction();
// console.log(localVar); // Error: localVar is not defined

16. This Keyword

let person = {
name: “Alice”,
greet: function() {
console.log(“Hello, ” + this.name);
}
};

person.greet(); // Outputs: Hello, Alice

17. Arrow Functions

const add = (a, b) => a + b;
console.log(add(5, 3)); // Outputs: 8

18. Template Literals

let name = “Alice”;
let greeting = Hello, ${name}!;
console.log(greeting); // Outputs: Hello, Alice!

19. Modules

  • module.js:

export const pi = 3.14;
export function add(a, b) {
return a + b;
}

  • main.js:

import { pi, add } from ‘./module.js’;
console.log(pi); // Outputs: 3.14
console.log(add(2, 3)); // Outputs: 5

20. String Methods

  • toUpperCase() and toLowerCase():

let text = “Hello, World!”;
console.log(text.toUpperCase()); // Outputs: HELLO, WORLD!
console.log(text.toLowerCase()); // Outputs: hello, world!

  • trim(): Removes whitespace from both ends of a string.

let paddedText = ” Hello, World! “;
console.log(paddedText.trim()); // Outputs: Hello, World!

  • slice(): Extracts a part of a string.


let greeting = “Hello, World!”;
console.log(greeting.slice(0, 5)); // Outputs: Hello

21. Array Iteration Methods

let numbers = [1, 2, 3];
numbers.forEach(num => console.log(num * 2)); // Outputs: 2, 4, 6

  • forEach():

let numbers = [1, 2, 3];
numbers.forEach(num => console.log(num * 2)); // Outputs: 2, 4, 6

  • filter(): Creates a new array with elements that pass a condition.

let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Outputs: [2]

22. Object Destructuring

let person = { name: “Alice”, age: 30 };
let { name, age } = person;
console.log(name); // Outputs: Alice

23. Array Destructuring

let colors = [“red”, “green”, “blue”];
let [firstColor, secondColor] = colors;
console.log(firstColor); // Outputs: red

24. The Math Object

  • Basic Math Operations:

console.log(Math.round(4.7)); // Outputs: 5
console.log(Math.floor(4.9)); // Outputs: 4
console.log(Math.ceil(4.1)); // Outputs: 5
console.log(Math.random()); // Outputs: Random number between 0 and 1

  • Finding Maximum and Minimum:

let nums = [1, 2, 3, 4, 5];
console.log(Math.max(…nums)); // Outputs: 5
console.log(Math.min(…nums)); // Outputs: 1

25. JSON Data Example

// Sample JSON data
let jsonData = [ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 25} ];

let users = JSON.parse(jsonData);
users.forEach(user => console.log(user.name)); // Outputs: Alice, Bob

26. Event Delegation

<ul id=”myList”> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> <script>document.getElementById(“myList”).addEventListener(“click”, function(event) { if (event.target.tagName === “LI”) {alert(event.target.innerText); } }); </script>

27. Set and Map

Set: A collection of unique values.

let uniqueNumbers = new Set([1, 2, 2, 3]);
console.log(uniqueNumbers); // Outputs: Set { 1, 2, 3 }

Map: A collection of key-value pairs.

let userMap = new Map();
userMap.set(“name”, “Alice”);
userMap.set(“age”, 30);
console.log(userMap.get(“name”)); // Outputs: Alice

28. Callback Functions

function fetchData(callback) {
setTimeout(() => {
callback(“Data received!”);
}, 2000);
}

fetchData((data) => {
console.log(data); // Outputs after 2 seconds: Data received!
});

29. Promise Chaining

function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(“Data received!”);
}, 2000);
});
}

fetchData()
.then(data => {
console.log(data);
return “Processing data…”;
})
.then(message => {
console.log(message); // Outputs after 2 seconds: Processing data…
});

30. Using Local Storage

// Store data
localStorage.setItem(“name”, “Alice”);

// Retrieve data
let storedName = localStorage.getItem(“name”);
console.log(storedName); // Outputs: Alice

// Remove data
localStorage.removeItem(“name”);

31. Ternary Operator

let age = 20;
let isAdult = (age >= 18) ? “Yes” : “No”;
console.log(isAdult); // Outputs: Yes

32. Switch Statement

let fruit = “apple”;

switch (fruit) {
case “banana”:
console.log(“Yellow fruit”);
break;
case “apple”:
console.log(“Red fruit”);
break;
default:
console.log(“Unknown fruit”);
}

33. While Loop


let count = 0;
while (count < 5) {
console.log(count);
count++;
}

34. Do-While Loop

let num = 0;
do {
console.log(num);
num++;
} while (num < 5);

35. Function Expressions

const multiply = function(a, b) {
return a * b;
};

console.log(multiply(3, 4)); // Outputs: 12

36. Immediately Invoked Function Expression (IIFE)

(function() {
console.log(“This runs immediately!”);
})();

37. Default Parameters

function greet(name = “Guest”) {
console.log(“Hello, ” + name + “!”);
}

greet(); // Outputs: Hello, Guest!
greet(“Alice”); // Outputs: Hello, Alice!

38. Rest Parameters

function sum(…numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}

console.log(sum(1, 2, 3, 4)); // Outputs: 10

39. Spread Operator

let arr1 = [1, 2, 3];
let arr2 = [4, 5, …arr1];
console.log(arr2); // Outputs: [4, 5, 1, 2, 3]

let obj1 = { a: 1, b: 2 };
let obj2 = { …obj1, c: 3 };
console.log(obj2); // Outputs: { a: 1, b: 2, c: 3 }

40. Sorting Arrays

Using the sort() method to sort elements.

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a – b);
console.log(numbers); // Outputs: [1, 2, 3, 4, 5]

41. Map and Filter Combined

Using map() and filter() together.

let numbers = [1, 2, 3, 4, 5];
let squaredEvens = numbers.filter(num => num % 2 === 0).map(num => num ** 2);
console.log(squaredEvens); // Outputs: [4, 16]

42. Date Object

let now = new Date();
console.log(now); // Outputs the current date and time
console.log(now.getFullYear()); // Outputs the current year
console.log(now.getMonth()); // Outputs the current month (0-11)

43. Event Handling with Multiple Events

<button id=”myButton”>Click Me!</button> <script> let button = document.getElementById(“myButton”); button.addEventListener(“click”, () => { alert(“Button clicked!”); }); button.addEventListener(“mouseover”, () => { button.style.backgroundColor = “yellow”; }); button.addEventListener(“mouseout”, () => { button.style.backgroundColor= “”; }); </script>

44. Using setTimeout and setInterval

setTimeout(() => {
console.log(“Executed after 2 seconds”);
}, 2000); // Executes after 2 seconds

let count = 0;
let intervalId = setInterval(() => {
count++;
console.log(count);
if (count === 5) {
clearInterval(intervalId); // Stops after 5
}
}, 1000); // Executes every second

45. The this Keyword in Different Contexts

let person = {
name: “Alice”,
greet() {
console.log(“Hello, ” + this.name);
}
};

person.greet(); // Outputs: Hello, Alice

let greetFunc = person.greet;
greetFunc(); // Outputs: Hello, undefined (this refers to the global object)

46. Using bind(), call(), and apply()

let user = {
name: “Bob”
};

function sayHello() {
console.log(“Hello, ” + this.name);
}

let greetBob = sayHello.bind(user);
greetBob(); // Outputs: Hello, Bob

sayHello.call(user); // Outputs: Hello, Bob
sayHello.apply(user); // Outputs: Hello, Bob

47. Basic Regular Expressions

let regex = /[a-z]+/; // Matches lowercase letters
let str = “Hello123”;
console.log(regex.test(str)); // Outputs: true (contains lowercase letters)

let emailRegex = /^[^\s@]+@[^\s@]+.[^\s@]+$/;
console.log(emailRegex.test(“[email protected]”)); // Outputs: true

48. Fetch API for Network Requests

fetch(‘https://jsonplaceholder.typicode.com/posts’)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(‘Error:’, error));

49. Basic Classes and Inheritance

class Animal {
constructor(name) {
this.name = name;
}

speak() {
    console.log(`${this.name} makes a noise.`);
}

}

class Dog extends Animal {
speak() {
console.log(${this.name} barks.);
}
}

let dog = new Dog(“Rex”);
dog.speak(); // Outputs: Rex barks.

50. Basic Module Syntax

module.js:

export const greet = (name) => Hello, ${name}!;

main.js:

import { greet } from ‘./module.js’;
console.log(greet(“Alice”)); // Outputs: Hello, Alice!

Also read: Different types of IOT projects

Different types of series

Fibonacci Series

function fibonacciSeries(n) {
let series = [0, 1];
for (let i = 2; i < n; i++) {
series[i] = series[i – 1] + series[i – 2];
}
return series.slice(0, n);
}

// Example usage:
console.log(fibonacciSeries(10)); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Arithmetic Series

function arithmeticSeries(start, difference, terms) {
let series = [];
for (let i = 0; i < terms; i++) {
series.push(start + i * difference);
}
return series;
}

// Example usage:
console.log(arithmeticSeries(2, 3, 10)); // [2, 5, 8, 11, 14, 17, 20, 23, 26, 29]

Geometric Series

function geometricSeries(start, ratio, terms) {
let series = [];
for (let i = 0; i < terms; i++) {
series.push(start * Math.pow(ratio, i));
}
return series;
}

// Example usage:
console.log(geometricSeries(3, 2, 10)); // [3, 6, 12, 24, 48, 96, 192, 384, 768, 1536]

Harmonic Series

function harmonicSeries(n) {
let series = [];
for (let i = 1; i <= n; i++) {
series.push(1 / i);
}
return series;
}

// Example usage:
console.log(harmonicSeries(10)); // [1, 0.5, 0.333…, 0.25, 0.2, 0.166…, 0.142…, 0.125, 0.111…, 0.1]

Triangular Numbers

function triangularNumbers(n) {
let series = [];
for (let i = 1; i <= n; i++) {
series.push((i * (i + 1)) / 2);
}
return series;
}

// Example usage:
console.log(triangularNumbers(10)); // [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]

Factorial Series

function factorialSeries(n) {
let series = [];
let factorial = 1;
for (let i = 1; i <= n; i++) {
factorial *= i;
series.push(factorial);
}
return series;
}

// Example usage:
console.log(factorialSeries(10)); // [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

Square Numbers

function squareNumbers(n) {
let series = [];
for (let i = 1; i <= n; i++) {
series.push(i * i);
}
return series;
}

// Example usage:
console.log(squareNumbers(10)); // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Cube Numbers

function cubeNumbers(n) {
let series = [];
for (let i = 1; i <= n; i++) {
series.push(i * i * i);
}
return series;
}

// Example usage:
console.log(cubeNumbers(10)); // [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

Prime Numbers

function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}

function primeNumbers(n) {
let series = [];
let count = 0;
let num = 2; // Starting from the first prime number
while (count < n) {
if (isPrime(num)) {
series.push(num);
count++;
}
num++;
}
return series;
}

// Example usage:
console.log(primeNumbers(10)); // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Lucas Numbers

function lucasNumbers(n) {
let series = [2, 1];
for (let i = 2; i < n; i++) {
series[i] = series[i – 1] + series[i – 2];
}
return series.slice(0, n);
}

// Example usage:
console.log(lucasNumbers(10)); // [2, 1, 3, 4, 7, 11, 18, 29, 47, 76]

Pell Numbers

function pellNumbers(n) {
let series = [0, 1];
for (let i = 2; i < n; i++) {
series[i] = 2 * series[i – 1] + series[i – 2];
}
return series.slice(0, n);
}

// Example usage:
console.log(pellNumbers(10)); // [0, 1, 2, 5, 12, 29, 70, 169, 408, 985]

Catalan Numbers

function catalanNumbers(n) {
let series = [];
for (let i = 0; i < n; i++) {
series[i] = factorial(2 * i) / (factorial(i + 1) * factorial(i));
}
return series;
}

function factorial(num) {
if (num === 0) return 1;
let result = 1;
for (let i = 1; i <= num; i++) {
result *= i;
}
return result;
}

// Example usage:
console.log(catalanNumbers(10)); // [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862]

Fibonacci-Related Series (Generalized Fibonacci)

function generalizedFibonacci(n, first = 0, second = 1) {
let series = [first, second];
for (let i = 2; i < n; i++) {
series[i] = series[i – 1] + series[i – 2];
}
return series.slice(0, n);
}

// Example usage:
console.log(generalizedFibonacci(10, 2, 3)); // [2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

Fibonacci-Like Series

function fibonacciLike(n, first, second) {
let series = [first, second];
for (let i = 2; i < n; i++) {
series[i] = series[i – 1] + series[i – 2];
}
return series;
}

// Example usage:
console.log(fibonacciLike(10, 3, 5)); // [3, 5, 8, 13, 21, 34, 55, 89, 144, 233]

Collatz Sequence

function collatzSequence(n) {
let series = [n];
while (n !== 1) {
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
series.push(n);
}
return series;
}

// Example usage:
console.log(collatzSequence(6)); // [6, 3, 10, 5, 16, 8, 4, 2, 1]

Bell Numbers

function bellNumbers(n) {
let bell = Array.from({ length: n }, () => Array(n).fill(0));
bell[0][0] = 1;

for (let i = 1; i < n; i++) {
    // Explicitly set the first value in the row
    bell[i][0] = bell[i - 1][i - 1];

    for (let j = 1; j <= i; j++) {
        bell[i][j] = bell[i - 1][j - 1] + bell[i][j - 1];
    }
}

return bell.map(row => row[0]); // Return the first element of each row

}

// Example usage:
console.log(bellNumbers(10)); // [1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147]

Alternating Series

function alternatingSeries(n) {
let series = [];
for (let i = 0; i < n; i++) {
series.push(i % 2 === 0 ? i : -i);
}
return series;
}

// Example usage:
console.log(alternatingSeries(10)); // [0, -1, 2, -3, 4, -5, 6, -7, 8, -9]

Sum of Squares

function sumOfSquares(n) {
let series = [];
for (let i = 1; i <= n; i++) { series.push(i * i); } return series.reduce((sum, value) => sum + value, 0);
}

// Example usage:
console.log(sumOfSquares(10)); // 385

Sum of Cubes

function sumOfCubes(n) {
let series = [];
for (let i = 1; i <= n; i++) { series.push(i * i * i); } return series.reduce((sum, value) => sum + value, 0);
}

// Example usage:
console.log(sumOfCubes(10)); // 3025

Sieve of Eratosthenes

function sieveOfEratosthenes(limit) {
let primes = Array(limit + 1).fill(true);
primes[0] = primes[1] = false; // 0 and 1 are not primes
for (let p = 2; p * p <= limit; p++) { if (primes[p]) { for (let i = p * p; i <= limit; i += p) { primes[i] = false; } } } return primes.map((isPrime, index) => (isPrime ? index : null)).filter(Boolean);
}

// Example usage:
console.log(sieveOfEratosthenes(30)); // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Tribonacci Sequence

function tribonacci(n) {
let series = [0, 1, 1];
for (let i = 3; i < n; i++) {
series[i] = series[i – 1] + series[i – 2] + series[i – 3];
}
return series.slice(0, n);
}

// Example usage:
console.log(tribonacci(10)); // [0, 1, 1, 2, 4, 7, 13, 24, 44, 81]

Tetranacci Sequence

function tetranacci(n) {
let series = [0, 1, 1, 2];
for (let i = 4; i < n; i++) {
series[i] = series[i – 1] + series[i – 2] + series[i – 3] + series[i – 4];
}
return series.slice(0, n);
}

// Example usage:
console.log(tetranacci(10)); // [0, 1, 1, 2, 4, 8, 15, 29, 56, 108]

Arithmetic-Geometric Sequence

function arithmeticGeometricSequence(n, a, d, r) {
let series = [];
for (let i = 0; i < n; i++) {
series.push(a + i * d);
a *= r; // Multiply the term by the geometric ratio
}
return series;
}

// Example usage:
console.log(arithmeticGeometricSequence(10, 1, 1, 2)); // [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

Stirling Numbers of the Second Kind

function stirlingSecondKind(n, k) {
let stirling = Array.from({ length: n + 1 }, () => Array(k + 1).fill(0));
stirling[0][0] = 1;

for (let i = 1; i <= n; i++) {
    for (let j = 1; j <= k; j++) {
        stirling[i][j] = j * stirling[i - 1][j] + stirling[i - 1][j - 1];
    }
}
return stirling[n][k];

}

// Example usage:
console.log(stirlingSecondKind(5, 2)); // 15

Hypergeometric Series

function hypergeometricSeries(a, b, c, z, n) {
let series = [];
let term = 1; // The first term is always 1
for (let k = 0; k < n; k++) {
series.push(term);
term *= (a + k) * z / ((b + k) * (c + k));
}
return series;
}

// Example usage:
console.log(hypergeometricSeries(1, 1, 1, 0.5, 10)); // Generates terms of the hypergeometric series

Euler’s Totient Function

function eulerTotient(n) {
let result = n;
for (let p = 2; p * p <= n; p++) { if (n % p === 0) { while (n % p === 0) { n /= p; } result -= result / p; } } if (n > 1) {
result -= result / n;
}
return result;
}

// Example usage:
console.log(eulerTotient(9)); // 6

Harmonic Mean Series

function harmonicMean(numbers) {
let n = numbers.length;
let reciprocalSum = numbers.reduce((sum, num) => sum + 1 / num, 0);
return n / reciprocalSum;
}

// Example usage:
console.log(harmonicMean([1, 2, 3, 4])); // 1.92

Arithmetic Mean Series

function arithmeticMean(numbers) {
let sum = numbers.reduce((acc, num) => acc + num, 0);
return sum / numbers.length;
}

// Example usage:
console.log(arithmeticMean([1, 2, 3, 4])); // 2.5

Geometric Mean Series

function geometricMean(numbers) {
let product = numbers.reduce((acc, num) => acc * num, 1);
return Math.pow(product, 1 / numbers.length);
}

// Example usage:
console.log(geometricMean([1, 2, 3, 4])); // 2.24

Alternating Harmonic Series

function alternatingHarmonicSeries(n) {
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += (i % 2 === 0 ? -1 : 1) / i;
}
return sum;
}

// Example usage:
console.log(alternatingHarmonicSeries(10)); // Approx. 0.645

Bernoulli Numbers

function bernoulliNumbers(n) {
const A = new Array(n + 1).fill(0).map(() => new Array(n + 1).fill(0));
for (let j = 0; j <= n; j++) {
A[j][0] = 1 / (j + 1);
for (let i = 1; i <= j; i++) {
A[j][i] = 0;
for (let k = 0; k < i; k++) {
A[j][i] += A[j – 1][k] / (i – k);
}
}
}
const B = new Array(n + 1).fill(0);
for (let j = 0; j <= n; j++) {
B[j] = A[j][0];
}
return B;
}

// Example usage:
console.log(bernoulliNumbers(10)); // [1, -0.5, 0.16667, 0, -0.03333, 0.03333, 0, -0.02381, 0.03333, 0]

Fibonacci Primes

function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}

function fibonacciPrimes(n) {
let fib = [0, 1];
let primes = [];

for (let i = 2; i < n; i++) {
    fib[i] = fib[i - 1] + fib[i - 2];
    if (isPrime(fib[i])) {
        primes.push(fib[i]);
    }
}
return primes;

}

// Example usage:
console.log(fibonacciPrimes(20)); // [2, 3, 5, 13]

Tetranacci-Like Sequence

function generalizedTetranacci(n, first, second, third, fourth) {
let series = [first, second, third, fourth];
for (let i = 4; i < n; i++) {
series[i] = series[i – 1] + series[i – 2] + series[i – 3] + series[i – 4];
}
return series.slice(0, n);
}

// Example usage:
console.log(generalizedTetranacci(10, 1, 1, 2, 4)); // [1, 1, 2, 4, 8, 15, 29, 56, 108, 208]

Catalan Path

function catalanPath(n) {
return factorial(2 * n) / (factorial(n + 1) * factorial(n));
}

function factorial(num) {
if (num === 0) return 1;
let result = 1;
for (let i = 1; i <= num; i++) {
result *= i;
}
return result;
}

// Example usage:
console.log(catalanPath(5)); // 42

Motzkin Numbers

function motzkinNumbers(n) {
let M = Array(n + 1).fill(0);
M[0] = 1;

for (let i = 1; i <= n; i++) {
    M[i] = 0;
    for (let j = 0; j < i; j++) {
        M[i] += M[j] * M[i - 1 - j];
    }
    M[i] += M[i - 1]; // Add the case of no chords
}
return M[n];

}

// Example usage:
console.log(motzkinNumbers(5)); // 21

Generalized Harmonic Series

function generalizedHarmonic(n, p) {
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += 1 / Math.pow(i, p);
}
return sum;
}

// Example usage:
console.log(generalizedHarmonic(10, 2)); // Approx. 1.54977

Fibonacci Factorial Sequence

function fibonacciFactorial(n) {
let fib = [0, 1];
for (let i = 2; i < n; i++) { fib[i] = fib[i – 1] + fib[i – 2]; } return fib.map(f => factorial(f));
}

// Example usage:
console.log(fibonacciFactorial(10)); // Factorials of the first 10 Fibonacci numbers

Perfect Numbers

function isPerfect(num) {
let sum = 0;
for (let i = 1; i <= num / 2; i++) {
if (num % i === 0) {
sum += i;
}
}
return sum === num;
}

function perfectNumbers(n) {
let found = [];
let num = 1;
while (found.length < n) {
if (isPerfect(num)) {
found.push(num);
}
num++;
}
return found;
}

// Example usage:
console.log(perfectNumbers(4)); // [6, 28, 496, 8128]

Pell’s Equation Solutions

function pellSolutions(D, n) {
let solutions = [];
let m = 0;
let d = 1;
let a0 = Math.floor(Math.sqrt(D));
let a = a0;

let num1 = 1, num2 = a0; // x values
let den1 = 0, den2 = 1; // y values

for (let i = 0; i < n; i++) {
    solutions.push([num2, den2]);
    m = d * a - m;
    d = (D - m * m) / d;
    a = Math.floor((a0 + m) / d);

    let tempNum = num2;
    num2 = a * num2 + num1;
    num1 = tempNum;

    let tempDen = den2;
    den2 = a * den2 + den1;
    den1 = tempDen;
}
return solutions;

}

// Example usage:
console.log(pellSolutions(2, 5)); // First 5 solutions for x^2 – 2y^2 = 1

Lucas Primes

function lucasNumbers(n) {
let series = [2, 1];
for (let i = 2; i < n; i++) {
series[i] = series[i – 1] + series[i – 2];
}
return series;
}

function lucasPrimes(n) {
const lucas = lucasNumbers(n);
return lucas.filter(isPrime);
}

// Example usage:
console.log(lucasPrimes(20)); // Lucas primes up to the 20th Lucas number

Factorials of Primes

function factorial(num) {
if (num <= 1) return 1;
return num * factorial(num – 1);
}

function factorialOfPrimes(limit) {
let primes = sieveOfEratosthenes(limit);
return primes.map(factorial);
}

// Example usage:
console.log(factorialOfPrimes(10)); // Factorials of primes less than or equal to 10

Fibonacci Matrix

function matrixMultiply(A, B) {
return [
[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]
];
}

function matrixPower(F, n) {
if (n === 1) return F;
if (n % 2 === 0) {
let halfPower = matrixPower(F, n / 2);
return matrixMultiply(halfPower, halfPower);
} else {
return matrixMultiply(F, matrixPower(F, n – 1));
}
}

function fibonacciMatrix(n) {
if (n === 0) return 0;
if (n === 1) return 1;

let F = [[1, 1], [1, 0]];
let result = matrixPower(F, n - 1);
return result[0][0]; // Fibonacci(n) is in the top left corner

}

// Example usage:
console.log(fibonacciMatrix(10)); // 55

Triangular Numbers

function triangularNumbers(n) {
let series = [];
for (let i = 1; i <= n; i++) {
series.push((i * (i + 1)) / 2);
}
return series;
}

// Example usage:
console.log(triangularNumbers(10)); // [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]

Hexagonal Numbers

function hexagonalNumbers(n) {
let series = [];
for (let i = 1; i <= n; i++) {
series.push(i * (2 * i – 1));
}
return series;
}

// Example usage:
console.log(hexagonalNumbers(10)); // [1, 6, 15, 28, 45, 66, 91, 120, 153, 190]

Pentagonal Numbers

function pentagonalNumbers(n) {
let series = [];
for (let i = 1; i <= n; i++) {
series.push((3 * i * i – i) / 2);
}
return series;
}

// Example usage:
console.log(pentagonalNumbers(10)); // [1, 5, 12, 22, 35, 51, 70, 92, 117, 145]

Catalan’s Triangle

function catalanTriangle(n) {
let triangle = [];
for (let i = 0; i < n; i++) {
triangle[i] = [];
for (let j = 0; j <= i; j++) {
if (j === 0 || j === i) {
triangle[i][j] = 1;
} else {
triangle[i][j] = triangle[i – 1][j – 1] + triangle[i – 1][j];
}
}
}
return triangle;
}

// Example usage:
console.log(catalanTriangle(5)); // Displays the first 5 rows of Catalan’s triangle

Narcissistic Numbers

function isNarcissistic(num) {
let strNum = num.toString();
let length = strNum.length;
let sum = strNum.split(”).reduce((acc, digit) => acc + Math.pow(Number(digit), length), 0);
return sum === num;
}

function narcissisticNumbers(limit) {
let result = [];
for (let i = 0; i < limit; i++) {
if (isNarcissistic(i)) {
result.push(i);
}
}
return result;
}

// Example usage:
console.log(narcissisticNumbers(1000)); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]

Sum of Divisors

function sumOfDivisors(n) {
let sum = 0;
for (let i = 1; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
sum += i;
if (i !== n / i) {
sum += n / i; // Add the complementary divisor
}
}
}
return sum;
}

// Example usage:
console.log(sumOfDivisors(12)); // 28 (1 + 2 + 3 + 4 + 6 + 12)

Square

function printSquare(size) {
for (let i = 0; i < size; i++) {
console.log(‘* ‘.repeat(size).trim());
}
}

// Example usage:
printSquare(5);

Right Triangle

function printRightTriangle(height) {
for (let i = 1; i <= height; i++) {
console.log(‘* ‘.repeat(i).trim());
}
}

// Example usage:
printRightTriangle(5);

Inverted Right Triangle

function printInvertedRightTriangle(height) {
for (let i = height; i >= 1; i–) {
console.log(‘* ‘.repeat(i).trim());
}
}

// Example usage:
printInvertedRightTriangle(5);

Diamond

function printDiamond(height) {
// Upper part
for (let i = 1; i <= height; i++) { console.log(‘ ‘.repeat(height – i) + ‘* ‘.repeat(i).trim()); } // Lower part for (let i = height – 1; i >= 1; i–) {
console.log(‘ ‘.repeat(height – i) + ‘* ‘.repeat(i).trim());
}
}

// Example usage:
printDiamond(5);

Hollow Square

function printHollowSquare(size) {
for (let i = 0; i < size; i++) {
let row = ”;
for (let j = 0; j < size; j++) {
if (i === 0 || i === size – 1 || j === 0 || j === size – 1) {
row += ‘* ‘;
} else {
row += ‘ ‘;
}
}
console.log(row.trim());
}
}

// Example usage:
printHollowSquare(5);

Hollow Right Triangle

function printHollowRightTriangle(height) {
for (let i = 1; i <= height; i++) {
let row = ”;
for (let j = 1; j <= i; j++) {
if (j === 1 || j === i || i === height) {
row += ‘* ‘;
} else {
row += ‘ ‘;
}
}
console.log(row.trim());
}
}

// Example usage:
printHollowRightTriangle(5);

Hourglass

function printHourglass(height) {
// Upper part
for (let i = height; i >= 1; i–) {
console.log(‘* ‘.repeat(i).trim());
}
// Lower part
for (let i = 2; i <= height; i++) {
console.log(‘* ‘.repeat(i).trim());
}
}

// Example usage:
printHourglass(5);

Pyramid

function printPyramid(height) {
for (let i = 1; i <= height; i++) {
console.log(‘ ‘.repeat(height – i) + ‘* ‘.repeat(i).trim());
}
}

// Example usage:
printPyramid(5);

Hollow Pyramid

function printHollowPyramid(height) {
for (let i = 1; i <= height; i++) { let row = ‘ ‘.repeat(height – i); if (i === height) { row += ‘* ‘.repeat(i).trim(); // Base of the pyramid } else { row += ‘*’; if (i > 1) {
row += ‘ ‘.repeat(2 * (i – 1) – 1) + ‘*’;
}
}
console.log(row);
}
}

// Example usage:
printHollowPyramid(5);

Diamond (Hollow)

function printHollowDiamond(height) {
// Upper part
for (let i = 1; i <= height; i++) {
let row = ‘ ‘.repeat(height – i);
if (i === 1) {
row += ‘‘; } else { row += ‘‘;
row += ‘ ‘.repeat(2 * (i – 1) – 1) + ‘‘; } console.log(row); } // Lower part for (let i = height – 1; i >= 1; i–) { let row = ‘ ‘.repeat(height – i); if (i === 1) { row += ‘‘;
} else {
row += ‘*’;
row += ‘ ‘.repeat(2 * (i – 1) – 1) + ‘*’;
}
console.log(row);
}
}

// Example usage:
printHollowDiamond(5);

Staircase

function printStaircase(height) {
for (let i = 1; i <= height; i++) {
console.log(‘* ‘.repeat(i).trim());
}
}

// Example usage:
printStaircase(5);

Cross

function printCross(size) {
for (let i = 0; i < size; i++) {
let row = ”;
for (let j = 0; j < size; j++) {
if (i === Math.floor(size / 2) || j === Math.floor(size / 2)) {
row += ‘* ‘;
} else {
row += ‘ ‘;
}
}
console.log(row.trim());
}
}

// Example usage:
printCross(7);

X Shape

function printX(size) {
for (let i = 0; i < size; i++) {
let row = ”;
for (let j = 0; j < size; j++) {
if (i === j || i + j === size – 1) {
row += ‘* ‘;
} else {
row += ‘ ‘;
}
}
console.log(row.trim());
}
}

// Example usage:
printX(7);

Parallelogram

function printParallelogram(height, width) {
for (let i = 0; i < height; i++) {
console.log(‘ ‘.repeat(i) + ‘* ‘.repeat(width).trim());
}
}

// Example usage:
printParallelogram(5, 7);

Kite Shape

function printKite(height) {
// Upper part
for (let i = 1; i <= height; i++) { console.log(‘ ‘.repeat(height – i) + ‘* ‘.repeat(i).trim()); } // Lower part for (let i = height – 1; i >= 1; i–) {
console.log(‘ ‘.repeat(height – i) + ‘* ‘.repeat(i).trim());
}
}

// Example usage:
printKite(5);

Trapezoid

function printTrapezoid(height, width) {
for (let i = 0; i < height; i++) {
const spaces = ‘ ‘.repeat(i);
const stars = ‘* ‘.repeat(width – i).trim();
console.log(spaces + stars);
}
}

// Example usage:
printTrapezoid(5, 7);

Spiral Pattern (Simple)

function printSpiral(n) {
const spiral = Array.from({ length: n }, () => Array(n).fill(‘ ‘));
let x = 0, y = 0;
let dx = 0, dy = 1;

for (let i = 0; i < n * n; i++) {
    spiral[x][y] = '*';
    if (spiral[(x + dx + n) % n][(y + dy + n) % n] !== ' ') {
        [dx, dy] = [dy, -dx];
    }
    x += dx;
    y += dy;
}

spiral.forEach(row => console.log(row.join('')));

}

// Example usage:
printSpiral(5);

Filled Hexagon

function printHexagon(size) {
for (let i = 1; i <= size; i++) {
console.log(‘ ‘.repeat(size – i) + ‘* ‘.repeat(size).trim());
}
for (let i = 1; i <= size; i++) {
console.log(‘ ‘.repeat(i) + ‘* ‘.repeat(size).trim());
}
}

// Example usage:
printHexagon(5);

Hollow Hexagon

function printHollowHexagon(size) {
console.log(‘ ‘.repeat(size) + ‘*’); // Top point

for (let i = 1; i < size; i++) {
    console.log(' '.repeat(size - i) + '*' + ' '.repeat(2 * (size - 1)) + '*');
}

console.log('* '.repeat(size).trim()); // Middle part

for (let i = 1; i < size; i++) {
    console.log(' '.repeat(i) + '*' + ' '.repeat(2 * (size - 1)) + '*');
}

console.log(' '.repeat(size) + '*'); // Bottom point

}

// Example usage:
printHollowHexagon(5);

Checkerboard Pattern

function printCheckerboard(size) {
for (let i = 0; i < size; i++) {
let row = ”;
for (let j = 0; j < size; j++) {
if ((i + j) % 2 === 0) {
row += ‘* ‘;
} else {
row += ‘ ‘;
}
}
console.log(row.trim());
}
}

// Example usage:
printCheckerboard(8);

Right Angled Triangle (Mirror)

function printRightAngledTriangleMirror(height) {
for (let i = 1; i <= height; i++) {
console.log(‘ ‘.repeat(height – i) + ‘* ‘.repeat(i).trim());
}
}

// Example usage:
printRightAngledTriangleMirror(5);

Kite Shape (Hollow)

function printHollowKite(height) {
// Upper part
for (let i = 1; i <= height; i++) {
let row = ‘ ‘.repeat(height – i);
if (i === 1) {
row += ‘‘; } else { row += ‘‘;
row += ‘ ‘.repeat(2 * (i – 1) – 1) + ‘‘; } console.log(row); } // Lower part for (let i = height – 1; i >= 1; i–) { let row = ‘ ‘.repeat(height – i); if (i === 1) { row += ‘‘;
} else {
row += ‘*’;
row += ‘ ‘.repeat(2 * (i – 1) – 1) + ‘*’;
}
console.log(row);
}
}

// Example usage:
printHollowKite(5);

Arrow Shape

function printArrow(size) {
// Arrow head
for (let i = 1; i <= size; i++) {
console.log(‘ ‘.repeat(size – i) + ‘* ‘.repeat(i).trim());
}
// Arrow tail
for (let i = 0; i < size; i++) {
console.log(‘ ‘.repeat(size – 1) + ‘*’);
}
}

// Example usage:
printArrow(5);

Flower Shape

function printFlower(size) {
for (let i = 0; i < size; i++) { console.log(‘ ‘.repeat(size – i – 1) + ‘* ‘.repeat(size + i)); } for (let i = size; i >= 1; i–) {
console.log(‘ ‘.repeat(size – i) + ‘* ‘.repeat(i));
}
}

// Example usage:
printFlower(5);

Spiral (Complex)

function printComplexSpiral(n) {
const spiral = Array.from({ length: n }, () => Array(n).fill(‘ ‘));
let x = Math.floor(n / 2), y = Math.floor(n / 2);
let dx = 0, dy = -1;

for (let i = 0; i < n * n; i++) {
    spiral[x][y] = '*';
    if (spiral[(x + dx + n) % n][(y + dy + n) % n] !== ' ') {
        [dx, dy] = [dy, -dx];
    }
    x += dx;
    y += dy;
}

spiral.forEach(row => console.log(row.join('')));

}

// Example usage:
printComplexSpiral(5);

Diamond (Filled)

function printFilledDiamond(height) {
// Upper part
for (let i = 1; i <= height; i++) { console.log(‘ ‘.repeat(height – i) + ‘* ‘.repeat(i).trim()); } // Lower part for (let i = height – 1; i >= 1; i–) {
console.log(‘ ‘.repeat(height – i) + ‘* ‘.repeat(i).trim());
}
}

// Example usage:
printFilledDiamond(5);

Wave Pattern

function printWave(size) {
for (let i = 0; i < size; i++) {
let row = ”;
for (let j = 0; j < size; j++) {
if (i % 2 === 0) {
row += ‘* ‘;
} else {
row += ‘ ‘.repeat(2);
}
}
console.log(row.trim());
}
}

// Example usage:
printWave(5);

Zigzag Pattern

function printZigzag(size) {
for (let i = 0; i < size; i++) {
let row = ”;
for (let j = 0; j < size; j++) {
if ((i + j) % 2 === 0) {
row += ‘* ‘;
} else {
row += ‘ ‘;
}
}
console.log(row.trim());
}
}

// Example usage:
printZigzag(5);

Christmas Tree

function printChristmasTree(height) {
for (let i = 1; i <= height; i++) {
console.log(‘ ‘.repeat(height – i) + ‘* ‘.repeat(2 * i – 1).trim());
}
console.log(‘ ‘.repeat(height – 1) + ‘*’); // Trunk
}

// Example usage:
printChristmasTree(5);

Hourglass (Hollow)

function printHollowHourglass(height) {
// Upper part
for (let i = height; i >= 1; i–) {
let row = ”;
for (let j = 1; j <= i; j++) {
if (j === 1 || j === i || i === height) {
row += ‘* ‘;
} else {
row += ‘ ‘;
}
}
console.log(row.trim());
}
// Lower part
for (let i = 2; i <= height; i++) {
let row = ”;
for (let j = 1; j <= i; j++) {
if (j === 1 || j === i || i === height) {
row += ‘* ‘;
} else {
row += ‘ ‘;
}
}
console.log(row.trim());
}
}

// Example usage:
printHollowHourglass(5);

Parabolic Shape

function printParabola(height) {
for (let i = 0; i <= height; i++) {
console.log(‘ ‘.repeat(height – i) + ‘* ‘.repeat(i * 2 + 1).trim());
}
}

// Example usage:
printParabola(5);

Right-Angled Triangle (Hollow)

function printHollowRightTriangle(height) {
for (let i = 1; i <= height; i++) {
let row = ”;
for (let j = 1; j <= i; j++) {
if (j === 1 || j === i || i === height) {
row += ‘* ‘;
} else {
row += ‘ ‘;
}
}
console.log(row.trim());
}
}

// Example usage:
printHollowRightTriangle(5);

Wavy Diamond

function printWavyDiamond(size) {
// Upper part
for (let i = 1; i <= size; i++) { console.log(‘ ‘.repeat(size – i) + ‘* ‘.repeat(i).trim()); } // Lower part for (let i = size – 1; i >= 1; i–) {
console.log(‘ ‘.repeat(size – i) + ‘* ‘.repeat(i).trim());
}
}

// Example usage:
printWavyDiamond(5);

Butterfly Pattern

function printButterfly(size) {
// Upper part
for (let i = 1; i <= size; i++) { console.log(‘* ‘.repeat(i) + ‘ ‘.repeat((size – i) * 2) + ‘* ‘.repeat(i)); } // Lower part for (let i = size; i >= 1; i–) {
console.log(‘* ‘.repeat(i) + ‘ ‘.repeat((size – i) * 2) + ‘* ‘.repeat(i));
}
}

// Example usage:
printButterfly(5);

Starburst

function printStarburst(size) {
for (let i = 0; i < size; i++) {
let row = ”;
for (let j = 0; j < size; j++) {
if (i === j || i + j === size – 1) {
row += ‘* ‘;
} else {
row += ‘ ‘;
}
}
console.log(row.trim());
}
}

// Example usage:
printStarburst(5);

Please join discussion on Facebook about world facts and its secret.