https://github.com/nas5w/javascript-tips-and-tidbits
console.log("this is smth")
console.error("this is error")
console.warn("this is warning") // Notification box!
alert('Hello World');A form of block-scoped declaration is the const, which creates constants. In ES6, a const represents a constant reference to a value. In other words, Object‘s and Array‘s contents may change, only the re-assignment of the variable is prevented. Here’s a simple example:
{
const b = 5;
b = 10; // TypeError: Assignment to constant variable
const arr = [5, 6];
arr.push(7);
console.log(arr); // [5,6,7]
arr = 10; // TypeError: Assignment to constant variable
arr[0] = 3; // value is mutable
console.log(arr); // [3,6,7]
}When using const with fixed strings or values, CAPITAL_CASING might be appropriate (ex: const PI = 3.14)
Concatenation
console.log("My name is " + name + " and I am " + age);Template literal
console.log(`My name is ${name} and I am ${age}`);Typeof
console.log(typeof z); String Methods
const str = "Hello World";
let smth; // declare a value
smth = str.length; // get length of the string
smth = str.toUpperCase();
smth = str.toLowerCase();
smth = str.slice(1, 3) //start and end positions. Returns new string.
smth = str.substring(1, 4); // result: ell
smth = str.substr(1, 3) //start and end positions. Returns new string.
smth = str.split(' '); // To Array: [Hello,World]
smth = str.split('', 3) // [Hel,lo ,Wor,ld]
smth = str.endsWith('d') // returns: true, false
smth = str.indexOf() // returns -1 if does not find.
smth = str.repeat(2) // repeats the orig string, does not change original.
smth = str.replace('Wor', 'bo') // search for a value or RegEx, does not change orig.
smth = str.trim() // removes spaces in front and at the end
smth = str
smth = str
smth = str
smth = strArrays
const fruits = ['apples', 'oranges', 'pears', 'grapes'];
console.log(fruits[0]); // Accessing the position in array "apples"Arrays Methods
fruits[4] = "blueberries"; // add a value in position 5
fruits.push("strawberries"); // add value in the end of array end changes length.
fruits.unshift("mangos"); // add value in the beginning
fruits.pop(); // delete last value
console.log(fruits.indexOf("oranges")); // get the index
arr.slice(1, 3) //slice for array. Start and end positions. Returns new array.
fruits.join(' and ') // returns an array as a string. default separator comma.
fruits.fill(value, start, end) // fills specified elements in an array with a value, overwrites original
fruits.reverse() // reverses the order of the elements in an array. Overwrites original.
includes(searchvalue, start) // no modifica el array, just true or false.
fruits.map() // creates a new array from calling a function for every array element. https://www.w3schools.com/jsref/jsref_map.asp
Objects
const person = {
name: "Edu",
age: 30,
hobbies: ["music", "movies", "sports"],
address: {
street: "50 Main st",
city: "Boston",
state: "MA",
},
};Objects cannot be compared.
Accessing object
console.log(person.name); //get a value
console.log(person['name']) //get a value
console.log(person.hobbies[1]); //get a value from array inside an object
person.email = "jdoe@gmail.com"; // adding property to an objectGetting all “values” out of object.
Object.keys(obj), Object.values(obj), Object.entries(obj)Conditions
if
let age = 18;
if (age >= 18) {
console.log("Eres mayor de edad");
} else {
console.log("Eres menor de edad");
}
if (hasCommonValue) { // just by containing a value is true
return alert('hasCommonValue is not null!');
}else if
let person = {
age:17,
sonOfBoss: true
}
if (person.age >= 18) {
console.log("Eres mayor de edad");
} else if (person.sonOfBoss == true) {
console.log("No eres mayor de edad pero eres el hijo del jefe");
} else {
console.log("Eres menor de edad");
}
switch
switch (key) {
case value:
// Código a ejecutar
break;
case value:
// Código a ejecutar
break;
default:
// Código a ejecutar
}
let diaActual = new Date();
const dia_de_la_semana = diaActual.getDay()
switch (dia_de_la_semana) {
case 1:
console.log("Es Lunes");
break;
case 2:
console.log("Es Martes");
break;
case 3:
console.log("Es Miércoles");
break;
case 4:
console.log("Es Jueves");
break;
case 5:
console.log("Es viernes");
break;
case 6:
case 7:
console.log("Es fin de semana");
break;
default:
console.log("Ese día no existe");
}
switch statements use strict comparison:
let x = 10;
switch(x) {
case "10": alert("Hello"); // will not display an alert
} Operators
+ Suma
- Resta
* Multiplicación
/ División
% Módulo
** exponente
++ Incremento
-- Decremento
= asigna var a = 1
+= Suma y asigna a += 2 // a = a + 2
-= Resta y asigna a -= 2 // a = a - 2
*= Multiplica y asigna a *= 2 // a = a * 2
/= Divide y asigna a /= 2 // a = a / 2
%= Módulo y asigna a %= 2 // a = a % 2
< Menor que
<= Menor igual que
== Igual
> Mayor que
>= Mayor o igual ue
!= Diferente
=== Estrictamente igual
!== Estrictamente diferenteTernary Operator
// (condicion)? valor1 : valor2
const age = 17;
const eresMayorDeEdad = age >= 18 ? "Eres mayor de edad" : "No eres mayor de edad";
console.log(eresMayorDeEdad)
const eresMayorDeEdad = age >= 18 ? "Eres mayor de edad" : "eresMayorDeEdad"; // else keeps the value that is already saved
const arabel == 'C' && array.push(100); // "ternary" without elsefunction getFee(isMember) { // send true / false to function
return isMember ? '$2.00' : '$10.00';
}
console.log(getFee(true));
// Expected output: "$2.00"Loops
for
const vueltas = [1,2,3,4,5,6,7,8,9,10];
for (let i = 0; i < vueltas.length; i++) {
console.log('Vuelta nº ' + vueltas[i]);
}while
const vueltas = [1,2,3,4,5,6,7,8,9,10];
let i = 0;
while (i < vueltas.length) {
console.log("Vuelta nº " + vueltas[i]);
i++;
}for of
Same as for, but no counter necessary, takes each value in sequence from the start. Works with arrays and not objects.
const vueltas = [1,2,3,4,5,6,7,8,9,10];
for (let vuelta of vueltas) {
console.log("Vuelta nº " + vuelta); //returns Vuelta nº 1 ... 10
}for in
Same as for, but no counter necessary, takes each key in sequence from the start. Instead of values, iterate through the properties of an array and returns the property (key) :
const person = { fname: "John", lname: "Doe", age: 25 };
for (let x in person) {
console.log(x) //returns: fname, lname, age
console.log(person[x]) //would return: John, Doe, 25
}For each
function muFunction(value, index) {
console.log(value, index);
}
advancedArray.forEach(muFunction);
advancedArray.forEach((value, index) => { console.log(value, index); });Do while
let doWhileCounter = 0;
do {
console.log(advancedArray[doWhileCounter]);
doWhileCounter++;
} while (doWhileCounter < advancedArray.length);Arrays Methods
const myArray = [1, 2, 3, 4];
const response = myArray.at(2);
console.log('myArray', myArray);
[1, 2, 3, 4]
console.log('response', response);
3
const response = myArray.pop();
console.log('myArray', myArray);
// [1, 2, 3]
console.log('response', response);
// 4
const response = myArray.push(10);
console.log('myArray', myArray);
// [1, 2, 3, 4, 10]
console.log('response', response);
// 5 === es el length
const response = myArray.fill(6);
console.log('myArray', myArray);
// [6, 6, 6, 6]
console.log('response', response);
// [6, 6, 6, 6]
const response = myArray.join('');
console.log('myArray', myArray);
// [1, 2, 3, 4]
console.log('response', response);
// return a string '1234'
const response = myArray.shift(); // always only the first value
console.log('myArray', myArray);
// [2, 3, 4]
console.log('response', response);
// 1
// Inserts new elements at the start of an array, and returns the new length of the array.
const response = myArray.unshift('a',0);
console.log('myArray', myArray);
// [a, 0, 1, 2, 3, 4]
console.log('response', response);
// 6
const response = myArray.reverse();
console.log('myArray', myArray);
// [4, 3, 2, 1]
console.log('response', response);
// [4, 3, 2, 1]
const response = myArray.includes(3);
console.log('myArray', myArray);
// [1, 2, 3, 4]
console.log('response', response);
// true
With callback
// executes a function on every item in the array.
const response = myArray.map(function(item) {
return item * 2;
});
console.log('myArray', myArray);
// [1, 2, 3, 4]
console.log('response', response);
// [2, 4, 6, 8]
const response = myArray.find(function(item) {
return item % 2 === 0;
});
console.log('myArray', myArray);
// [1, 2, 3, 4]
console.log('response', response);
// 2
const response = myArray.filter(function(item) {
return item % 2 === 0;
});
console.log('myArray', myArray);
// [1, 2, 3, 4]
console.log('response', response);
// [2, 4]
const response = myArray.every(function(item) {
return item > 0;
});
console.log('myArray', myArray);
// [1, 2, 3, 4]
console.log('response', response);
// true
// returns the index of the first element that passes a test (provided by a function)
const response = myArray.findIndex(function(item) {
return item % 2 === 0;
});
console.log('myArray', myArray);
// [1, 2, 3, 4]
console.log('response', response);
// 1
// returns a single value: the function's accumulated result. does not change the original array.
const initialItem = 100;
const response = myArray.reduce(function(lastReturnedItem, item) {
return lastReturnedItem + item; }, initialItem);
console.log('myArray', myArray);
// [1, 2, 3, 4]
console.log('response', response);
// 110
const people = [
{ name: 'Jona', weight: 100 },
{ name: 'Ana', weight: 60 },
{ name: 'Pepe', weight: 40 },
];
const sortedPeople = people.sort(function (p1, p2) {
if (p1.weight > p2.weight) { // sort people from min to max
return 1;
} else {
return -1;
}
});
console.log(sortedPeople);
String Methods
const myString = 'Hello world';
const response = myString.length;
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// 11
const response = myString.charAt(6);
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// w
const response = myString.endsWith('d');
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// true
const response = myString.includes('orld');
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// true
const response = myString.indexOf('p');
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// -1
const response = myString.repeat(2);
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// 'Hello worldHello world'
const response = myString.replace('Hello', 'Bye');
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// 'Bye world'
const response = myString.split(' ');
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// ['Hello', 'world']
const response = myString.startsWith('Hell');
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// true
https://stackoverflow.com/questions/2243824/what-is-the-difference-between-string-slice-and-string-substring#:~:text=slice()%20extracts%20parts%20of,the%20specified%20number%20of%20characters.
const response = myString.slice(1, 3);
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// el
const response = myString.substring(1, 3);
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// el
const response = myString.substr(1, 3);
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// ell
const response = myString.toLowerCase();
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// 'hello world'
const response = myString.toUpperCase();
console.log('myString', myString);
// 'Hello world'
console.log('response', response);
// 'HELLO WORLD'
const response = ' Hello world '.trim();
console.log('myString', myString);
// ' Hello world '
console.log('response', response);
// 'Hello world'
const splittedPhrase = 'jona quiere irse ya'.split('');
const upperInitial = splittedPhrase[0].toUpperCase();
splittedPhrase[0] = upperInitial;
const x = splittedPhrase.join('');
console.log(x);
// 'jona quiere irse ya'
'Soy un crack en javascript'
'Jona quiere irse ya'
Dates
// https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Date
const today = new Date();
console.log(today);
console.log('getMilliseconds', today.getMilliseconds());
console.log('getSeconds', today.getSeconds());
console.log('getMinutes', today.getMinutes());
console.log('getHours', today.getHours());
console.log('getDate', today.getDate());
console.log('getDay', today.getDay()); // of the week
console.log('getMonth', today.getMonth());
console.log('getFullYear', today.getFullYear());
console.log('getTime', today.getTime()); // ms since 01/01/1970
today.setMonth(7);
today.setDate(1);
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);
console.log('setters', today.toString());
Functions
Function must be placed above from where it is called.
// Function to compute the product of p1 and p2
function myFunction(p1, p2) { //
return p1 * p2;
}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}When JavaScript reaches a return statement, the function will stop executing.
Arrow Functions
Arrow functions are a short-hand notation for writing functions in ES6. The arrow function definition consists of a parameter list ( ... ), followed by the => marker and a function body. For single-argument functions, the parentheses may be omitted.
const numbers = [1, 2, 3, 4];
function gt2(num) {
return num > 2;
}
const filteredNumbers1 = numbers.filter(gt2);
console.log('filteredNumbers1', filteredNumbers1);
const filteredNumbers2 = numbers.filter(function (num) { return num > 2; });
console.log('filteredNumbers2', filteredNumbers2);
const filteredNumbers3 = numbers.filter((num) => { return num > 2; });
console.log('filteredNumbers3', filteredNumbers3);
const filteredNumbers4 = numbers.filter((num) => num > 2);
console.log('filteredNumbers4', filteredNumbers4);
const filteredNumbers5 = numbers.filter(num => num > 2);
console.log('filteredNumbers5', filteredNumbers5);Destructuring
https://dmitripavlutin.com/javascript-object-destructuring/
const destructuringNumbers = [1, 2, 3];
// const firstItem = destructuringNumbers[0];
// const thirdItem = destructuringNumbers[2];
const [firstItem, , thirdItem] = destructuringNumbers;
console.log('firstItem', firstItem);
console.log('thirdItem', thirdItem);
const teacher = {
age: 32,
name: 'Jona',
isAdult: true,
description: 'xxxxxxxx'
};
// const username = teacher.name;
const { name: username, age, description = 'yyyyy', desc = 'yyyyy' } = teacher;
console.log('username', username);
console.log('age', age);
console.log('description', description);
console.log('desc', desc);Spread / Rest Operator
... operator is referred to as spread or rest operator, depending on how and where it is used.
When used with any iterable, it acts as to “spread” it into individual elements:
If put args in as object {} the order is not important as it looks for names instead.
function doStuff ({arg1, arg2,}) {
//smth here
}
doStuff({arg2, arg1}) // will enlace args correctly.Stopping the loop
continue;
break;
return ()
return !{} // will return false for if checks
return {...} //will return truePromises
const MyPromise = askTheWaiter()
new Promise( function name )
.then resolve
.catch reject // catch errors and exception
// fetch always 2 promises so 2 .then
fetch('https://restcountries.com/v3.1/all')
.then(res => res.json()) // receive a promise inside a promise
.then(formattedResponse => console.log('formattedResponse', formattedResponse)) // decoded promise
.catch(err => console.error(err));
// async (better)
async function getCountries() {
const response = await fetch('https://restcountries.com/v3.1/all');
const data = await response.json(); // await only can use inside of async
console.log('async/await', data);
}
getCountries(); // brake out of async / await loop
// if there is await inside function, function need to be async
Spread
const spreadNumbersOne = [1, 2, 3];
const spreadNumbersTwo = [4, 5, 6];
const spreadNumbersTotal = [...spreadNumbersOne, ...spreadNumbersTwo];
console.log('spreadNumbersTotal', spreadNumbersTotal);
const myVehicle = {
brand: 'Ford',
model: 'Mustang',
color: 'red'
}
const updateMyVehicle = {
type: 'car',
year: 2021,
color: 'yellow'
}
const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}Rest
const numbersToRest = [1, 2, 3];
const [firstNumber, ...restArray] = numbersToRest;
console.log('firstNumber', firstNumber);
console.log('restArray', restArray);
const teacherToRest = {
name: 'Jona',
age: 32,
isAdult: true,
description: 'xxxxxxxx'
};
const { isAdult, ...restObject } = teacherToRest;
console.log('isAdult', isAdult);
console.log('restObject', restObject);
Ternary
const myAge = 32;
const adultAge = 18;
const amIAdult = myAge >= adultAge;
if (amIAdult) {
console.log('Im adult! 1');
} else {
console.log('Im a baby! 1');
}
amIAdult ? console.log('Im adult! 2') : console.log('Im a baby! 2');
const message = amIAdult ? 'Im adult! 3' : 'Im a baby! 3';
console.log(message);Optional Params
function add(num1, num2, num3 = 0) {
return num1 + num2 + num3;
}
console.log('add(1, 2)', add(1, 2));
console.log('add(1, 2, 0)', add(1, 2, 0));
console.log('add(1, 2, 3)', add(1, 2, 3));Template literals
const min = 0;
console.log('El número mínimo es ' + min);
console.log(`El número mínimo es ${min}`);
Leave a Reply