Skip to content

03. Arrays and Sets

idavidov13 edited this page Nov 7, 2023 · 3 revisions

Arrays

An array in JavaScript is a single variable used to store different elements. It's essentially a list-like object whose prototype provides methods to perform traversal and mutation operations. The elements can be of any data type, including numbers, strings, and objects.

  • Declaration
    let fruits = ["apple", "banana", "cherry"];
    or
    let fruits = new Array("apple", "banana", "cherry");
  • Indexed
    console.log(fruits[0]); Outputs: apple
  • Length
    console.log(fruits.length); Outputs: 3
  • Dynamic
    Arrays in JavaScript are dynamic, meaning you can add and remove items. For example, using methods like push(), pop(), shift(), and unshift() image
  • Versatile
    let mixedArray = [1, "string", {name: "John"}, [1, 2, 3]];
  • Methods
    Arrays come with a plethora of built-in methods to manipulate, search, or transform the data. Examples include map(), filter(), reduce(), slice(), splice(), and many more.

Spread Operator ...array on the right of the =

It's used for building new arrays or to pass multiple values to a function

Rest Operator ...array on the left of the =

It's used to pack items into an array

Operators ||, && and ??

Operators are used to perform logical operations and handle default values in expressions.

  • || - returns the first true value (falsy values are 0, "", false, null, and undefined) or the last falsy value if all values are false
  • && - returns the first falsy value or last true value if all values are true
  • ?? - returns the first true value (falsy values are null and undefined)

OR/NULLISH/AND assignment operator - very useful when working with APIs

  • OR || operator - person.firstName ||= 'Ivan' (if the person has a truthy value for the first name, no change will occur. Else - the firstName of the object will assign the value 'Ivan')(falsy values are 0, "", false, null, and undefined)
  • NULLISH ?? operator - works as OR operator with exception (falsy values are null and undefined)
  • AND && operator - useful for masking values person.firstName &&= 'ANONYMOUS'

Associative Arrays

  • Arrays indexed by string keys
  • Hold a set of pairs [key => value]. The key is a string and the value can be of any type
  • We can use for-in loop to iterate through the keys

Set

Make a set with unique values. The main use case is to remove duplicate values from array
let newMadeSet = new Set([....])

  • Methods - aSet.size, aSet.has(), aSet.add(), aSet.delete(), aSet.clear()
  • Can loop through sets for (let item of aSet) ...
  • New array with unique values - let uniqueArray = [...new Set(initialArray)]

Clone this wiki locally