Javascript assigning a method to an array value - javascript

I'm trying to figure out why I cannot assign the toUpperCase method to a specific value in an array (see below). I am a little confused because I thought objects were mutable and manipulated by reference? Maybe I am looking at it backwards?
var ary = ["hello", "there", "world"];
ary[0][0] = ary[0][0].toUpperCase();
console.log(ary[0][0]); // returns lowercase h
Any clarification would help me out a lot.

Since Strings are immutable in JavaScript, assigning a new character to an index of a String will not change the string at all. You need to create a new String like this
ary[0] = ary[0][0].toUpperCase() + ary[0].substr(1);
# H
We are creating a new string with the first letter capitalized and the rest of the string as it is.

Related

Why do some JavaScript functions require a new variable to be created, but others do not?

Why some functions like toLowerCase() when used on a string need to be assigned a new variable, but other functions like sort(), reverse(), or pop() do not when used on an array?
For example, the code below is wrong:
var str = "Hello World";
str.toLowerCase();
but the code below is correct:
var arr = ["This","is","my","array"]
arr.sort();
I am reading that when using toLowerCase() on a string, I must have the code written like this:
str = str.toLowerCase();
Because strings are immutable in JavaScript, which means you cannot change them. Every time you try to modify a string, you are effectively creating a new string with the changes.
So when you do str.toLowerCase();, it's not modifying str, it is actually making a copy of it with the lowercase of the letters.
The array is different because it is a list of references to the array items. You can change each item separately from the other items arr[5]=11. You can also add or remove an item. The sort() and reverse() functions re-arrange the items in the array.
By the way, this concept is not unique to JavaScript. Many other modern languages also make strings immutable (perhaps all languages that have String as a built-in type).

If String is immutable in javascript then how splice method changing the original String?

As i heard, String is immutable in JavaScript then how splice method changing the original String?
As I know
var name = 'Alto';// it will create an new object in global space memory with 'alto' and assign to name reference.
name = 'swift'; // it will create an new object in global space memory and with 'swift' assign to name reference. ('Alto' string object will be moved to garbage collector whenever possible).
var newName = name.slice(0,2);// here splicing the 'sw' from 'swift' create an new Object in global space and assign to newName. name will have 'swift' since string is immutable.
var newName1 = name.splice(0,2);// here cut the 'sw' from 'swift'(original string) and assign to newName. now name will have 'ift'. so how String is an immutable?
Can anyone explain the process behind splice?
They are immutable. You cannot change a character within a string with something like var myString = "abbdef"; myString[2] = 'c'. The string manipulation methods such as trim, slice return new strings.

Changing the first(or any) character of an array string value

Say I have an array with string values such as:
var foo = ["Hello", "World"];
I can return the first character of each array element by doing:
foo[0][0]; // Will return "H"
foo[1][0]; // Will return "W"
However, when attempting to change the value of those characters using a similar method, it doesn't work. What I mean is that doing this does not work:
foo[0][0] = "J"; // Will not change "H" to "J".
It's not a huge issue since I know alternative ways to do so such as:
foo[0] = "J"+foo[0].substsring(1); // Hello --> Jello
But I'm curious as to why the previous method does not work? EDIT: Did some fiddling around and apparently it doesn't work with strings at all to begin with, not just strings in arrays. I guess I was under the false impression that strings act just like arrays. I can return certain characters by calling it's position in the string similar to how calling an array index works, but changing said index doesn't hold.
From Javascript String reference:
For character access using bracket notation, attempting to delete or
assign a value to these properties will not succeed. The properties
involved are neither writable nor configurable. (See
Object.defineProperty() for more information.)
Strings are immutable, that is, they cannot be altered.
This:
foo[0][0] = "J";
Doesn't work because you are attempting to modify the string stored at position 0 in the foo array.
This:
foo[0] = "J"+foo[0].substsring(1);
does work because you aren't trying to modify a string, you are trying to replace the element at position 0 in the foo array with an entirely new string.
All primitive data types in JavaScript are immutable.
Quote from MDN:
Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string.
Strings are immutable, so they cannot be changed unless you create a new string and store the new value inside of that string. You cannot change a character within a string, The string manipulation methods such as trim, substring etc.
From substring method - The result is a String value, not a String object.
var foo = ["Hello", "World"];
foo[0][0] = "J";
console.log(foo);
foo[0] = "J"+foo[0].substring(1);
console.log(foo);
Notice if you change
var foo = [1, "World"];
foo[0][0] = "J";
It works, since it's not a string
Check this out : https://tc39.github.io/ecma262/#sec-string.prototype.substring
If start is larger than end, they are swapped.
The following steps are taken: From the link above
Let O be ? RequireObjectCoercible(this value).
Let S be ? ToString(O).
Let len be the number of elements in S.
Let intStart be ? ToInteger(start).
If end is undefined, let intEnd be len; else let intEnd be ? ToInteger(end).
Let finalStart be min(max(intStart, 0), len).
Let finalEnd be min(max(intEnd, 0), len).
Let from be min(finalStart, finalEnd).
Let to be max(finalStart, finalEnd).
Return a String whose length is to - from, containing code units from S, namely the code units with indices from through to - 1, in ascending order.

