Programming/JavaScript/Objects and Data Structures

From Dev Wiki
Jump to navigation Jump to search

See also General Syntax.


Basic Data Structures

Arrays

JavaScript arrays generally handle the same as standard arrays. See Arrays for more info.

Additionally, JavaScript arrays have the following logic:

Get array length:

<array_var>.length;

Add item to start of array:

<array_var>.unshift(<value>);

Add item to end of array:

<array_var>.push(<value>);

Remove first item in array:

removedValue = <array_var>.shift()

Remove last item in array:

removedValue = <array_var>.pop();

Return shallow copy of array. Original array is left unchanged:

arrayCopy = <array_var>.slice(<start_index>, <end_index>);

Locate index of item in array. Or -1 if not found:

index = <array_var>.indexOf(<value_to_search>, <opitonal_starting_index>);


Dictionaries

In JavaScript, classes and dictionaries are hybridized, and referred to as "Objects".

Dictionaries can be incredibly powerful. See Dictionaries for more info.


Declaring Dictionaries

// Declaring with values.
let <object_var> = {
    <key_1>: <value_1>,
    <key_2>: <value_2>,
}

Example:

let productsSold = {
    'Ice Cream': 50,
    'Burgers': 56,
    'Pizza': 102,
}


Accessing Dictionary Values

Warn: Dot notation only works if a key does not have numbers, spaces, or special characters. Otherwise bracket notation is required.

Read an existing key-value pair:

// Dot notation.
<value> = <object_var>.<key>;

// Bracket notation.
<value> = <object_var>[<key>];

Example:

// Dot notation.
pizzasSold = productsSold.pizza;

// Bracket notation.
pizzasSold = productsSold['pizza'];


Set a new key-value pair, or update an existing one:

// Dot notation.
<object_var>.<key> = <value>;

// Bracket notation.
<object_var>[<key>] = <value>;

Example:

// Dot notation.
productsSold.pizza = 25;

// Bracket notation.
productsSold['pizza'] = 25;


Remove an existing key-value pair:

// Dot notation.
delete <object_var>.<key>;

// Bracket notation.
delete <object_var>[<key>];

Example:

// Dot notation.
delete productsSold.pizza;

// Bracket notation.
delete productsSold['pizza'];


To loop through dictionary values:

for (let <dict_key> in <dict_var>) {
    # Loop logic here, on <dict_key>.
}

Example:

for (let product in productsSold) {
    console.log(`Sold ${productsSold[product]} ${product}s!);
}


Classes

In JavaScript, classes and dictionaries are hybridized, and referred to as "Objects".

Class properties/variables use the above "dictionary" syntax. Then functions use the following:

let <object_var> = {
    <key_value_1>,
    <key_value_2>,
    
    ...
    <key_value_n>,

    <function_name>() {
         # Function logic here.
    },
    
}

Access object internal data with the keyword this.