Skip to content
DevNursery.com - New Web Developer Docs
GitHub

Useful Javascript Tricks

1-25

TrickPurposeSyntaxExample
Trick 1Remove duplicates from an arrayArray.from(new Set(array))const uniqueArray = Array.from(new Set([1, 2, 2, 3]))
Trick 2Check if a variable is definedtypeof variable !== 'undefined'javascript if (typeof myVar !== 'undefined') { /* do something */ }
Trick 3Create an array with a range of numbersArray.from({ length: n }, (_, i) => i)const numbers = Array.from({ length: 5 }, (_, i) => i);
Trick 4Convert an array-like object to an arrayArray.from(arrayLike)const arrayLike = { 0: 'one', 1: 'two', length: 2 }; const newArray = Array.from(arrayLike);
Trick 5Merge two objectsconst merged = { ...obj1, ...obj2 }javascript const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const merged = { ...obj1, ...obj2 };
Trick 6Shuffle an arrayarray.sort(() => Math.random() - 0.5)javascript const shuffledArray = array.sort(() => Math.random() - 0.5);
Trick 7Check if a string contains a substringstring.includes(substring)const contains = 'Hello, world!'.includes('world');
Trick 8Get the current date in ISO formatconst isoDate = new Date().toISOString();const isoDate = new Date().toISOString();
Trick 9Find the maximum number in an arrayconst max = Math.max(...array)const numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; const max = Math.max(...numbers);
Trick 10Check if an array is emptyconst isEmpty = array.length === 0;const isEmpty = [].length === 0;
Trick 11Flatten a nested arrayconst flatArray = nestedArray.flat();const nestedArray = [1, [2, 3], [4, [5, 6]]]; const flatArray = nestedArray.flat(Infinity);
Trick 12Convert a string to uppercaseconst uppercased = string.toUpperCase();const string = 'hello'; const uppercased = string.toUpperCase();
Trick 13Convert a string to lowercaseconst lowercased = string.toLowerCase();const string = 'Hello'; const lowercased = string.toLowerCase();
Trick 14Replace all occurrences of a substringconst replaced = string.replace(/old/g, 'new');const string = 'old text old text'; const replaced = string.replace(/old/g, 'new');
Trick 15Check if an object is emptyconst isEmpty = Object.keys(obj).length === 0;const isEmpty = Object.keys({}).length === 0;
Trick 16Convert a string to an array of charactersconst charArray = string.split('');const string = 'hello'; const charArray = string.split('');
Trick 17Get the last element of an arrayconst lastElement = array[array.length - 1];const array = [1, 2, 3, 4, 5]; const lastElement = array[array.length - 1];
Trick 18Generate a random number within a rangeconst randomNum = Math.floor(Math.random() * (max - min + 1)) + min;const min = 1; const max = 10; const randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
Trick 19Reverse a stringconst reversed = string.split('').reverse().join('');const string = 'hello'; const reversed = string.split('').reverse().join('');
Trick 20Check if an array contains a specific valueconst containsValue = array.includes(value);const array = [1, 2, 3, 4, 5]; const value = 3; const containsValue = array.includes(value);
Trick 21Find the index of an element in an arrayconst index = array.indexOf(element);const array = [1, 2, 3, 4, 5]; const element = 3; const index = array.indexOf(element);
Trick 22Convert a number to a string with leading zerosconst strWithZeros = num.toString().padStart(width, '0');const num = 42; const strWithZeros = num.toString().padStart(4, '0');
Trick 23Swap the values of two variableslet temp = a; a = b; b = temp;javascript let a = 1; let b = 2; let temp = a; a = b; b = temp;
Trick 24Truncate a string to a specified lengthconst truncated = string.slice(0, maxLength);const string = 'This is a long string'; const maxLength = 10; const truncated = string.slice(0, maxLength);
Trick 25Calculate the factorial of a numberfunction factorial(n) { return n <= 1 ? 1 : n * factorial(n - 1); }const result = factorial(5);

26-50

TrickPurposeSyntaxExample
Trick 26Convert a string to a numberconst num = parseFloat(string);const string = '3.14'; const num = parseFloat(string);
Trick 27Capitalize the first letter of a stringconst capitalized = string.charAt(0).toUpperCase() + string.slice(1);const string = 'hello'; const capitalized = string.charAt(0).toUpperCase() + string.slice(1);
Trick 28Check if an element exists in the DOMconst elementExists = !!document.querySelector(selector);const elementExists = !!document.querySelector('.my-element');
Trick 29Convert an object to a JSON stringconst jsonString = JSON.stringify(obj);const obj = { name: 'John', age: 30 }; const jsonString = JSON.stringify(obj);
Trick 30Parse a JSON string to an objectconst obj = JSON.parse(jsonString);const jsonString = '{"name":"John","age":30}'; const obj = JSON.parse(jsonString);
Trick 31Sort an array of objects by a propertyarray.sort((a, b) => a.property - b.property);javascript const people = [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }]; people.sort((a, b) => a.age - b.age);
Trick 32Get the current URLconst currentURL = window.location.href;const currentURL = window.location.href;
Trick 33Execute a function after a delaysetTimeout(() => { /* code to execute */ }, delayInMilliseconds);javascript setTimeout(() => { console.log('Delayed function executed!'); }, 2000);
Trick 34Remove whitespace from a stringconst trimmed = string.replace(/\s+/g, '');const string = ' Hello, world! '; const trimmed = string.replace(/\s+/g, '');
Trick 35Get the current timestamp (milliseconds)const timestamp = Date.now();const timestamp = Date.now();
Trick 36Calculate the difference between two datesconst differenceInDays = Math.floor((date2 - date1) / (1000 * 60 * 60 * 24));javascript const date1 = new Date('2023-09-01'); const date2 = new Date('2023-09-10'); const differenceInDays = Math.floor((date2 - date1) / (1000 * 60 * 60 * 24));
Trick 37Check if a number is an integerconst isInteger = Number.isInteger(num);const num = 42; const isInteger = Number.isInteger(num);
Trick 38Get the current day of the weekconst dayOfWeek = new Date().getDay();const dayOfWeek = new Date().getDay();
Trick 39Find the smallest number in an arrayconst min = Math.min(...array);const numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; const min = Math.min(...numbers);
Trick 40Convert an array to a comma-separated stringconst csvString = array.join(',');const array = ['apple', 'banana', 'cherry']; const csvString = array.join(',');
Trick 41Get the current time in HH
format
const time = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });const time = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
Trick 42Create a copy of an arrayconst copy = array.slice();const originalArray = [1, 2, 3]; const copy = originalArray.slice();
Trick 43Calculate the square root of a numberconst sqrt = Math.sqrt(num);const num = 16; const sqrt = Math.sqrt(num);
Trick 44Check if a function is definedconst isDefined = typeof func === 'function';const isDefined = typeof myFunction === 'function';
Trick 45Generate a random hexadecimal colorconst randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);const randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);
Trick 46Convert a string to title case`const titleCase = string.toLowerCase().replace(/^(.)\s+(.)/g, ($1) => $1.toUpperCase());`
Trick 47Check if an array contains only unique valuesconst isUnique = array.length === new Set(array).size;const array = [1, 2, 3, 4, 5]; const isUnique = array.length === new Set(array).size;
Trick 48Get the current monthconst currentMonth = new Date().getMonth() + 1;const currentMonth = new Date().getMonth() + 1;
Trick 49Get a random item from an arrayconst randomItem = array[Math.floor(Math.random() * array.length)];const array = [1, 2, 3, 4, 5]; const randomItem = array[Math.floor(Math.random() * array.length)];
Trick 50Convert a string with spaces to kebab caseconst kebabCase = string.replace(/\s+/g, '-').toLowerCase();const string = 'This is a Test String'; const kebabCase = string.replace(/\s+/g, '-').toLowerCase();

51-75

