Skip to content

Instantly share code, notes, and snippets.

console.log(users[1]?.girl_friend?.name)
// output: undefined
const users = [
{
name: 'Nguyễn Hưng Khánh',
girl_friend: {
name: 'Nguyễn Thị Khánh',
address: 'Hà Nội'
}
},
{
name: 'Nguyễn Văn Khánh'
// Written as of ES2019
if (onError) { // Testing if onError really exists
onError();
}
// Using optional chaining with function calls
onError?.(); // no exception if onError is undefined
class User {
#salary = 1000;
}
const newUser = new User();
console.log(newUser.salary) // undefined
const number1 = 10;
const number2 = 0;
// Written as of ES2019
const score1 = number1 || 1;
console.log(score1); // 10
const score2 = number2 || 1;
console.log(score2); // 1
// Using nullish coalescing
// Written as of ES2019
await Promise.resolve(console.log('🎉')); // → SyntaxError: await is only valid in async function
(async function() {
await Promise.resolve(console.log('🎉')); // → 🎉
}());
// Top level await
await Promise.resolve(console.log('🎉')); // → 🎉
@daubattu
daubattu / hackerrank_solution_of_encryption_in_javascript.js
Created January 10, 2020 07:44
[Hackerrank] Solution of Encryption Shop in JavaScript - nguyenhungkhanh.com
// Complete the encryption function below.
function encryption(s) {
const ceil = Math.ceil(Math.sqrt(s.length));
let temp = s;
let array = [];
while(temp) {
array = array.concat(temp.substring(0, ceil));
temp = temp.substring(ceil)
@daubattu
daubattu / hackerrank_solution_of_modified_kaprekar_numbers_in_javascript.js
Created January 10, 2020 08:40
//[Hackerrank] Solution of Modified Kaprekar Numbers in JavaScript - nguyenhungkhanh.com
//[Hackerrank] Solution of Modified Kaprekar Numbers in JavaScript
function kaprekarNumbers(p, q) {
let result = [];
for(let i = p; i <= q; i++) {
const squareString = (i * i).toString();
const num1 = squareString.substring(0, squareString.length/2);
const num2 = squareString.substring(squareString.length/2, squareString.length);
if (Number(num1) + Number(num2) === i) {
result = result.concat(i)
@daubattu
daubattu / hackerrank_solution_of_beautiful_triplets_in_javascript.js
Created January 10, 2020 09:06
[Hackerrank] Solution of Beautiful Triplets in JavaScript
function beautifulTriplets(d, arr) {
let result = 0;
for (let i = 0; i < arr.length; i++) {
const numb1 = arr[i] - d;
const numb2 = numb1 - d;
if (arr.includes(numb1) && arr.includes(numb2)) {
result += 1;
}
}
return result;
function minimumDistances(a) {
let min;
const findOtherIndex = index => {
for (let i = index + 1; i < a.length; i++) {
if (a[i] === a[index]) {
return i;
}
}
return null;
}