Javascript accessing the string variable as array

I just tried this code in Chrome deveoper tools:
var str = "1111111";
str[0] = 2;
2
console.log(str[0]);
1
As you can see, the output was 1, where I expected 2. My conclusion is this is not meant to be working like that, so I ask how would I get this to work - how would I change the first 'item' of the varable str to 2?
That is because in JavaScript strings are immutable objects. You should use substr function:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
};
var str = '11111';
console.log(str.replaceAt(0, '2'));
From the rhino book:
In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings. Strings are assigned by reference, not by value. In general, when an object is assigned by reference, a change made to the object through one reference will be visible through all other references to the object. Because strings cannot be changed, however, you can have multiple references to a string object and not worry that the string value will change without your knowing it.
Try this out
str.replace(str.charAt(0), "2")
You need to split the string first.
So something like:
str = str.split('');
Then you can treat it as an array.

Javascript use reserved keyword as key

Doing so
var x = new Array();
x['length']=5;
will make x an array of 5 undefined items, but I actually want to have the value '5' stored at key 'length'.
Is that possible?
In javascript arrays do not have keys. You are looking for objects:
var x = {}
x.length = 5;
I have to parse a file containing many words and store the number of occurences of each word
Use an object, and make the words the keys. You aren't storing sequential / ordered data, so you shouldn't use an array.
var word_count = {};
for (var i; i < words.length; i++) {
var word = words[i];
if (word_count[word]) {
word_count[word]++;
} else {
word_count[word] = 1;
}
If you want to do this you'd be better off creating an object rather than an array. This should give you what you want.
var x = {};
x['length'] = 5;
You can call methods on a javascript object using two different syntaxes. The familiar 'dot' syntax with parens to invoke the method, and the square bracket syntax. You can 'call' a method on a javascript object using the syntax myObj["methodname"](args). This is handy when you want to construct the method name dynamically using strings. Remember, objects in javascript are very much like a hash table (dictionary) where keys denote property and function names. If a key's value holds a function, it can be invoked (using parentheses).
In your example, Array has a method called 'length'. You are inadvertently calling its setter (which sets the length of the array to empty values, i.e., undefined).
Putting that all aside, you really do want a hash (associative array) in this case. An array is an offset indexed data structure.
A simple object literal like myObj = {} will suffice to give you hash semantics (again, objects in javascript are already like hashes) and you can then call myObj.whatever = "some value"
You could use objects instead of arrays to store your data. But if you need to use Arrays (you might need to use their functionality), You could cripple the words and store them as array keys.
Use some kind of simple rule to follow to bypass all the possible keywords. For example prefix all your array keys with a "_" character. This way you could always restore the original words from the keys, by simply removing their first character, and you are sure you are not referencing any specific property of the Array objects (like the length property).

Categories