TypeScript ArraysAn array is a homogenous collection of similar type of elements which have a contiguous memory location. An array is a user-defined data type. An array is a type of data structure where we store the elements of a similar data type. In an array, we can store only a fixed set of elements. We can also use it as an object. The array is index-based storage, where the first element stored at index 0. The below structure helps to understand the structure of an array. Characteristics of an Array
AdvantageCode Optimization: An array helps to make the code optimized, which increases the speed and performance of the program. It allows us to retrieve or sort the array data more efficiently. Random access: It provides the ability to access any data of an array in constant time (independent of its position and size). Thus, we can get any data of an array located at any index position directly. DisadvantageSize Limit: An array allows us to store only the fixed number of elements. Once the array is declared, we cannot alter its size. Hence, if we want to insert more element than declared, it is not possible. Array declarationJust like JavaScript, TypeScript also supports arrays. There are two ways to declare an array: 1. Using square brackets. Example: 2. Using a generic array type. Example: Types of the array in TypeScriptThere are two types of an array:
Single-Dimensional ArrayA single-dimensional array is a type of linear array, which contains only one row for storing data. It has a single set of the square bracket ("[]"). We can access its elements either using row or column index. Syntax Initialization Example Output: Array[0]: 1 Array[1]: 2 Multi-Dimensional ArrayA multi-dimensional array is an array which contains one or more arrays. In the multi-dimensional array, data is stored in a row and column-based index (also known as matrix form). A two-dimensional array (2-D array) is the simplest form of a multi-dimensional array. Syntax Initialization Example Output: 1 2 3 5 6 7 Array ObjectArray objects allow us to store multiple values in a single variable. We can create an array by using the Array object. The Array constructor is used to pass the following arguments for array creation.
Syntax Example Output: JavaTpoint 2200 Java Abhishek Array Traversal by using a for...in loopExample Output: JavaTpoint 2300 Java Abhishek Passing Arrays to FunctionsWe can pass arrays to functions by specifying the array name without an index. Example Output: JavaTpoint 2300 Java Abhishek TypeScript Spread operatorThe spread operator is used to initialize arrays and objects from another array or object. We can also use it for object de-structuring. It is a part of the ES 6 version. Example Output: CopiedArray: 1,2,3 NewArray: 1,2,3,7,8 MergedArray: 1,2,3,4,5,6 Array MethodsThe list of array methods with their description is given below.
Next TopicTypeScript Tuples
|