TrickPurposeSyntaxExample
Trick 51Check if a string starts with a substringconst startsWith = string.startsWith(substring);const string = 'Hello, world!'; const startsWith = string.startsWith('Hello');
Trick 52Check if a string ends with a substringconst endsWith = string.endsWith(substring);const string = 'Hello, world!'; const endsWith = string.endsWith('world!');
Trick 53Convert a number to a binary stringconst binaryString = num.toString(2);const num = 42; const binaryString = num.toString(2);
Trick 54Check if a string is empty or contains only whitespaceconst isEmptyOrWhitespace = string.trim() === '';const string = ' '; const isEmptyOrWhitespace = string.trim() === '';
Trick 55Check if an array contains a specific objectconst containsObject = array.some(item => item === object);const array = [{ id: 1 }, { id: 2 }, { id: 3 }]; const object = { id: 2 }; const containsObject = array.some(item => item.id === object.id);
Trick 56Get the first N elements of an arrayconst firstN = array.slice(0, N);const array = [1, 2, 3, 4, 5]; const firstN = array.slice(0, 3);
Trick 57Get the last N elements of an arrayconst lastN = array.slice(-N);const array = [1, 2, 3, 4, 5]; const lastN = array.slice(-3);
Trick 58Swap the values of two objectsjavascript const temp = {...obj1}; Object.assign(obj1, obj2); Object.assign(obj2, temp);javascript const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const temp = { ...obj1 }; Object.assign(obj1, obj2); Object.assign(obj2, temp);
Trick 59Remove an element from an array by valuearray = array.filter(item => item !== value);let array = [1, 2, 3, 4, 5]; const value = 3; array = array.filter(item => item !== value);
Trick 60Check if an array is a subset of another arrayconst isSubset = subset.every(item => array.includes(item));const array = [1, 2, 3, 4, 5]; const subset = [2, 3]; const isSubset = subset.every(item => array.includes(item));
Trick 61Find the index of the maximum value in an arrayconst maxIndex = array.indexOf(Math.max(...array));const array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; const maxIndex = array.indexOf(Math.max(...array));
Trick 62Calculate the average of an arrayconst average = array.reduce((acc, val) => acc + val, 0) / array.length;const array = [1, 2, 3, 4, 5]; const average = array.reduce((acc, val) => acc + val, 0) / array.length;
Trick 63Reverse the order of words in a stringconst reversedWords = string.split(' ').reverse().join(' ');const string = 'Hello, world!'; const reversedWords = string.split(' ').reverse().join(' ');
Trick 64Convert a number to currency formatconst currencyFormatted = num.toFixed(2);const num = 42.567; const currencyFormatted = num.toFixed(2);
Trick 65Create a unique identifier (UUID)```javascript const uuid = ‘xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx’.replace(/[xy]/g, function(c) { const r = Math.random() * 160, v = c == ‘x’ ? r : (r & 0x3
Trick 66Convert a string with hyphens to camelCaseconst camelCase = string.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());const string = 'this-is-a-test'; const camelCase = string.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
Trick 67Check if a value is a JavaScript arrayconst isArray = Array.isArray(value);const value = [1, 2, 3]; const isArray = Array.isArray(value);
Trick 68Deep copy an objectconst deepCopy = JSON.parse(JSON.stringify(object));const object = { a: 1, b: { c: 2 } }; const deepCopy = JSON.parse(JSON.stringify(object));
Trick 69Calculate the length of an object (number of properties)const length = Object.keys(obj).length;const obj = { a: 1, b: 2, c: 3 }; const length = Object.keys(obj).length;
Trick 70Check if an element is visible in the viewport```javascript const isVisible = (element) => { const rect = element.getBoundingClientRect(); return (rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight
Trick 71Find the median value in an arrayjavascript const median = (arr) => { const mid = Math.floor(arr.length / 2), nums = [...arr].sort((a, b) => a - b); return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; };javascript const numbers = [5, 1, 3, 9, 2]; const median = (arr) => { const mid = Math.floor(arr.length / 2), nums = [...arr].sort((a, b) => a - b); return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; }; median(numbers);
Trick 72Encode a URL parameterconst encodedParam = encodeURIComponent(param);const param = 'user input'; const encodedParam = encodeURIComponent(param);
Trick 73Check if a value is a primitiveconst isPrimitive = (value !== Object(value));const isPrimitive = (42 !== Object(42));
Trick 74Create an array with a sequence of numbersconst sequence = Array.from({ length: n }, (_, i) => i + start);const n = 5; const start = 1; const sequence = Array.from({ length: n }, (_, i) => i + start);
Trick 75Check if a year is a leap year`const isLeapYear = (year % 4 === 0 && year % 100 !== 0)

76-100

TrickPurposeSyntaxExample
Trick 76Create an array with unique valuesconst uniqueArray = [...new Set(array)];const array = [1, 2, 2, 3, 3, 4]; const uniqueArray = [...new Set(array)];
Trick 77Round a number to a specified decimal placeconst rounded = Number(number.toFixed(decimalPlaces));const number = 3.14159; const decimalPlaces = 2; const rounded = Number(number.toFixed(decimalPlaces));
Trick 78Convert a string to a date objectconst date = new Date(string);const dateString = '2023-09-17'; const date = new Date(dateString);
Trick 79Generate a random integer within a rangeconst randomInt = Math.floor(Math.random() * (max - min + 1)) + min;const min = 1; const max = 10; const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
Trick 80Remove duplicates from an array using a Setconst uniqueArray = [...new Set(array)];const array = [1, 2, 2, 3, 3, 4]; const uniqueArray = [...new Set(array)];
Trick 81Get the current yearconst currentYear = new Date().getFullYear();const currentYear = new Date().getFullYear();
Trick 82Get the current month (zero-based)const currentMonth = new Date().getMonth();const currentMonth = new Date().getMonth();
Trick 83Get the current day of the monthconst currentDay = new Date().getDate();const currentDay = new Date().getDate();
Trick 84Sort an array of strings alphabeticallyconst sortedArray = array.sort();const array = ['banana', 'apple', 'cherry']; const sortedArray = array.sort();
Trick 85Generate a random color in RGB formatconst randomColor = 'rgb(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ')';const randomColor = 'rgb(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ')';
Trick 86Check if an element is an arrayconst isArray = Array.isArray(element);const element = [1, 2, 3]; const isArray = Array.isArray(element);
Trick 87Get the current timestamp (seconds)const timestamp = Math.floor(Date.now() / 1000);const timestamp = Math.floor(Date.now() / 1000);
Trick 88Replace all occurrences of a character in a stringconst replaced = string.replace(/char/g, 'replacement');const string = 'a-b-c-d'; const replaced = string.replace(/-/g, '_');
Trick 89Calculate the distance between two pointsjavascript const distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));javascript const x1 = 0, y1 = 0, x2 = 3, y2 = 4; const distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
Trick 90Create a function with default parametersjavascript function greet(name = 'Anonymous') { return `Hello, ${name}!`; }javascript function greet(name = 'Anonymous') { return `Hello, ${name}!`; } const message = greet('Alice');
Trick 91Get the current time in HH:MM
format
javascript const now = new Date(); const formattedTime = now.toLocaleTimeString('en-US');javascript const now = new Date(); const formattedTime = now.toLocaleTimeString('en-US');
Trick 92Check if a value is NaNconst isNaN = Number.isNaN(value);const value = 'Not a number'; const isNaN = Number.isNaN(value);
Trick 93Create a random alphanumeric stringjavascript const randomString = Math.random().toString(36).substring(2, 10);javascript const randomString = Math.random().toString(36).substring(2, 10);
Trick 94Find the index of the minimum value in an arrayconst minIndex = array.indexOf(Math.min(...array));const array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; const minIndex = array.indexOf(Math.min(...array));
Trick 95Convert a string to an array of wordsconst words = string.split(' ');const string = 'Hello world'; const words = string.split(' ');
Trick 96Remove leading and trailing whitespace from a stringconst trimmed = string.trim();const string = ' Trim me '; const trimmed = string.trim();
Trick 97Check if an array contains only truthy valuesconst isTruthy = array.every(Boolean);const array = [true, 1, 'hello', 42]; const isTruthy = array.every(Boolean);
Trick 98Get the current time in milliseconds since epochconst currentTimeMillis = Date.now();const currentTimeMillis = Date.now();
Trick 99Find the index of the first occurrence of an element in an arrayconst index = array.indexOf(element);const array = ['apple', 'banana', 'cherry']; const element = 'banana'; const index = array.indexOf(element);
Trick 100Convert a string to an array of charactersconst charArray = [...string];const string = 'hello'; const charArray = [...string];