Useful Code Snippets (JS)
Create a random number between 1-6
const randomNumber = Math.floor(Math.random() * 6) + 1 // 0-5 -> 1-6
function getRandomInt(x){
return Math.floor(Math.random() * x);
}
getRandomInt(10)
Covert a string to an array
let str = "Apple";
const arr = str.split("")
Covert an array to a string
Concatenation of all elements of the array:
["e", "l", "p", "p", "a"].join("")
Swap Operation
let temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
Removing Spaces from a character
function cleanUpSpaces(str) {
return str.replace(/\s/g, '')
}
Use 'for of' Loop to iterate through a string or an array
- Use
for of
Loop to iterate through a string or an array
let string = "Ambreen" for(let char of string){ console.log(char) }
Use 'for in' Loop to iterate through an object
const charMap = {
'car': 'Toyota Corolla',
'model': '2022'
}
for(let key in charMap){
console.log('Key: ', key, 'Value: ', charMap[key])
}
Working with key/values in JS object
const keys = Object.keys(courses);
// print all keys
console.log(keys);
// [ 'java', 'javascript', 'nodejs', 'php' ]
// iterate over object
keys.forEach((key, index) => {
console.log(`${key}: ${courses[key]}`);
});
Using indexOf method to determine index position
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison')); //1
Sort a number Array
// https://www.w3schools.com/js/js_array_sort.asp
// By default, the sort() function sorts values as strings.
// You can fix this by providing a compare function
array.sort((a,b) => a-b);
Build Character Map
function buildCharMap(str) {
const charMap = {};
for (let char of str) {
charMap[char] = charMap[char] + 1 || 1;
}
return charMap;
}
Compare the size of 2 character maps
if (Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
return false;
}
Getting values for all keys from a hash map
Object.values(anagramMap)
Converting Set to array
function intersection(nums1, nums2) {
const set = new Set(nums1);
const filteredSet = new Set(nums2.filter((n) => set.has(n)));
return [ ...filteredSet ];
}
Filtering out the alphabet character only
// Filtering out the alphabet character only:
function filterAlphbetOnly(str){
const regex = /[a-zA-Z]/g;
let filteredArr = str.match(regex);
let reversedArr = reverseArr(filteredArr);
return reversedArr;
}
JS Filter Method
const age = [23, 45, 20, 20, 55, 65];
// console.log(age.filter(age40AndAbove));
console.log(age.filter((age)=> {
return age >= 40
}));
Merge two or more arrays
The concat()
method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
Common Mathematics functions
Math.abs()
The Math.abs() function returns the absolute value of a number. That is, it returns x if x is positive or zero, and the negation of x if x is negative.
Math.sign()
The Math.sign() function returns either a positive or negative +/- 1, indicating the sign of a number passed into the argument. If the number passed into Math.sign() is 0, it will return a +/- 0. Note that if the number is positive, an explicit (+) will not be returned. (returns 1 if number is positive else returns -1)
Math.max()
The Math.max() function returns the largest of the zero or more numbers given as input parameters
The Math.floor()
function returns the largest integer less than or equal to a given number.
Using filter Function
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const filterList = (arr) => {
const filteredIntegers = arr.filter(num => Number.isInteger(num) && num > 0);
return filteredIntegers;
};
const filteredIntegers = filterList(realNumberArray);
console.log(filteredIntegers);
Using map & filter functions together
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
const squaredIntegers = arr.filter(num => Number.isInteger(num) && num > 0).map(x => x * x);
return squaredIntegers;
};
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
Setting default value
const increment = (function() {
return function increment(number, value = 1) {
return number + value;
};
})();
console.log(increment(5, 2));
console.log(increment(5));
Using Rest Operator for Function Parameter
const sum = (function() {
return function sum(...args) {
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3, 4));
Using the Spread Operator to make a copy of an array
- Spreads out an array (i.e. makes a copy) into its individual parts
//Original array is mutated
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
(function() {
arr2 = arr1;
arr1[0] = 'potato'
})();
console.log(arr2); //outputs: ["potato", "FEB", "MAR", "APR", "MAY"] as both arr1 & arr2 are still pointing to the same array.
//Here arr2 will NOT be equal to arr1 instead it will be equal to the content of the arr1
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
(function() {
arr2 = [...arr1];
arr1[0] = 'potato'
})();
console.log(arr2);
Destructuring
var voxel = {x: 3.6, y: 7.4, z: 6.54 };
var x = voxel.x; // x = 3.6
var y = voxel.y; // y = 7.4
var z = voxel.z; // z = 6.54
const { x : a, y : b, z : c } = voxel; // a = 3.6, b = 7.4, c = 6.54
const AVG_TEMPERATURES = {
today: 77.5,
tomorrow: 79
};
function getTempOfTmrw(avgTemperatures) {
const { tomorrow : tempOfTomorrow } = avgTemperatures; // change this line
return tempOfTomorrow;
}
console.log(getTempOfTmrw(AVG_TEMPERATURES)); // should be 79
Destructuring from Nested Objects
const LOCAL_FORECAST = {
today: { min: 72, max: 83 },
tomorrow: { min: 73.3, max: 84.6 }
};
function getMaxOfTmrw(forecast) {
"use strict";
const { tomorrow : { max : maxOfTomorrow }} = forecast;
return maxOfTomorrow;
}
console.log(getMaxOfTmrw(LOCAL_FORECAST));
Use Destructuring Assignment to assign variables from Arrays
const [z, x, , y] = [1, 2, 3, 4, 5, 6];
console.log(z, x, y);
//Output: 1,2,4
//Uisng destructuring to switch values
let a = 8, b = 6;
(() => {
"use strict";
[a, b] = [b, a]
})();
console.log(a); //6
console.log(b); //8
Using Destructuring Assignment with the Rest operator to Reassign Array Element
const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
const [ , , ...arr] = list;
return arr;
}
const arr = removeFirstTwo(source);
console.log(arr);
console.log(source);
//We can also assign the first two to some variables as below
const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
const [ a, b, ...arr] = list;
return arr;
}
const arr = removeFirstTwo(source);
console.log(arr);
console.log(source);
Use Destructuring Assignment to Pass an object as a Function's Parameters
const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85
};
const half = (function() {
return function half({ max, min }) {
return (max + min) / 2.0;
};
})();
console.log(stats);
console.log(half(stats));
Template Literals
function makeList(arr) {
const resultDisplayArray = [];
arr.forEach(element => resultDisplayArray.push(`<li class="text-warning">${element}</li>`))
console.log(resultDisplayArray)
return resultDisplayArray;
}
/**
* makeList(result.failure) should return:
* [ `<li class="text-warning">no-var</li>`,
* `<li class="text-warning">var-on-top</li>`,
* `<li class="text-warning">linebreak</li>` ]
**/
const resultDisplayArray = makeList(result.failure);
Write concise Object Literal Declaration uisng simple fileds
//LOng approach
const createPerson = (name, age, gender) => {
return {
name: name,
age: age,
gender: gender
};
};
console.log(createPerson("Zodiac Hasbro", 56, "male"));
//Using concise approach:
const createPerson = (name, age, gender) => ({ name, age, gender });
console.log(createPerson("Zodiac Hasbro", 56, "male"));
Write Concise Declarative function
//Concise Way
const bicycle = {
gear: 2,
setGear(newGear) {
"use strict";
this.gear = newGear;
}
};
bicycle.setGear(3);
console.log(bicycle.gear);
//Long form:
const bicycle = {
gear: 2,
setGear: function(newGear) {
"use strict";
this.gear = newGear;
}
};
bicycle.setGear(3);
console.log(bicycle.gear);
Use class Syntax to define a constructor function
//Using old way
var SpaceShuttle = function(targetPlanet){
this.targetPlanet = targetPlanet;
}
var zeus = new SpaceShuttle('Jupiter');
console.log(zeus.targetPlanet)
//New approach
class SpaceShuttle {
constructor(targetPlanet){
this.targetPlanet = targetPlanet;
}
}
var zeus = new SpaceShuttle('Jupiter');
console.log(zeus.targetPlanet)
//Another Example
function makeClass() {
class Vegetable {
constructor(name){
this.name = name;
}
}
return Vegetable;
}
const Vegetable = makeClass();
const carrot = new Vegetable('carrot');
console.log(carrot.name);
Using getter & setters to control an access to an object
class Book {
constructor(author) {
this._author = author;
}
// getter
get writer(){
return this._author;
}
// setter
set writer(updatedAuthor){
this._author = updatedAuthor;
}
}
//Another Example
function makeClass() {
class Thermostat {
constructor(temp) {
this._temp = 5/9 * (temp - 32);
}
get temperature(){
return this._temp;
}
set temperature(updatedTemp){
this._temp = updatedTemp;
}
}
return Thermostat;
}
const Thermostat = makeClass();
const thermos = new Thermostat(76);
let temp = thermos.temperature;
thermos.temperature = 26;
temp = thermos.temperature;
Use export to reuse a code block
const capitalizeString = (string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
}
export { capitalizeString };
export const foo = "bar";
export const bar = "foo";
Use * to import everything from a file
import * as capitalizeStrings from "capitalize_strings"
Create an Export fallback with export default
export default function subtract(x,y) {return x - y;}
Importing a Default Export
import subtract from "math_functions";