Advertisement
karlakmkj

Arrays using let and const

Dec 9th, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let condiments = ['Ketchup', 'Mustard', 'Soy Sauce', 'Sriracha'];
  2.  
  3. const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork'];
  4.  
  5. //Re-assign the first element to value 'Mayo' and array now becomes [ 'Mayo', 'Mustard', 'Soy Sauce', 'Sriracha']
  6. condiments[0] = 'Mayo';
  7. console.log(condiments);
  8.  
  9. //Now re-assign condiments as a new array that contains a single string ['Mayo']
  10. //this can be done because array was created with the let keyword
  11. condiments = ['Mayo'];
  12. console.log(condiments);
  13.  
  14. //Re-assign the last element to value 'Spoon' and array now becomes [ 'Fork', 'Knife', 'Chopsticks', 'Spoon']
  15. //this can be done because we can change the contents of const array as it remains mutable
  16. utensils[3] ='Spoon';
  17. console.log(utensils);
  18.  
  19. //however we cannot reassign a new array or a different value.
  20. utensils = ['Spoon'];
  21. console.log(utensils);  //will result in TypeError
  22.  
  23.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement