DEV Community

gfish94
gfish94

Posted on • Updated on

Complex DataTypes in JS

Collections

Objects and arrays are ‘complex’ data-types in JavaScript. Objects and arrays are mutable meaning that they can be accessed and changed after being created. JavaScript collections can be of indeterminant size.

What's the Difference?

Objects are collections of data made of unordered properties. These properties are made of a value assigned to a key. A key need to be a string, however a value can be any data-type.

Arrays are collections of data made of values assigned to a numerical index starting at zero. Arrays, unlike objects, are specifically ordered. Array values can also be any data-type.

Accessing Object Properties

Dot notation is used to access an objects properties when the LITERAL name of a key is known.

Bracket notation can be use a variable assigned to a key can be passed in the place of a key’s literal name. Bracket notation can also be used when a key has a ‘special’ character.

Accessing Array Elements

Array elements are accessed using bracket notation passing the index number of the value trying to be accessed.

Property Deletion

Object properties can be deleted using the delete keyword.

Removing Elements from an Array

There are various ways to remove elements from arrays.

The array method splice takes in two arguments: the index of the first element to remove and the number of elements to remove. The splice method can be used to return an array of the removed elements or if no arguments are passed then it can create an unaltered copy of the array.

The array method shift can be used to remove the first element from an array. The shift method can be used to return the element that was removed.

The array method pop can be used to remove the last element from an array. The pop method can also be used to return the element that was removed.

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Object keys can be Symbols as well as strings. If you're using a symbol, then you must use the bracket notation.

const a = Symbol()
const myObj = {
  val: 3,
  [a]: 4
}

console.log(myObj.val)  // 3
console.log(myObj[a])  // 4
Enter fullscreen mode Exit fullscreen mode