Skip to content

Instantly share code, notes, and snippets.

@verticalgrain
Last active March 31, 2021 15:36
Show Gist options
  • Save verticalgrain/e2308a6011e23858949e16887fdcf624 to your computer and use it in GitHub Desktop.
Save verticalgrain/e2308a6011e23858949e16887fdcf624 to your computer and use it in GitHub Desktop.
Javascript Cheat Sheet
const myobject = {}
myobject[ key ] = value
// { key: value }
// Add element to array
const myarray = []
myarray.push(value1)
myarray.push(value2)
// [value1,value2]
// Add individual members of array into array
// array1 = [9]
// array2 = [1,5,2,9,5]
array1.push.apply(array1, array2(;
// array1 = [9,1,5,2,9,5]
// Remove element from array
const myElement = 4;
let myArray = [1,4,5,7,9,22];
const index = myArray.indexOf(myElement);
myArray.splice(index,1);
// [1,5,7,9,22]
// Create object and add to array
const myarray = []
const element = {}
element.id = 10
element.quantity = 1
myarray.push({myelement: element})
// [{ myelement: { id: 10, quantity: 1} }]
// Assign object property name as a variable using bracket notation
const name = 'property name';
myarray.push({[name]: element})
// data = {...}
const siteContent = []
siteContent.push({
key: data.name,
content: data['elements'][0]
})
// Modify value of an object in an array of objects
//Initailize array of objects.
let myArray = [
{id: 0, name: "Jhon"},
{id: 1, name: "Sara"},
{id: 2, name: "Domnic"},
{id: 3, name: "Bravo"}
],
//Find index of specific object using findIndex method.
objIndex = myArray.findIndex((obj => obj.id == 1));
//Update object's name property.
myArray[objIndex].name = "Laila"
// Fetch
fetch(source)
.then(function(response) {
if (response.status >= 400) {
throw new Error("The server doesnt seem available right now");
}
return response.json();
})
.then(function(response) {
console.log(response.id);
})
// For loop
for (let item of items) {
console.log(item);
}
// forEach
// Iterate over array of objects
data.messages.forEach(function(message){
console.log(message)
});
// Merge objects with assign
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
// Merge arrays of objects with concat
var arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"});
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
var result=arr1.concat(arr2);
// result: [{name: "lang", value: "English"}, {name: "age", value: "18"}, {name : "childs", value: '5'}, {name: "lang", value: "German"}]
// Check if a value is in an array
[1, 2, 3].includes(2); // returns true
['sport','news','decor'].includes('games'); // returns false
// Check if a value is in an object
var mycar = {make: 'Honda', model: 'Accord', year: 1998};
'make' in mycar; // returns true
// Localstorage
// Get an array from localstorage, with fallback
var selectedSourcesLocalstorage = JSON.parse(localStorage.getItem( 'selectedSources' )) || ['bbc-news','cnn','google-news'];
// Set an array to localstorage
localStorage.setItem( 'selectedSources', JSON.stringify(selectedSources) );
// Check for empty string
if(data !== null && data !== '') {
// do something
}
// Check if an array contains an object with an attribute that matches a given value
var givenValueId = 12;
var filteredArray = arrayOfOjbects.filter(item => item.id === givenValueId );// filteredArray will be an array
// Check if an array contains an object with an attribute that matches a given value,
// And return the result as a boolean value
var givenValueId = 12;
var filteredArray = !arrayOfOjbects.filter(item => item.id === givenValueId );// filteredArray will be a boolean true / false
// Loop n number of times
var n = 64;
[...Array(n)].map((e, i) => <span className="test" key={i}>test</span>)
// Dates
// Make a Javascript date object in the users current timezone, with the current date/time
const dateTime = new Date();
// Make a javascript date object in the users current timezone, from a string.
const dateTime = new Date( '2019-06-15T14:15:00' ); // year-month-dayThour-minute-second
const dateTime = new Date( '2019', '06', '15', '14', '15', '00' ); // year, month, day, hour, minute, seconds, milliseconds
// Make a javascript date object in UTC, from a string
// The Z stands for zero time offset
const dateTime = new Date( '2019-06-15T14:15:00Z' ); // year-month-dayThour-minute-second
// Make a javascript date object in UTC, from a string
// The Z stands for zero time offset
const dateTime = new Date( '2019-06-15T14:15:00Z' ); // year-month-dayThour-minute-second
// Make a javascript date object in a specific timezone
// The number of hours to offset follows the date string - in this case -8 hours
const dateTime = new Date( '2019-06-15T14:15:00-08:00' ); // year-month-dayThour-minute-second
// Double Negation operator. Converts anything to boolean.
// Returns false if the value is 0, null, "", or undefined, otherwise returns true
!! testVar
// Short circuit AND logical operator
&& <TestComponent />
// Combine double negationi and short circuit AND operators
!! testVar && testVar
// Test an array to confirm it is an array and it has values
if ( !arrayName || !( Array.isArray( arrayName ) && arrayName.length > 0 ) ) {
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment