Pokazywanie postów oznaczonych etykietą ES6. Pokaż wszystkie posty
Pokazywanie postów oznaczonych etykietą ES6. Pokaż wszystkie posty

piątek, 1 lipca 2016

shallow and deep cloning objects in JavaScript

As all values in JavaScript are pass by reference clonig is quite popular operation, to save original object. Unfortunately JavaScript does not provide any method to clone deeply the whole object.

ES6 provided some features, which could be useful, but still we have to remember, that this is only a shallow cloning.

The first solution is to use Object.assign:
const a = {
  b: {
    c: 1
  },
  z: 15
};

console.log(a); // {"b":{"c":1},"z":15}

let d = Object.assign({}, a);

d.b.c = 5;
d.z = 29;

console.log(a); // {"b":{"c":5},"z":15}
console.log(d); // {"b":{"c":5},"z":29}

The first console.log will display original a object, but in the second a.b.c value will be changed. Only a.z value will stay the same. This is what shallow cloning is. Only first level properties are cloned, rest is passed by reference.

So what would happen if d.b would be changed?
d.b = 118;

console.log(a); // {"b":{"c":5},"z":15}
console.log(d); // {"b":118,"z":29}

The same situation will happen if we will use spread operator:
const aa = {
  g: {
    h: 1
  },
  y: 15
};

console.log(aa); // {"g":{"h":1},"y":15}

let e = { ...aa };

e.g.h = 9;
e.y = 23;
console.log(aa); // {"g":{"h":9},"y":15}

So, how to make a deep cloning in JavaScript?

1. Use JSON stringify and parse
JSON.parse(JSON.stringify(object));

2. Write own method to do a deep clone of passed object.

czwartek, 3 września 2015

ES6 - arrows

The biggest difference between arrow and function is this value. Function uses its own this value, but arrow uses this value of the enclosing context.

Arrows are always anonymous functions!

Their syntax is slightly different than function expression:
(args) => { statements }


There could be few variations from this main version:
(arg1, arg2, argN) => { statements }
arg1 => { statements }
() => { statements }

(arg1, arg2, argN) => { statements }
(arg1, arg2, argN) => expression
(arg1, arg2, argN) => ({ prop: val })


It means - prentheses are optional. Mostly if there is only one argument, or only one value to return, this could be simplified.
But there is a catch:
(arg1, arg2, argN) => expression

but
(arg1, arg2, argN) => { return expression }


Example:
(arg1, arg2) => arg1 * arg2

(arg1, arg2) => { return arg1 * arg2 }


Both return the same, but we can write it in different way.