Web-Dev-Hub-Docs
Web Development Frameworks & Libraries
Productivity
Misc
Backend
Networking
Science & Tech (Innovation)
Reading
Docs
Code Editors & Tools
Free-Stuff
Blockchain & Crypto
Data Structures & Interviewing
WEBDEV-Bootcamp-Notes
Group 1
Powered By GitBook
Mutability And Reference VS Privative Types in JavaScript
Mutability && Primitive && Reference Examples
​

Mutability And Reference VS Privative Types in JavaScript

Mutability && Primitive && Reference Examples

​
​Mutability​
In JavaScript, String values are immutable, which means that they cannot be altered once created.
For example, the following code:
1
var myStr = "Bob";
2
myStr[0] = "J";
Copied!
cannot change the value of myStr to Job, because the contents of myStr cannot be altered. Note that this does not mean that myStr cannot be changed, just that the individual characters of a string literal cannot be changed. The only way to change myStr would be to assign it with a new string, like this:
1
var myStr = "Bob";
2
myStr = "Job";
Copied!

Objects are passed by reference, are mutable, and can be modified by our functions:

1
function rotateLeft(arr, num) {
2
for (let i = 0; i < num; i++) {
3
let el = arr.pop();
4
arr.unshift(el);
5
}
6
}
7
let myArr = [1, 2, 3, 4, 5, ];
8
rotateLeft(myArr, 2);
9
console.log(myArr);
Copied!
Strings are passed by value, are immutable, and a new array is constructed and returned, because it cannot be changed in place.
1
function rotateString(str, num) {
2
return str.slice(num) + str.slice(0, num);
3
}
4
​
5
let str = "foobar";
6
let ret = rotateString(str, 3);
7
console.log(str);
8
console.log(ret);
Copied!

Dereferencing

Arrays

To dereference an array, use let [var1, var2] syntax.
1
let arr = ['one', 'two', 'three'];
2
​
3
let [first] = arr;
4
console.log(first);
Copied!

Objects

To dereference attributes from an object, use let {} syntax.

Primitive Data Types in Depth

​
​

Check Out My New Blog:

​Canonical link​
Exported from Medium on August 31, 2021.
Last modified 1d ago