Intro – 50 JavaScript Code Snippets
JavaScript is a versatile and widely-used programming language that powers the dynamic and interactive features of websites and web applications. Whether you’re a seasoned developer or just getting started with JavaScript, having a collection of handy code snippets can save you time and effort in your coding journey. In this article, we’ll explore a variety of JavaScript code snippets and their practical applications.
Checking Variable Existence: Sometimes, you need to check if a variable exists before using it in your code. The following code snippet does just that:
if (typeof variableName !== 'undefined') {
// Do something with variableName
}
By using this snippet, you ensure that your code won’t throw errors when working with potentially undefined variables.
Getting the Current Date and Time: JavaScript allows you to retrieve the current date and time easily. This snippet is valuable when you need to display timestamps or work with date-related data.
const currentDate = new Date();
console.log(currentDate); // Example output: Sun Sep 18 2023 12:34:56 GMT+0000 (Coordinated Universal Time)
Converting a String to an Integer: You can convert a string to an integer using JavaScript.This snippet is handy for data conversion tasks.
const str = "42";
const num = parseInt(str);
console.log(num); // Example output: 42
Converting an Array-Like Object to an Array: JavaScript often works with array-like objects. Convert them to arrays like this:
const arrayLike = document.querySelectorAll('.some-class');
const newArray = Array.from(arrayLike);
Looping Through an Array with forEach: JavaScript arrays can be iterated using the forEach
method. This snippet simplifies array processing.
const array = [1, 2, 3, 4, 5];
array.forEach(item => {
// Do something with each item
console.log(item); // Example output: 1, 2, 3, 4, 5
});
Filtering Elements in an Array: Filtering elements in an array is a common task in JavaScript:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Example output: [2, 4]
Mapping Elements in an Array: Mapping elements in an array is another common operation:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // Example output: [2, 4, 6, 8, 10]
Finding the Maximum or Minimum Value in an Array: You can find the maximum and minimum values in an array using JavaScript:
const numbers = [10, 5, 8, 20, 3];
const maxNumber = Math.max(...numbers);
const minNumber = Math.min(...numbers);
console.log(maxNumber); // Example output: 20
console.log(minNumber); // Example output: 3
Checking if an Element Exists in an Array: Checking if an element exists in an array is straightforward:
const array = [1, 2, 3, 4, 5];
const elementToCheck = 3;
const exists = array.includes(elementToCheck);
console.log(exists); // Example output: true
Basic Error Handling with try…catch: Robust error handling is crucial in any JavaScript application. The try…catch block helps you handle errors gracefully. By using this snippet, you can prevent your application from crashing when unexpected errors occur.
try {
// Code that might throw an error
} catch (error) {
console.error(error);
}
Creating a New Object with Spread Operator: You can create a new object by spreading the properties of an existing object:
const originalObject = { key1: 'value1', key2: 'value2' };
const newObject = { ...originalObject, key3: 'value3' };
console.log(newObject); // Example output: { key1: 'value1', key2: 'value2', key3: 'value3' }
Destructuring Assignment: Destructuring assignment allows you to extract values from objects easily:
const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name); // Example output: 'John'
console.log(age); // Example output: 30
Converting an Object to JSON and Vice Versa:
JavaScript Object Notation (JSON) is a common data format used for data exchange. These snippets demonstrate how to work with JSON:
Converting an Object to JSON:
const object = { key: 'value' };
const jsonObject = JSON.stringify(object);
Parsing JSON to an Object:
const jsonString = '{"key":"value"}';
const parsedObject = JSON.parse(jsonString);
Getting the Length of an Array or String: You can easily obtain the length of an array or string:
const array = [1, 2, 3, 4, 5];
const length = array.length;
console.log(length); // Example output: 5
const str = "Hello, world!";
const strLength = str.length;
console.log(strLength); // Example output: 13
Concatenating Arrays: To combine two arrays, you can use the concat
method:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const concatenatedArray = array1.concat(array2);
console.log(concatenatedArray); // Example output: [1, 2, 3, 4, 5, 6]
Checking if a Value is an Array: To determine if a value is an array, you can use the Array.isArray
method:
const value = [1, 2, 3];
const isArray = Array.isArray(value);
console.log(isArray); // Example output: true
Removing an Item from an Array by Value: To remove an item from an array by its value, you can use the filter
method:
const numbers = [1, 2, 3, 4, 5];
const valueToRemove = 3;
const filteredArray = numbers.filter(num => num !== valueToRemove);
console.log(filteredArray); // Example output: [1, 2, 4, 5]
Convert an Array to a Comma-Separated String: To convert an array into a comma-separated string, you can use the join
method:
const fruits = ['apple', 'banana', 'cherry'];
const fruitString = fruits.join(', ');
console.log(fruitString); // Example output: 'apple, banana, cherry'
Check if a String Contains a Substring: You can check if a string contains a specific substring using the includes
method:
const text = 'Hello, world!';
const substring = 'world';
const containsSubstring = text.includes(substring);
console.log(containsSubstring); // Example output: true
Convert a String to Lowercase or Uppercase: JavaScript allows you to convert strings to lowercase or uppercase easily:
const originalString = 'Hello, World!';
const lowercaseString = originalString.toLowerCase();
const uppercaseString = originalString.toUpperCase();
console.log(lowercaseString); // Example output: 'hello, world!'
console.log(uppercaseString); // Example output: 'HELLO, WORLD!'
Remove Whitespace from the Beginning and End of a String: Trimming whitespace from a string can be done using the trim
method:
const stringWithWhitespace = ' Trim me! ';
const trimmedString = stringWithWhitespace.trim();
console.log(trimmedString); // Example output: 'Trim me!'
Check if an Object Has a Specific Property: You can determine if an object has a specific property using the in
operator:
const person = { name: 'Alice', age: 25 };
const hasProperty = 'name' in person;
console.log(hasProperty); // Example output: true
Get the Current URL: You can retrieve the current URL of a web page using:
const currentURL = window.location.href;
console.log(currentURL); // Example output: 'https://www.example.com/page'
Delay Execution Using setTimeout:
You can delay the execution of code using setTimeout
:
console.log('Start');
setTimeout(() => {
console.log('Delayed code');
}, 2000); // Delays execution for 2 seconds
console.log('End');
Calculating the Sum of Elements in an Array: You can calculate the sum of elements in an array using the reduce
method:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, current) => acc + current, 0);
console.log(sum); // Example output: 15
Converting a String to an Array of Characters: Convert a string to an array of characters like this:
const text = 'Hello';
const charArray = Array.from(text);
console.log(charArray); // Example output: ['H', 'e', 'l', 'l', 'o']
Checking if a Number is Even or Odd: Determine if a number is even or odd with a simple calculation:
const number = 7;
const isEven = number % 2 === 0;
console.log(isEven); // Example output: false
Creating a Function with Default Parameters: You can create functions with default parameters to provide fallback values:
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Example output: Hello, Guest!
greet('Alice'); // Example output: Hello, Alice!
Reversing a String: Reverse a string by converting it to an array of characters, reversing the array, and joining it back into a string:
const str = 'JavaScript';
const reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // Example output: 'tpircSavaJ'
Finding the Index of an Element in an Array: You can find the index of an element in an array using the indexOf
method:
const fruits = ['apple', 'banana', 'cherry'];
const indexOfBanana = fruits.indexOf('banana');
console.log(indexOfBanana); // Example output: 1
Creating an Object with Computed Property Names: You can create an object with computed property names:
const key = 'dynamicKey';
const value = 'dynamicValue';
const dynamicObject = { [key]: value };
console.log(dynamicObject); // Example output: { dynamicKey: 'dynamicValue' }
Sorting an Array of Numbers: Sort an array of numbers in ascending order:
const numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const sortedNumbers = numbers.sort((a, b) => a - b);
console.log(sortedNumbers); // Example output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
Converting a Number to a String with a Specific Number of Decimal Places: Convert a number to a string with a specific number of decimal places using the toFixed
method:
const num = 3.14159265;
const formattedNum = num.toFixed(2);
console.log(formattedNum); // Example output: '3.14'
Creating a New Array by Removing Duplicates: Remove duplicate values from an existing array while creating a new array:
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // Example output: [1, 2, 3, 4, 5]
Checking if a Value is a Prime Number: Determine if a value is a prime number using a custom function
function isPrime(num) {
if (num <= 1) return false;
if (num <= 3) return true;
if (num % 2 === 0 || num % 3 === 0) return false;
let i = 5;
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) return false;
i += 6;
}
return true;
}
console.log(isPrime(17)); // Example output: true
Getting the Current Timestamp (Milliseconds since Jan 1, 1970): Obtain the current timestamp in milliseconds:
const timestamp = Date.now();
console.log(timestamp); // Example output: (Current timestamp)
Finding the Intersection of Two Arrays: Find the common elements between two arrays:
const array1 = [1, 2, 3, 4];
const array2 = [3, 4, 5, 6];
const intersection = array1.filter(value => array2.includes(value));
console.log(intersection); // Example output: [3, 4]
Checking if an Array Contains Only Unique Values: Determine if an array contains only unique values using a custom function
function hasUniqueValues(arr) {
return new Set(arr).size === arr.length;
}
console.log(hasUniqueValues([1, 2, 3, 4, 5])); // Example output: true
Creating a Shallow Copy of an Array: Create a copy of an array without mutating the original array:
const originalArray = [1, 2, 3];
const copyArray = [...originalArray];
console.log(copyArray); // Example output: [1, 2, 3]
Generate a Range of Numbers in an Array: Sometimes you need an array of numbers within a specific range. You can achieve this using the Array.from
method along with the length
property and an iterator function
const start = 1;
const end = 5;
const rangeArray = Array.from({ length: end - start + 1 }, (_, i) => start + i);
console.log(rangeArray); // Example output: [1, 2, 3, 4, 5]
💁 Check out our other articles😃
👉 Mastering Modern JavaScript: Your Comprehensive Cheat Sheet ES6- ES11
👉 Creating a Toggle Switcher with Happy and Sad Faces using HTML, CSS, and JavaScript
Check if an Object is Empty: To check if an object is empty, you can count the number of its keys using Object.keys
. This function returns true
if the object has no properties and false
otherwise.
function isEmptyObject(obj) {
return Object.keys(obj).length === 0;
}
console.log(isEmptyObject({})); // Example output: true
Merge Two Objects: Merging two objects into one can be done using the spread operator (...
):
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObject = { ...obj1, ...obj2 };
console.log(mergedObject); // Example output: { a: 1, b: 3, c: 4 }
Generate a Random Hexadecimal Color: Creating random colors in hexadecimal format is useful for styling web elements dynamically
const randomHexColor = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
console.log(randomHexColor); // Example output: Random hexadecimal color code
Create an Array of Unique Values from Two Arrays: Combining and removing duplicates from two arrays can be accomplished using the Set
object
const array1 = [1, 2, 3];
const array2 = [3, 4, 5];
const uniqueArray = [...new Set([...array1, ...array2])];
console.log(uniqueArray); // Example output: [1, 2, 3, 4, 5]
Calculate the Factorial of a Number: Calculating the factorial of a number involves recursion
function factorial(n) {
if (n === 0 || n === 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // Example output: 120
Convert an Array of Strings to Lowercase: If you have an array of strings and want to convert them to lowercase, you can use the map
method. This code snippet converts each string in the array to lowercase.
const words = ['Hello', 'World', 'JavaScript'];
const lowercaseWords = words.map(word => word.toLowerCase());
console.log(lowercaseWords); // Example output: ['hello', 'world', 'javascript']
Check if a String is a Palindrome: A palindrome is a word or phrase that reads the same backward as forward. You can check if a string is a palindrome by cleaning it and comparing it to its reverse
function isPalindrome(str) {
const cleanStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
const reversedStr = cleanStr.split('').reverse().join('');
return cleanStr === reversedStr;
}
console.log(isPalindrome('racecar')); // Example output: true
Truncate a String to a Specified Length: To truncate a string to a specific length, you can use the slice
method
function truncateString(str, maxLength) {
if (str.length > maxLength) {
return str.slice(0, maxLength) + '...';
}
return str;
}
console.log(truncateString('Lorem ipsum dolor sit amet', 10)); // Example output: 'Lorem ipsu...'
Sum All Numbers in an Array Using the Reduce Method: To calculate the sum of all numbers in an array, you can use the reduce
method:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, current) => acc + current, 0);
console.log(sum); // Example output: 15
Shuffle an Array Randomly: To shuffle the elements of an array randomly, you can use the Fisher-Yates shuffle algorithm
function shuffleArray(array) {
const shuffledArray = [...array];
for (let i = shuffledArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
}
return shuffledArray;
}
console.log(shuffleArray([1, 2, 3, 4, 5])); // Example output: (Randomly shuffled array)
Get the File Extension from a File Path or URL: To extract the file extension from a file path or URL, you can use the split
method
function getFileExtension(filePath) {
return filePath.split('.').pop();
}
console.log(getFileExtension('document.pdf')); // Example output: 'pdf'
Calculate the Square Root of a Number: You can calculate the square root of a number using the Math.sqrt
method. This code calculates the square root of 25
and stores it in the squareRoot
variable.
const number = 25;
const squareRoot = Math.sqrt(number);
console.log(squareRoot); // Example output: 5
Find the Largest Element in an Array: To find the largest element in an array, you can use the Math.max
function along with the spread operator
const numbers = [10, 5, 8, 20, 3];
const maxNumber = Math.max(...numbers);
console.log(maxNumber); // Example output: 20
Check if a String Starts with a Specific Prefix: You can check if a string starts with a specific prefix using the startsWith
method
const str = 'Hello, world!';
const startsWithHello = str.startsWith('Hello');
console.log(startsWithHello); // Example output: true
These additional JavaScript code snippets expand your toolkit for common tasks, such as shuffling arrays, extracting file extensions, calculating square roots, finding the largest element in arrays, and checking string prefixes. Incorporate these snippets into your coding practices to make your JavaScript development more versatile and efficient.