Strings, Objects (immutability)

Topic includes

  • immutability
  • literal string
  • methods/functions
  • value type
  • reference type
  • object
  • class
  • verbatim string

Today I’ll discuss what does the heading above mean and why it is important or maybe it isn’t?

When anybody starts to program the first thing that will come up to him are strings. Strings are EVERYTHING in programming, you can do whatever you like with them you can also convert other data type to strings and make some useful operations and then again convert to its primitive type ( I do that very often). At one point you will have to get familiar with the basic methods that strings provide. If you go deeper you will see that you can substitute many string operations using regex.

What does immutable mean?

If you asked a layman what does immutable mean he’ d most probably say something that cannot MUTATE (something that can not change).

I remember when I first heard this word in programming, I immediately thought of a monster who can mutate (can change its appearance, structure, look ect.). Even tough this doesn’t make sense since we want something immutable here.

I must say that I picked up the term really quickly and I understood what it meant but didn’t go deeper with my mind to it.

Enough talking for now, let’s start with an example:

var name="Paul";
name.concat(" and Jenny");
alert(name);

The question is, why doesn’t the literal string “&Jenny” get applied to the name, why doesn’t it change the value of name when the concat() function is applied?? The answer can be found in the title of-course, strings are immutable. This means that the variable “name” is of value type which means that it stores the data directly to the memory and access it as well.

