Created
April 28, 2020 19:49
-
-
Save sandrabosk/4519c1bdc0699d9d51b17d33895f293a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// ************************************************ | |
// ****************** Arrays ********************* | |
// ************************************************ | |
const campuses = ['madrid', 'barcelona', 'miami']; | |
const [firstCampus, secondCampus, thirdCampus] = campuses; | |
console.log(thirdCampus); // miami | |
// Put the first item in the array in a variable: | |
const [first] = campuses; | |
console.log(first); // <== madrid | |
// Skip the first element, and take the second one only: | |
const [, second] = campuses; | |
console.log(second); // <== barcelona | |
// Skip the first and the second element, and take the third one only: | |
const [, , campus3] = campuses; | |
console.log(campus3); // <== miami | |
// Default values | |
const [campus1, campus2, campus3, campus4] = campuses; | |
console.log(campus4); // ==> undefined | |
// But we can assign the value to the additional variable (campus4): | |
const [campus1, campus2, campus3, campus4 = 'paris'] = campuses; | |
console.log(campus4); // ==> paris | |
// Nested arrays and destructuring | |
const europeanCampuses = [ | |
['madrid', 'es'], | |
['barcelona', 'es'], | |
['berlin', 'de'], | |
['paris', 'fr'], | |
['amsterdam', 'nl'], | |
['lisbon', 'pt'] | |
]; | |
const [ | |
[campusSpain1], | |
[campusSpain2, country], | |
[campus5, theCountry] | |
] = europeanCampuses; | |
console.log(campusSpain1, campusSpain2, country, theCountry); | |
// ==> 'madrid' 'barcelona' 'es' 'de' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment