DEV Community

param-19
param-19

Posted on

Javascript : Arrays and Objects

Arrays

Arrays are a data type that can store a list of sequences of values. It is written as a list of values between square brackets, separated by commas.
All arrays are 0 indexed in javascript, i.e., the first element starts off with index 0 rather than the conventional 1. This is standard across all coding languages, and has been kind of a tradition.

let list = [1, 2, 3, 4, 5];
//You can access each value inside this array as : 
console.log("The first element is : "+list[0]);
//The first element is 1
Enter fullscreen mode Exit fullscreen mode

The two main ways to access properties in JavaScript are with a dot and with square brackets. Both value.x and value[x] access a property on value —but not necessarily the same property. The difference is in how x is interpreted.
When using a dot, the word after the dot is the literal name of the property.
When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result, converted to a string, as the property name.

Methods

  • Properties that contain functions are generally called methods of the value they belong to, for example, "toUpperCase" is a method of string.
  • We can manipulate the arrays in JS using two main methods : push and pop .
let sequence = [1, 2, 3];
sequence.push(4); //push method adds an element at the end of the array
sequence.push(5);
console.log(sequence);
// → [1, 2, 3, 4, 5]
console.log(sequence.pop()); //pop method removes the last element of the array
// → 5
console.log(sequence);
// → [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Objects

Values of the type object are arbitrary collections of properties. We usually define objects using curly braces {} . We can access the elements of individual properties within an object using the . operator.

let day1 = {
squirrel: false,
events: ["work", "touched tree", "pizza", "running"]
};
console.log(day1.squirrel);
// → false
console.log(day1.wolf);
// → undefined
day1.wolf = false;
console.log(day1.wolf);
// → false
Enter fullscreen mode Exit fullscreen mode

You can use the delete operator to delete a property of an object. For example

let anObject = {left: 1, right: 2};
console.log(anObject.left);
// → 1
delete anObject.left;
console.log(anObject.left);
// → undefined
console.log(anObject.right);
// → 2

console.log("left" in anObject);
// → false
console.log("right" in anObject);
// → true
Enter fullscreen mode Exit fullscreen mode

The binary in operator can be used to check if an object has a property with the particular name. To find the keys in an object, you can use Object.Keys .

console.log(Object.keys({x: 0, y: 0, z: 2}));
// → ["x", "y", "z"]
Enter fullscreen mode Exit fullscreen mode

Array loop

The first loop is below is a normal for loop, going over each element one by one. However, the counter here has no purpose other than referencing each element.

for (let i = 0; i < JOURNAL.length; i++) {
let entry = JOURNAL[i];
// Do something with entry
}

for (let entry of JOURNAL) {
console.log(`${entry.events.length} events.`);
}
Enter fullscreen mode Exit fullscreen mode

The second loop also iterates through the entire array, and each element is sequentially taken as entry, and used inside the loop.
Both the loops are used and work well.

Some more methods

  • Just like push and pop work at the last index of an array, shift and unshift are used to add and remove elements at the start of an array.
let todoList = [];
function remember(task) {
todoList.push(task);
}
function getTask() {
return todoList.shift();
}
function rememberUrgently(task) {
todoList.unshift(task);
}
Enter fullscreen mode Exit fullscreen mode
  • To search for a specific value, there is an indexOf method. This returns the first index from the start. If you wish to start searching from the last index, you have lastIndexOf .
console.log([1, 2, 3, 2, 1].indexOf(2));
// → 1
console.log([1, 2, 3, 2, 1].lastIndexOf(2));
// → 3
//Both these methods take in an optional second argument,
//that indicates from where to start searching
Enter fullscreen mode Exit fullscreen mode
  • We also have the slice and concat methods to perform slicing and concatenation respectively.
function remove(array, index) {
return array.slice(0, index)
.concat(array.slice(index + 1));
}
console.log(remove(["a", "b", "c", "d", "e"], 2));
// → ["a", "b", "d", "e"]
Enter fullscreen mode Exit fullscreen mode

Strings and their methods

  • One of the most useful ones are slice and indexOf .
console.log("coconuts".slice(4, 7));
// → nut
console.log("coconut".indexOf("u"));
// → 5
Enter fullscreen mode Exit fullscreen mode
  • The trim method removes whitespaces, and other extra symbols from a given string.
console.log("Hey param \n ".trim());
// → Heyparam
Enter fullscreen mode Exit fullscreen mode
  • The padStart method allows us to pad a given string, taking in the length and the padding character as arguments.
console.log(String(6).padStart(3, "0"));
// → 006
Enter fullscreen mode Exit fullscreen mode
  • You can use the split and join methods on strings.
let sentence = "Secretarybirds specialize in stomping";
let words = sentence.split(" ");
console.log(words);
// → ["Secretarybirds", "specialize", "in", "stomping"]
console.log(words.join(". "));
// → Secretarybirds. specialize. in. stomping
Enter fullscreen mode Exit fullscreen mode
  • You can use the repeat method to create multiple copies of a string
console.log("LA".repeat(3));
// → LALALA
Enter fullscreen mode Exit fullscreen mode

Rest Parameters

Sometimes, we may want to have a function to have any number of arguments. This can be done by adding in 3 dots ... before the last parameter of the function.

function max(...numbers) {
let result = -Infinity;
for (let number of numbers) {
if (number > result) result = number;
}
return result;
}
console.log(max(4, 1, 9, -2));
// → 9
Enter fullscreen mode Exit fullscreen mode

The JSON Object

We often need to store information in objects, or use it for later use. To do this effectively, we serialize the data. This means that it will be stored in a flat description. One of the most popular ways is to store it in JSON (JavaScript Object Notation) format. This is used not only for JS, but also used across the web to send and store information.

{
"squirrel": false,
"events": ["work", "touched tree", "pizza", "running"]
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)