Recap: Arrays and Tuples
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 21 of 73.
Challenge
EasyCreate a function named addToShoppingList that takes two parameters: a tuple of type [string, number] representing an item (name and quantity), and an array of strings representing the current shopping list.
The function should extract the item name from the tuple and add it to the shopping list array. The function should return the updated shopping list as a new array (without modifying the original array).
Test your function with the following data:
- Create a tuple named
groceryItemwith the values"apples"and5 - Create an array named
currentListwith the values["bread", "milk", "eggs"] - Call your function with these parameters and store the result in a variable named
updatedList
Print the updated shopping list to the console.
Then test the function again with:
- Create another tuple named
bakeryItemwith the values"cookies"and2 - Call your function using the
updatedListfrom the previous step and the newbakeryItem - Store this result in a variable named
finalList
Print the final shopping list to the console.
Try it yourself
// TODO: Write your code here
// Create the addToShoppingList function that takes a tuple and array as parameters
// Test data
const groceryItem: [string, number] = ["apples", 5];
const currentList: string[] = ["bread", "milk", "eggs"];
// TODO: Call your function and store the result in updatedList
// TODO: Print the updated shopping list
// Second test
const bakeryItem: [string, number] = ["cookies", 2];
// TODO: Call your function again using updatedList and bakeryItem, store in finalList
// TODO: Print the final shopping listAll lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples