← Torna al blog

Dev Tips

Un trucchetto al giorno leva le complicazioni di torno! Piccole "scorciatoie" che possono facilitare la vita degli sviluppatori e far risparmiare tempo...e righe di codice.

31

Add properties to an Object

2021-03-08

1// JS Tip of the Day
2// Add properties to an Object
3
4const hero = { name: 'Batman', weapon: 'Batarang' };
5hero.vehicle = 'Batmobile'; // Dot notation way
6hero['partner'] = 'Robin'; // Array notation way
7
8Object.assign(hero, { friend: 'Superman' }); // Object Assign
9console.log(hero); 
10// { name: "Batman", weapon: "Batarang", vehicle: "Batmobile", partner: "Robin", friend: "Superman" }
11
12const anotherHero = { ...hero,  pet: 'Ace' }; // Immutable way with destructuring
13console.log(anotherHero);
14// {name: "Batman", weapon: "Batarang", vehicle: "Batmobile", partner: "Robin", friend: "Superman", pet: "Ace" }
30

Array truncation

2021-03-05

1// JS Tip of the Day
2// Array truncation
3
4const heroes = ['Batman', 'Superman', 'Green Arrow', 'Wonder Woman'];
5console.log(heroes.length); // 4
6
7heroes.length = 2; // Quick truncation!
8console.log(heroes.length); // 2
9console.log(heroes); // ['Batman', 'Superman']
29

Insert Elements into a Specific Index of an Array

2021-03-04

1// JS Tip of the Day
2// Insert Elements into a Specific Index of an Array
3
4const heroes = ['Batman', 'Wonder Woman'];
5
6const insertAt = (array, index, ...items) => {
7    array.splice(index, 0, ...items);
8  	return array; // return the array if you want
9}
10
11console.log(insertAt(heroes, 1, 'Green Arrow', 'Superman'));
12// ['Batman', 'Green Arrow', 'Superman', 'Wonder Woman']
28

Calling a function only if a condition is true

2021-03-03

1// JS Tip of the Day
2// Calling a function only if a condition is true
3
4const myFavouriteHero = "Batman";
5const callHero = (hero) => console.log(`Help me ${hero}!`); 
6
7
8// Longhand 
9if (myFavouriteHero) {
10 callHero(myFavouriteHero); // Help me Batman!
11} 
12// Shorthand 
13myFavouriteHero && callHero(myFavouriteHero); // Help me Batman!
27

Get a Random Number in a Range

2021-03-02

1// JS Tip of the Day
2// Get a Random Number in a Range (max included)
3
4const randomInRange = (min, max) => {
5  return Math.floor(Math.random() * (max - min + 1)) + min;
6}
7
8console.log(randomInRange(20, 50)); // 34

Contattaci.

Hai in mente un progetto e vorresti realizzarlo?
Sei interessato a migliorare le competenze del tuo team in ambito di programmazione e sviluppo?
Oppure vuoi semplicemente prendere prendere un caffè con noi e vedere la nostra collezione di Action Figure, allora scrivici tramite questo form.

Se, invece, vuoi far parte del team, guarda le nostre offerte di lavoro.

Questo sito è protetto da reCAPTCHA e si applicano le Norme sulla privacy e i Termini di servizio di Google.