Blog

- Showing all posts in category: Javascript
# Javascript references and copies
Published on 14-04-2020

Good to know how Javascript takes care of reference primitive types

Primitive type:

const one = 1;
const copyOne = one;

 

Reference type for objects:

const person = {
  name: 'Loki'
};
const refPerson = person;

person.name = 'Tom';

console.log(refPerson.name);// prints 'Tom'

 

Same object, this time using the spread operator that makes a copy instead of a reference:

const person = {
  name: 'Loki'
};
const refPerson = {...person};

person.name = 'Tom';

console.log(refPerson.name);// prints 'Loki'

 

Fun fact: Loki is my cat.

 

 

# ES6 Spread and Rest operator
Published on 14-04-2020

Spread operator example:

In an array:

const numbers = [1, 2 ,3 4];
const myNewArray = [...numbers, 5 , 6, 7];

console.log(myNewArray); //prints [1, 2, 3, 4, 5, 6, 7]

 

In a JSON object

const person = {
  name: 'Gokhan'
}

const otherPerson = {
  ...person,
  age: 31
}
console.log(otherPerson);//prints {name: 'Gokhan', age: 31}

 

Rest operator

(similar to Java varargs:

const glueNames = (...names) =>  names.map((elem, i) => {
  return {
    index: i,
    name: elem,
    nameCharacterCount: elem.length
  }
});

const out = glueNames("Gokhan", "Orhun", "Awesomeguy");
console.log(JSON.stringify(out));
//Will print the following array:
[
  {
    "index": 0,
    "name": "Gokhan",
    "nameCharacterCount": 6
  },
  {
    "index": 1,
    "name": "Orhun",
    "nameCharacterCount": 5
  },
  {
    "index": 2,
    "name": "Awesomeguy",
    "nameCharacterCount": 10
  }
]

If you would like to swap the position items in a javascript array use this code:


var items = ["foo", "bar"];

function changeOrder(posA, posB) {
    var itemA = items[posA];
    var itemB = items[posB];

    items[posA] = itemB;
    items[posB] = itemA;
}

changeOrder(0,1);

console.log(items.join(",")) // will output "bar,foo"

JSFiddle example