definition of value types (source url:https://msdn.microsoft.com/en-us/library/t63sy5hs.aspx): A data type is a value type if it holds the data within its own memory allocation.

This withdraws the reference types, strings are immutable because the are not reference type rather than that, they are value types as mentioned above.

definition of reference type (source url:https://msdn.microsoft.com/en-us/library/t63sy5hs.aspx): A reference type contains a pointer to another memory location that holds the data.

One thing to clear up here. No matter which type of is the variable “name” the concat() function returns the result “Paul & Jenny” BUT DOES NOT APPLY IT TO THE VARIABLE NAME. It just stays there “hanging in the air”.

example:

var name="Paul";
name.concat(" and Jenny");
alert(name.concat(" and Jenny"));

In the alert box you will see the result “Paul & Jenny” and you will wonder, how did this concatenate now, but if we print out (again showing a alert box) the variable name “Paul & Jenny” the concatenation is not applied and it does not show up? That’s because the function concat() returns the new value and the alert box just display’s it.

To make a conclusion: value types can not be altered/modified/changed. Reference types can be changed.

How do I concat my string literal to the variable string “Paul”?

The easiest solution here would be to override the variable ( replacing the variable name by applying a new content to it, see the following example)

example:

var name="Paul";
name=name.concat("and Jenny");
alert(name);

The output of name will now be “Paul & Jenny”

Using a string like an array is extremely useful sometimes but the immutability kicks in and we have to write some extra code to overcome this state.

example:

 var name="Paul";
 name[0]="r";
 alert(name);

As you can see in the output, the name remains exactly the same (although we’ve “changed” the first letter to ‘r’)By now you should know the answer why this is the case, but, just in case, strings are immutable, strings are value types hence not reference types. Na altering/modifying/changing whatsoever.

Let’s now modify the string in the way that we could not do it before, but first let’s make a small introduction to Objects.

When I started to learn objects (OOP- object oriented programming) things didn’t make sense because I always and I must says once again, always thought in this way: “Why would I use something else if I can achieve that with the previous known stuff”.

Every time someone asks me about objects, I say to him :Objects or OOP programming is used to make things more tidy, more neater.” I didn’t mention more effective, less code or anything else apart from the sentence above.

I always avoided functions/methods, classes ect. because I liked to get my things done quickly just writing the code going step by step, line by line and finding a solution without this fancy stuff which was good until bigger projects came… Then I just new that I had to involve the objects/classes (object!=class) to get my things done quicker!

I’ don’t want to go too deep into objects and classes especially not in the JavaScript sense, since JavaScript does not have a full OOP structure like C# for example, but I will say the most important part of it.

You can think of an object as a wrapper where you wrap inside your properties and functions which you later use by specifying the object name and accessing it’s properties or methods via the . symbol

example:

var person = {
 firstName: "Paul",
 lastName : "Sanders",
 fullName : function() {
 return person.firstName+" "+ person.lastName;
 }
};
alert(person.fullName());

You can see that we have an object which encapsulates (wraps around) properties and methods and we are accessing the method .fullName() via the . symbol (as said) and we are also able to access it because we used the object before “person”.

I will stop here with the explanation of objects, I think that this is more than enough for this post (at the end of the article you can find a short explanation of objects and classes)

Let’s get back now to reference types, why? Because we involved object in the whole story… TO BE CONTINUED…

Incredibly good links on immutability:

 

Adding text from div to another div atribute inside a (stackoverflow problem)

Problem posted: 07/08/2015

url: http://stackoverflow.com/questions/31871404/how-to-add-text-in-the-data-attribute-using-jquery
fiddle: http://jsfiddle.net/eugensunic/0kourse6/4/

Problem description:

The title says it all. The user wanted to fetch the text from the div tag and assign it to the

attribute which had a parent li.

Solution to the problem:

var array=[];
$('.pin_head > div').each(function (index,obj) { 

   array[index]= $(this).text();

});

$('li > div').each(function (index,obj) {
    var data= $(this).attr("data-col",array[index]);
});

Formating characters – indentation&comma (stackoverflow problem)

Problem posted: 08/08/2015

url:  http://stackoverflow.com/questions/31890301/javascript-string-split-based-on-value/31890361#31890361
fiddle: https://jsfiddle.net/eugensunic/kphe5fbL/13/

Problem description:

Format the current string :
Landing Hits: 0Rewards Hits: 0Facebook Posts: 0Twitter Tweets: 0Twitter Autofollows: 0Instagram Photos: 0Instagram Likes: 0Instagram Votes: 0Pinterest Pins: 0Form Submissions: 0Submissions: 0Engagement: 0Views: 0Prints: 0″

to the following output:
Landing Hits: 0, Rewards Hits: 0, Facebook Posts: 0, Twitter Tweets: 0, Twitter Autofollows: 0, Instagram Photos: 0, Instagram Likes: 0, Instagram Votes: 0, Pinterest Pins: 0, Form Submissions: 0, Submissions: 0, Engagement: 0, Views: 0, Prints: 0″

The OP wanted to add a comma after the number (the number can be positive or negative greater than and lower than 0, not only 0)

Solution to the problem:

var c = "Landing Hits: -345Rewards Hits: 0Facebook Posts: 0Twitter Tweets: 034534532Twitter Autofollows: 0Instagram Photos: 0Instagram Likes: 0Instagram Votes: 0Pinterest Pins: 0Form Submissions: 0Submissions: 0Engagement: 0Views: 0Prints: 0";
var array = []
var counter = 0;
var num;
var dup = "";
for (var i = 0; i<c.length; i++) {
 dup += c[i];
 if (c[i]==":"){dup+=" ";}
 if (!isNaN(c[i]) && isNaN(c[i+1]) && c[i]!=" ") {
 dup += ", "
 }
}
 alert(dup);

After that I also decided to make a function which would get the length of each number after the colon ":" in the same sequence.

var c = "Landing Hits: 345Rewards Hits: 0Facebook Posts: 0Twitter Tweets: 034534532Twitter Autofollows: 0Instagram Photos: 0Instagram Likes: 0Instagram Votes: 0Pinterest Pins: 0Form Submissions: 0Submissions: 0Engagement: 0Views: 0Prints: 0";
var array = []
var counter = 0;
var num;
var dup = "";
var i=0;
for (var j=0; j<c.length; j++)
{
if (!isNaN(c[j]) && c[j]!=" ") // because js interprets " " as 0 if applied on isNan() evaluates to false so I hade to include the other part inside the if as well
{
counter++;
if (isNaN(c[j+1]))
{
array[i]=counter;
i++;
counter=0;
}
}
}
console.log(array[0]);

Important methods (math, integers, strings)

Math

Methods
Math.random() returns a decimal
Math.min(params_int) returns the min number which is in the sequence
Math.max(params_int) returns the max number in the sequence
Math.round() rounds the number to the nearest integer
Math.ceil() rounds the number up to the nearest integer (ceiling/high above)
Math.floor() rounds the number down to the nearest integer (ground/floor)

popular constants

Math.E // returns Euler’s number
Math.PI // returns PI
Math.SQRTnum // returns the square root of num

Converting to integer/floats

parseFloat(string/char) self explanatory
parseInt(string/char) self explanatory

toFixed(number_of_digits_after_dot) sets the number of digits of a decimal number after the dot. If number=0, then there are no digits after the space(Whole number). Returns string.
toPrecision(number_rounding_result) Rounds the number to a precision based on the number_rounding_result

Important values
undefined – The undefined property indicates that a variable has not been assigned a value.
nan – not a number (can be a char/string/bool..) useful method isNaN(string/char/int/float ect…)

Strings

Basic properties

 .length 

retrieves all characters from the string and returns an integer which specifies the amount of char in the given string.

Basic methods:

charAt(index)

returns a char specifying the character at a certain index position (index start from 0)

charCodeAt(index)

returns a integer specifying the unicode number where the char at the given index is located.

concat(params)

concatenates (glues) a string to the previous string( the string specified inside the argument is added to the previous one, multiple strings can be added inside the argument).

fromCharCode(unicode_num);

returns a char based on the unicode value argument input.

indexOf(string/char)

returns a integer index specifying the index position of the first char inside the argument,

common method

lastIndexOf(char)

returns a integer index specifying the index position of the last time the char inside the string appeared..

replace(_to_be_replaced,put_instead_of)

replaces a char/string, with the char/string specified as the first argument,

common method

slice(start_index,end_index)

returns the chars between the start_index and the end_index-1,

common method

split(criteria)

splits the strings inside the main string using a certain criteria (criteria example: “,” ” ” ect.)

common method

substr(start_included, counter_included)

extracts the string from start_included to counter_included. The method actually returns the char from the start_included where this argument is included in the return and the counter_included where this argument is also included in the return. Similar to slice method but slice does not include the second argument index.

substring(start_index, end_index)

almost completely the same as the above method but the end_index is not included it is end_index-1 which is included and between this interval the string is returned.

common method

toLowerCase()

changes the full string to lower case letters no matter what the letters are currently in the string that is being affected.

toUpperCase()

changes the full string to upper case letters no matter what the letters are currently in the string that is being affected.

toString()

converts the data to string so that strings methods can be applied to it.

common method

trim()

removes both spaces at the end and the beginning of a string

Quick reference (basic methods):

-charAt(index)
-charCodeAt(index)
-concat(params)
-fromCharCode(unicode_num_integer)
-indexOf(string_char)
-lastIndexOf(char)
-replace(to_be_replaced,put_instead_of)
-slice(start_index,end_index), goes till end_index-1
-split(criteria)
-substr(start_included,count) includes the char at position start_included and also the count number is included
-substring(start_index,end_index) end_index not included, end_index-1 included in fetching the substring
-toLowerCase()
-toUpperCase()
-toString()
-trim()