1

I just started using nodeJS and I am having some difficulties understanding the variable scope and referencing. For example in the code below, variable a will change/be overwritten even though the slice was made to variable b. My question is, how could I copy variable a into variable b without referencing it/overwriting variable a.

var a = ['a', 'b', 'c', 'd'];
var b = a;
b.splice(3,1);

console.log(a)    //will display ['a', 'b', 'c'] instead of ['a', 'b', 'c', 'd']
1

4 Answers 4

1

Instead of using a library like Amit suggested, this can be done natively and without installing a huge library...

Using .slice() with no arguments

var a = ['a', 'b', 'c', 'd'];
var b = a.slice();
b.splice(3,1);

console.log(a);

When you set b = a, you are NOT creating a new array, you are only telling b to hold a reference to a. So a and b are actually referencing the same location in memory. .slice works by returning a entire new array.

Sign up to request clarification or add additional context in comments.

Comments

0

The functionality you're looking for is know as deep clone or deep copy.

There are several ways to do this, for example you could use lodash:

var _ = require('lodash');
var a = ['a', 'b', 'c', 'd'];
var b = _.cloneDeep(a);

3 Comments

Yeahiii! -1 spree!!! Best when done without a comment
You're answer is overkill... why have him download, install and use lodash, when this can simply be done with native Javascript. _.cloneDeep is meant for objects, which are a little trickier to clone.
@ArianFaurtosh - The question is about general variables. The question was closed as dup referencing how to copy an array. It will not be long before the asking user find that an array copy doesn't work (a = [{name: 'some name'}]; b = a.slice(); b[0].name = 'some other name'; console.log(a);). My answer is an overkill for the sample code, not for the question itself.
0

you could use slice

b = a.slice(0);

or you could use concat

b = [].slice(0);

for object there is also the extend method for objects.

and the clone method in underscore library

Comments

0

Thanks for the help but I found the answer to my problem. If anyone comes by this post and has the same problem, you can find the solution here Nodejs: how to clone a object

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.