JavaScript - astromechanic/cheat_sheets GitHub Wiki
- Return a new string which is count times longer
str.repeat(count);
-
Convert letter to number:
String.charCodeAt()
Method returns the Unicode of the character at a specified index (position) in a string.'a'.charCodeAt(0)
returns 97 -
String interpolation
let name = 'Masha';
let age = 25;
let message = `Hi there, my name is ${name} and I'm ${age} years old`;
- String.indexOf(char)
- Array.indexOf(element) Check if something is not in the string or array
let clothes = ['skirt', 't-shirt', 'jeans'];
console.log(clothes.indexOf('hat')); // -1
- Some useful array methods.
let numbers = [1, 3, 6, 12, 7];
let doubleNumbers = numbers.map(function(num){
return num * 2;
});
let oneDigitNumbers = numbers.filter(function(num){
return num < 10;
});
// every() - returns true if all elements in array satisfy a condition
let ages = [43, 18, 20, 22];
let isAllAdult = ages.every(function(item){
return item >= 18;
});
// some() - returns true if at least one element satisfy
// sort()
// reduce() - apply a function to every element and return a result
let scores = [3, 4, 4, 3, 5, 3, 5, 5];
let scoresSum = scores.reduce(function(previousItem, currentItem){
return previousItem + currentItem;
}, 0);
// forEach()
- Open json with fetch
function fetchJSONFile(path, callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
httpRequest.open('GET', path);
httpRequest.send();
}
- Some useful object and JSON methods.
let cart = {
cartLineItems: [
'white skirt',
'black skirt',
'jeans'
],
shippingMethod: {
shippingMethodId: "DHL",
shippingCost: 3.99
}
}
console.log(Object.keys(cart)); // returns array of keys
console.log(Object.values(cart)); // returns array of values
console.log(typeof JSON.stringify(cart)); // returns string
JSON.parse - gets a string and returns an object
let userInfo = '{"userAuthenticated": true, "firstName": "Jack", "lastName": "Smith"}';
console.log(JSON.parse(userInfo));
- Shallow copy. Copy elements of one array into another using spread operator. The arr2 remains unchanged when arr1 is changed. Shallow copy works only in one level like an array
let arr1 = [1, 2, 3];
let arr2 = [...arr1];
- Divide string into array
let greeting = "Hello";
let charList = [...greeting];
- Combine arrays and objects Only unique object properties are combined. If objects have the same properties, the right object overwrites them.
let arr1 = ["twitter", "facebook"];
let arr2 = ["google", "amazon"];
let arr3 = [...arr1, ...arr2];
- Instead of array.push()
let arr4 = [...arr3, "instagram"];
- Nested copy If there are more than 1 level, the spread operator doesn't work.
let users = [
{name: "Mike"},
{name: "Ann"}
];
Hack!
let registeredUsers = JSON.parse(JSON.stringify(users));
registeredUsers[0].name = "Sasha";
- Destructuring array
let actions = ['Add to cart', 'Buy', 'Cancel'];
let [addToCart, buy, cancel] = actions;
//console.log(addToCart);
- Destructuring object
let text = {
title: "My essay",
date: "23.10.2021",
author: "me"
}
let {title, date, author} = text;
The variables we get when destructuring an object is not a reference!
text.author = "Pushkin";
console.log(author); // me
function checkIsSuccess(data) {
return new Promise(function(resolve, reject){
if (data == "Success") {
return resolve('Success');
} else {
return reject('Unsuccess');
}
});
}
checkIsSuccess('Success').then(function(result){
console.log(result);
}).catch(function(error){
console.error(error);
});
Service call - fetch A service call is always an async promise call.
then() always returns a promise
fetch('https://api.github.com/users/karkranikhil').then(function(result){
// the result that we get is also a promise
// let's get the response!
return result.json();
}).then(function(response){
console.log(response);
});
Допустим, у нас есть два файла: app.js и utils.js. Мы хотим импортировать методы из utils.js в app.js. Как устроен файл utils.js:
function add(a, b) {
return a + b;
}
function minus(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
export {add, minus, multiply}
В тег <script> в html надо добавить type='module':
<script type='module' src='app.js'></script>
В app.js импортируем модуль:
import * as Utils from './utils.js'
Использование:
Utils.add(1,3));
Utils.minus(10,3));
querySelectorAll() - returns a NodeList! not an array! Array.from(allElements) - convert nodelist to array
Instead of document, we write this.template in LWC
document.getElementById('register').addEventListener('mouseover', handler);
function handler() {
console.log('Register');
}
function removeHandler() {
document.getElementById('register').removeEventListener('mouseover', handler);
}
Event bubbling and Event capturing bubbling - from bottom to top
const hello = () => console.log('Hello');
hello();
const add = (a, b) => {
return a + b;
}
Arrow functions solves the problem of pointing at this
let user = {
firstName: 'Ann',
lastName: 'James',
getFullName: function() {
console.log(this.firstName);
const fullName = () => {
arrow function know what _this_ is
console.log(`Full name is ${this.firstName} ${this.lastName}`);
}
fullName();
}
}
user.getFullName();