-
Notifications
You must be signed in to change notification settings - Fork 1
03. Arrays and Sets
idavidov13 edited this page Nov 7, 2023
·
3 revisions
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 likepush(),pop(),shift(), andunshift()
- 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 includemap(),filter(),reduce(),slice(),splice(), and many more.
It's used for building new arrays or to pass multiple values to a function
It's used to pack items into an array
Operators are used to perform logical operations and handle default values in expressions.
-
||- returns the first true value (falsy values are0,"",false,null, andundefined) 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 arenullandundefined)
- 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 are0,"",false,null, andundefined) - NULLISH
??operator - works as OR operator with exception (falsy values arenullandundefined) - AND
&&operator - useful for masking valuesperson.firstName &&= 'ANONYMOUS'
- 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-inloop to iterate through the keys
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)]