Table of Contents
Code Snippet 1 - Adding Two Numbers & Converting Strings to Numbers
Adding two numbers is one of the most basic operations in programming. In Javascript, you can easily achieve this using the "+" operator. Here's an example:
const num1 = 5; const num2 = 10; const sum = num1 + num2; console.log(sum); // Output: 15
You can also add two numbers using the parseInt()
function to convert strings to numbers:
const num1 = "5"; const num2 = "10"; const sum = parseInt(num1) + parseInt(num2); console.log(sum); // Output: 15
Related Article: How to Create a Countdown Timer with Javascript
Code Snippet 2 - Checking if a String Contains a Substring
Often, you need to check if a string contains a specific substring. Javascript provides the includes()
method to accomplish this. Here's an example:
const str = "Hello, World!"; const substring = "World"; const containsSubstring = str.includes(substring); console.log(containsSubstring); // Output: true
You can also use the indexOf()
method to check if a string contains a substring. It returns the index of the first occurrence of the substring, or -1 if the substring is not found:
const str = "Hello, World!"; const substring = "World"; const containsSubstring = str.indexOf(substring) !== -1; console.log(containsSubstring); // Output: true
Code Snippet 3 - Converting Strings to Numbers
In Javascript, you can convert strings to numbers using the parseInt()
and parseFloat()
functions. The parseInt()
function converts a string to an integer, while the parseFloat()
function converts a string to a floating-point number. Here's an example:
const str1 = "10"; const num1 = parseInt(str1); console.log(num1); // Output: 10 const str2 = "3.14"; const num2 = parseFloat(str2); console.log(num2); // Output: 3.14
Code Snippet 4 - Removing Duplicates from an Array
To remove duplicates from an array, you can use the filter()
method along with the indexOf()
method. Here's an example:
const array = [1, 2, 3, 2, 4, 5, 1, 3]; const uniqueArray = array.filter((value, index, self) => { return self.indexOf(value) === index; }); console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Alternatively, you can use the Set
object to remove duplicates from an array:
const array = [1, 2, 3, 2, 4, 5, 1, 3]; const uniqueArray = [...new Set(array)]; console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Related Article: Executing a React Component in a JavaScript File
Code Snippet 5 - Checking if an Array Contains a Specific Value
To check if an array contains a specific value, you can use the includes()
method. Here's an example:
const array = [1, 2, 3, 4, 5]; const value = 3; const containsValue = array.includes(value); console.log(containsValue); // Output: true
You can also use the indexOf()
method to check if an array contains a specific value. It returns the index of the first occurrence of the value, or -1 if the value is not found:
const array = [1, 2, 3, 4, 5]; const value = 3; const containsValue = array.indexOf(value) !== -1; console.log(containsValue); // Output: true
Code Snippet 6 - Reversing a String
To reverse a string in Javascript, you can use the split()
, reverse()
, and join()
methods. Here's an example:
const str = "Hello, World!"; const reversedStr = str.split("").reverse().join(""); console.log(reversedStr); // Output: "!dlroW ,olleH"
Code Snippet 7 - Finding the Maximum and Minimum Values in an Array
To find the maximum and minimum values in an array, you can use the Math.max()
and Math.min()
functions along with the spread operator. Here's an example:
const array = [1, 2, 3, 4, 5]; const max = Math.max(...array); const min = Math.min(...array); console.log(max); // Output: 5 console.log(min); // Output: 1
Code Snippet 8 - Sorting an Array in Ascending and Descending Order
To sort an array in ascending and descending order, you can use the sort()
method along with a compare function. Here's an example:
const array = [3, 1, 4, 2, 5]; const ascendingOrder = array.sort((a, b) => a - b); const descendingOrder = array.sort((a, b) => b - a); console.log(ascendingOrder); // Output: [1, 2, 3, 4, 5] console.log(descendingOrder); // Output: [5, 4, 3, 2, 1]
Related Article: How To Validate An Email Address In Javascript
Code Snippet 9 - Checking if an Object is Empty
To check if an object is empty, you can use the Object.keys()
method. If the length of the keys array is 0, then the object is empty. Here's an example:
const obj1 = {}; const obj2 = { name: "John", age: 30 }; const isEmpty1 = Object.keys(obj1).length === 0; const isEmpty2 = Object.keys(obj2).length === 0; console.log(isEmpty1); // Output: true console.log(isEmpty2); // Output: false
Code Snippet 10 - Generating Random Numbers
To generate random numbers in Javascript, you can use the Math.random()
function. Here's an example:
const randomNum = Math.random(); console.log(randomNum); // Output: a random number between 0 and 1
If you want to generate random numbers within a specific range, you can use the following formula:
const min = 1; const max = 10; const randomNumInRange = Math.floor(Math.random() * (max - min + 1)) + min; console.log(randomNumInRange); // Output: a random number between 1 and 10
Code Snippet 11 - Capitalizing the First Letter of a String
To capitalize the first letter of a string in Javascript, you can use the charAt()
and toUpperCase()
methods. Here's an example:
const str = "hello, world!"; const capitalizedStr = str.charAt(0).toUpperCase() + str.slice(1); console.log(capitalizedStr); // Output: "Hello, world!"
Code Snippet 12 - Finding the Length of an Object
To find the length of an object in Javascript, you can use the Object.keys()
method. The length of the keys array represents the number of properties in the object. Here's an example:
const obj = { name: "John", age: 30 }; const length = Object.keys(obj).length; console.log(length); // Output: 2
Related Article: AI Implementations in Node.js with TensorFlow.js and NLP
Code Snippet 13 - Checking if a Number is Even or Odd
To check if a number is even or odd in Javascript, you can use the modulo operator (%). If the number modulo 2 is 0, then it's even. Otherwise, it's odd. Here's an example:
const num = 7; const isEven = num % 2 === 0; const isOdd = num % 2 !== 0; console.log(isEven); // Output: false console.log(isOdd); // Output: true
Code Snippet 14 - Trimming Whitespace from a String
To trim whitespace from the beginning and end of a string in Javascript, you can use the trim()
method. Here's an example:
const str = " Hello, World! "; const trimmedStr = str.trim(); console.log(trimmedStr); // Output: "Hello, World!"
Code Snippet 15 - Converting a String to Title Case
To convert a string to title case in Javascript, you can use a combination of the split()
, map()
, and join()
methods along with the charAt()
and toUpperCase()
methods. Here's an example:
const str = "hello, world!"; const titleCaseStr = str.split(" ").map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(" "); console.log(titleCaseStr); // Output: "Hello, World!"
Code Snippet 16 - Checking if a Year is a Leap Year
To check if a year is a leap year in Javascript, you can use the modulo operator (%) and logical operators. Here's an example:
const year = 2020; const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; console.log(isLeapYear); // Output: true
Related Article: How to Get the Value of Text Input Field in Javascript
Code Snippet 17 - Calculating the Factorial of a Number
To calculate the factorial of a number in Javascript, you can use a recursive function. Here's an example:
function factorial(num) { if (num === 0 || num === 1) { return 1; } else { return num * factorial(num - 1); } } const num = 5; const factorialNum = factorial(num); console.log(factorialNum); // Output: 120
Code Snippet 18 - Calculating the Fibonacci Sequence
To calculate the Fibonacci sequence in Javascript, you can use a recursive function. Here's an example:
function fibonacci(num) { if (num <= 1) { return num; } else { return fibonacci(num - 1) + fibonacci(num - 2); } } const num = 6; const fibonacciNum = fibonacci(num); console.log(fibonacciNum); // Output: 8
Code Snippet 19 - Checking if a Number is Prime
To check if a number is prime in Javascript, you can use a for loop to iterate from 2 to the square root of the number. If the number is divisible by any of the values in this range, it's not prime. Here's an example:
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; } const num = 17; const isPrimeNum = isPrime(num); console.log(isPrimeNum); // Output: true
Code Snippet 20 - Finding the Longest Word in a String
To find the longest word in a string in Javascript, you can use the split()
method to convert the string into an array of words. Then, you can use the reduce()
method to find the word with the maximum length. Here's an example:
const str = "The quick brown fox jumps over the lazy dog"; const longestWord = str.split(" ").reduce((prev, current) => (prev.length > current.length) ? prev : current); console.log(longestWord); // Output: "quick"
Related Article: How To Check If A String Contains A Substring In Javascript
Code Snippet 21 - Reversing the Order of Words in a String
To reverse the order of words in a string in Javascript, you can use the split()
and reverse()
methods. Here's an example:
const str = "The quick brown fox"; const reversedStr = str.split(" ").reverse().join(" "); console.log(reversedStr); // Output: "fox brown quick The"
Code Snippet 22 - Converting a Number to Roman Numerals
To convert a number to Roman numerals in Javascript, you can use a combination of if-else statements and a lookup table. Here's an example:
function convertToRoman(num) { const romanNumerals = { 1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I" }; let result = ""; for (let value in romanNumerals) { while (num >= value) { result += romanNumerals[value]; num -= value; } } return result; } const num = 36; const romanNum = convertToRoman(num); console.log(romanNum); // Output: "XXXVI"
Code Snippet 23 - Generating a Random Password
To generate a random password in Javascript, you can use a combination of string manipulation and random number generation. Here's an example:
function generateRandomPassword(length) { const characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()"; let password = ""; for (let i = 0; i < length; i++) { const randomIndex = Math.floor(Math.random() * characters.length); password += characters[randomIndex]; } return password; } const passwordLength = 8; const randomPassword = generateRandomPassword(passwordLength); console.log(randomPassword); // Output: a randomly generated password
Code Snippet 24 - Checking if a String is Palindrome
To check if a string is a palindrome in Javascript, you can compare the string with its reversed version. Here's an example:
function isPalindrome(str) { const reversedStr = str.split("").reverse().join(""); return str === reversedStr; } const str = "madam"; const isPalindromeStr = isPalindrome(str); console.log(isPalindromeStr); // Output: true
Related Article: How to Use date-fns: the JavaScript date utility library
Code Snippet 25 - Converting Temperature Units
To convert temperature units in Javascript, you can use the following formulas:
- Celsius to Fahrenheit: F = (C * 9/5) + 32
- Fahrenheit to Celsius: C = (F - 32) * 5/9
Here's an example:
function celsiusToFahrenheit(celsius) { return (celsius * 9/5) + 32; } function fahrenheitToCelsius(fahrenheit) { return (fahrenheit - 32) * 5/9; } const celsius = 25; const fahrenheit = celsiusToFahrenheit(celsius); console.log(fahrenheit); // Output: 77 const convertedCelsius = fahrenheitToCelsius(fahrenheit); console.log(convertedCelsius); // Output: 25