Mutation in javascript?

what is the difference between size1 and size2 method.why size2() replacing the head property to null.To my knowledge objects are stored as reference…

class Node {
	constructor(data, next = null) {
		this.data = data;
		this.next = next;
	}
}

class LinkedList {
	constructor() {
		this.head = null;
	}

	insertFirst(data) {
		this.head = new Node(data, this.head);
	}

	size1() {
		var counter = 0;
		var node = this.head;
		while (node) {
			counter++;
			node = node.next;
		}
		return counter;
	}

	size2() {
		var counter = 0;
		while (this.head) {
			counter++;
			this.head = this.head.next;
		}
		return counter;
	}
}


//*************//

var list = new LinkedList();
list.insertFirst(30);
list.insertFirst(60);
list.insertFirst(80);


// console.log(list.size2());
console.log(list.size1());
console.log(list);

There’s no good reason for size2 to be coded the way that it is. What is the source of that code, for I think that it may have a different purpose other than being useful.

i am just playing around with that code.Just i want to why it is behaving like that because in size1 we are storing only a reference to variable node.so this variable is pointing to same object in the size2 method but why it is not changing the head value?

With size1, you have a separate variable called node that has a reference to the head object. It’s as if the node variable is pointing at the head object, without actually being it. So you can change what the node points at without changing the actual head object.

Variables assigned to objects or arrays are assigned by reference. Other things like strings, numbers, booleans are assigned by value instead. When assigning by value, the value is copied to the new variable. When assigned by reference, the variable points to the referenced item instead.

In the below example though i used a reference it changing the object where it is pointed to but why this behaviour is not happening in size1() method

var obj = {name:'brinth',age:23};

var v = obj;

v.name = 'santi';
console.log(obj)//{name: "santi", age: 23}

There you are changing something in the object. With the node1 code, you are not changing anything in the head object. Instead you are assigning the node variable to point to the next object.

1 Like

got it…

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.