DEV Community

Understanding basics of array in javascript

Frugence Fidel on May 05, 2018

This post is originally posted to my blog. In the post I will share some basics about Array. Array Array is the way of storing group or list of ...
Collapse
 
mhdbnmsd profile image
Mehdi Benmessaoud

I think you should be using for(let color of colors) not for(const color of colors). What do you think !?

Collapse
 
frugencefidel profile image
Frugence Fidel

In most case let and const are almost same, the only difference I known, const cannot be updated but let can.

Let use this example for demonstration

  const colors = ['purple', 'black', 'yellow', 'aqua'];

 // const

 for(const color of colors) {
    color = 'white';
    console.log(color);  // Uncaught TypeError: Assignment to constant variable.
 }

 // Let

 for(let color of colors) {
    color = 'white';
    console.log(color);  // white white white white
 }
Collapse
 
mhdbnmsd profile image
Mehdi Benmessaoud

Yes i agree with you on that, but i think that’s a miss use of const because inside the loop the variable color is changing at each iteration.

Thread Thread
 
frugencefidel profile image
Frugence Fidel

When use const in for of loop, in each iteration you get a new variable, which is scoped only to that iteration.

Thread Thread
 
frugencefidel profile image
Frugence Fidel

I use let only when i want to modify variable's value.

In below example you can't use const because the value of variable is modified by increment one until the condition is false.

  for(let i = 1; i < 3; i++) {
    console.log(i); // 1 and 2
  }

In below example, the constant variable(random) hold each values of that array.

  for(const random of ['a', 'b', 1, 2]  ) {
    // Here it print values that held by constant random without modify it
    console.log(random); // a b 1 2
  }

Remember, to be constant does not mean to hold only single data. const can also hold list of data. Good example is array.

 // Here constant colors is holding two color
 const colors = ['purple', 'black'];

 // First color is purple
 console.log(colors[0]); // 'purple'

 // Second color is black
 console.log(colors[1]); // 'black'
Collapse
 
rnrnshn profile image
Olimpio

Then their aren't same anymore...

Collapse
 
pafnut profile image
Pafnut

How to delete some item from array?

Collapse
 
frugencefidel profile image
Frugence Fidel

You can delete by using splice method

// Syntax
yourArray.splice(index, numberOfItemsTodelete)

// Real example
const colors = ['purple', 'black'];

// let say you want to delete purple color
colors.splice(0, 1);
console.log(colors); // ['black']
Collapse
 
straleb profile image
Strahinja Babić

Hey, really nice and useful article, great job !!

Collapse
 
frugencefidel profile image
Frugence Fidel

Thanks friend