Created
March 27, 2022 08:45
-
-
Save titomus/36e6539f50d4035da5a4daedcfc28e20 to your computer and use it in GitHub Desktop.
Bonnes pratiques JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Class js avec private vars | |
*/ | |
class Person { | |
name = ''; | |
//private vars | |
#age = 0; | |
#ageInDogYears = 0; | |
constructor(name, age) { | |
this.name = name; | |
this.#age = age; | |
this.#ageInDogYears = this.#getAgeInDogYears(); | |
} | |
//private function | |
#getAgeInDogYears() { | |
return this.#age * 7; | |
} | |
//public function can return private vars | |
log() { | |
console.log(this.name); | |
console.log(this.#age); // here | |
console.log(this.#ageInDogYears); //here | |
} | |
}; | |
const Jeremy = new person('Jeremy', 39); | |
Jeremy.log(); | |
console.log(Jeremy.name); // Jeremy | |
console.log(Jeremy.age); // undefined | |
console.log(Jeremy.#age); // Error! Uncaught SyntaxError: Private field '#age' must be declared in an enclosing class | |
/* | |
Trouver le premier index d'un tableau qui correspond à un param | |
*/ | |
let ages = [12, 20, 6, 4,19]; | |
//trouve le premier qui correspond | |
let firstAdult = ages.find(age => age >= 18); // 20 | |
//retourne son ID (commence à 0) | |
let firstAdultIndex = ages.findIndex(age => age >= 18); // 1 | |
/* | |
créer un unique ID => pas forcément unique mais possibilité faible de Duplicate | |
*/ | |
let id = crypto.randomUUID(); // '5872aded-d613-410e-841f-a681a6aa8d8b' | |
console.log(`ID généré: ${id}`); | |
/* | |
ecriture autorisé des nombres pour une meilleure lecture | |
*/ | |
//le _ est autorisé en js pour la lisibilité du code | |
const oneMillion = 1_000_000; // 1000000 | |
const decimals = 1_000_00.01_02_03 // 100000.010203 | |
const jeVais = 'je_vais_au_toilettes'; // don't work | |
console.log(oneMillion); | |
console.log(decimals); | |
console.log(jeVais); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment