Keep it Simple- 2: Pass By Reference Vs Pass By Value

Pass By Reference Vs Pass By Value, which of these two JavaScript follows? Well JS is pretty good at handling both the pass by reference and pass by value. Let’s look into the basic definition of both the methods first and then dig into How JS uses these methods.

Pass By Reference: Imagine, you and your friend are on a same boat and you want to reach somewhere, if the boat has reached the other end of the river then both you and your friend will also been reached. So, one’s status is affecting other’s status.

xophcjaathopsououswi

Pass By Value:  Here each will be sailing in their own boats, so if one boat has reached the other end of the river, it doesn’t mean that other boats had also reached the end. So, here one boat is independent on other boats.  31863404-Иллюстрация-Благодаря-kids-пробуя-различные-водные-виды-спорта

How JavaScript is handling both the methods?

JS follows pass by reference  in case of objects and arrays i.e., if they are passed to a function and the values inside the function are assigned to a new value then it does affects the original value as well.

passByRef

It follows pass by value in case of variables like  boolean, string, number i.e., if they are passed to a function and the values inside the function are assigned to a new variable then it doesn’t going to affect the original value.passByValue

Keep It Simple -1: Five Simple Facts of Sort() in VanillaJS

It is always a good idea to get a strong knowledge on basics. We have many ways to sort elements in most of the JavaScript frameworks in angularJS, react JS etc., here lets see how it is done in Plain/VanillaJS.

In JavaScript, sort() always tries to put elements in ascending or alphabetical order if none specified. Here are 5 basic and simple facts about sort() in plain JavaScript-

  1. It sorts the elements with same special characters as expected
    Ex: [‘$5’, ‘$1’, ‘$2’] gives $1, $2, $5 
  2. When same element with different characters are in array then it sorts according to the special char but not based on the digits.
    Ex: [ ‘$3’, ‘*4′,’@1’, ‘&2’] gives $3, &2, *4, @1
  3. It doesn’t sort elements with different number of digits.
    Ex: [1,2,10,3] gives 1,10,2,3
  4. When an empty string is involved with numbers and alphabets, it always puts the empty string at first, then numbers will be sorted in ascending order and then strings will sorted alphabetically.
    Ex: [‘bananas’, ‘apple’, ”,1, 5] gives  ,1,5,apple,banana
  5. If an array has negative numbers involved with positive numbers, it just considers negative numbers together and tries to sort them ascending without considering ‘-‘ and then sorts positive numbers.
    Ex: [1, -15, -1, -3, 2, -2] gives  -1,-15,-2,-3,1,2