Some confusing JS stuff

Kazi Mashry
6 min readAug 7, 2020

Disclaimer: If you’re not a beginner then probably this article is not for you😊

slice() vs splice():

As a beginner, we have confusion about JavaScript slice() and splice(). Both of them are almost the same by syntax and used as array method. So in this article, I’ll write about their usage and differences. Stay tuned. 😉

Photo by Hugo Aitken on Unsplash

Let's understand these two methods with an example. Let's say, we have an array named numbers, declared like below:

let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

So here, if we want to use these two methods we simply have to do this:

let part = numbers.slice(starting_index, end_index);let removed = numbers.splice(starting_index, number_of_element_removed, values_that_eill_replace(optional));

Let’s say, we want to fetch the values of the range which starts from index 2 and ends with index 5. That means we want an array with [2, 3, 4] that will be fetched from the numbers array. In this case, we’ll use the slice() method. So the code will be like,

let part = numbers.slice(2, 5);

Basically, the slice() method has no effect on the main array, (numbers array in our example).

Now, let’s say, we want to remove or cut off a part from the numbers array. In this case, we’ll use the splice() method. In this method, firstly, we have to pass the index value as a parameter that’ll indicate from where we want to remove or cut off the array. Secondly, we have to pass the number of elements we want to cut off from the original array. Then we can pass several values as parameters that will be positioned from the starting index of the removed part.

For example, let’s say, we want to remove a part from index 3 and remove 5 elements. Then,

let removed = numbers.splice(3, 5);

So, now, the numbers array has become,

numbers = [0, 1, 2, 8, 9, 10, 11, 12, 13, 14, 15];

As the splice() method returns an array so the removed array has become

removed = [3, 4, 5, 6, 7];

Now, if we pass more values that’ll be positioned from the first removed position then the syntax will be like,

let removed = numbers.splice(3, 5, 10, 44, 45, 55, 32, 44, 54, 66);

So, now, the numbers array has become,

numbers = [0, 1, 2, 10, 44, 45, 55, 32, 44, 54, 66, 8, 9, 10, 11, 12, 13, 14, 15].;

And the removed array will be the same as before.

map() vs filter():

There is another confusing topic to me was the map() and the filter(). Let’s dig into it.

Photo by Caleb Dow on Unsplash

map():

Let’s say, someone asked you to double every value of an array and store them into another array. As a beginner, we’ll use for loop(or while loop sometimes). But there is another smart way to do this thing. We can use a map() for this. It’ll be like,

const numbers = [1, 2, 3, 4, 5, 6, 7, 8];const result_1 = [], result_2 = [];// Beginner’s way:for(let i = 0; i < numbers.length; i++) {result_1.push(numbers[i] * 2);}// Smart way(😎)result_2 = numbers.map(element => element*2);

Both of them will generate the same output.

filter():

Now, if we want to fetch those values that are divisible by 2 or 3 then we can do it with a loop.

let result = [];for(let i = 0; i < numbers.length; i++) {
if(numbers[i]%2 == 0 || numbers[i]%3==0){
result.push(numbers[i]);
}
}

Or, we can simply use filter() like this,

let result = numbers.filter(element => element%2==0 || element%3==0);

Both results will be the same.

Basically, the filter() method filters out those values which meet the condition and return an array. On the other hand, the map() method operates a certain operation inside it and captures the returned values and finally returns an array.

Put them together:

Now, let’s say we want to double those values which are odd in the numbers array and fetch them into another array. So we can do that using map() and filter() methods together like this,

const result = numbers.filter(x => x%2==0).map(x => x*2);

So the result array will be,

result = [2, 6, 10, 14];

Hoisting:

Hoisting means raise. Like, if you want to build a multi-floor building then you have to hoist some metallic or heavy things with the help of a crane to the top of the building.

Photo by Arc Sotto on Unsplash

In the same way, JS hoist or raise a variable declaration and a function declaration to the top of the function scope. Those variables and functions can be used from any part of the function without raising any reference error.

console.log(value); //output: undefined
var value = 10;

The code above is equivalent to the code below:

var value;
console.log(value);
value = 10;

That means, JS hoist the declaration part of a variable to the top of the scope. As a result, it doesn’t show any error rather it shows undefined. If here we used let instead of var then there would be an error.

For functions:

Any function declaration will be hoisted at the top.

function myFunction() {    var innerFunction = function() {
anotherFunction();
}
innerFunction(); function anotherFunction() {
console.log("another function");
}
}myFunction(); // output: another function

The above code is equivalent to the code below:

function myFunction() {    function anotherFunction() {
console.log("another function");
}
var innerFunction = function() {
anotherFunction();
}
innerFunction();}myFunction(); // output: another function

But for the below code there will generate an error:

function myFunction() {    function callInnerFunction() {
innerFunction();
}
callInnerFunction(); var innerFunction = function() {
console.log("inner function");
}
}
myFunction();

The error will be like, TypeError: innerFunction is not a function

That means the function callInnerFunction() recognized innerFunction but it isn’t any function but as a declared variable or something. The code above is equivalent to the code below:

function myFunction() {
var innerFunction;
function callInnerFunction() {
innerFunction();
}
callInnerFunction(); innerFunction = function() {
console.log("inner function");
}}myFunction();

If we run this code it’ll also generate an error as above.

So, from above, we can get that, only the declaration part is hoisted. The value assigned remains at its location. A function declaration is hoisted. If you have a function expression only the variable part of the function expression will be hoisted. The definition part will remain at its place.

Closure:

According to the MDN web docs, a closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).

Photo by Tim Mossholder on Unsplash

Very tough definition, right? Okay, let’s look at the code below:

function stopWatch() {
let count = 0;
function increase() {
++count;
return count;
}
return increase;
}
let clock1 = stopWatch();
let clock2 = stopWatch();
clock1() // 1
clock1() // 2
clock1() // 3
clock2() // 1
clock1() // 4
clock2() // 2

Here, an outer function stopWatch contains a local variable named count and returning a function.

In this example, function increase() preserved the value of count when the stopWatch() function is called. Now, when the outer function stopWatch is called and it returns the function increase(), so the value of clock1 and clock2 will be increase() function(returning function). So for both the clock the value of the count is 0. when clock1() is called for several times, the value of the count of clock1 will increase by 1. So, when we call it three times the value of the count has become 3. Again, when we called clock2(), the value of count for clock2 has increased by 1. You would not be able to access (get or set) the value of count from outside. Hence the privacy of the value of “i” is maintained secretly. This is called encapsulation in object-oriented programming.

Conclusion:

Still confused, right? 🤯 Doesn’t matter. It’ll take some time to grasp all the concepts. You know, there is a popular saying that, practice makes a man perfect. So, as a beginner, we need to practice a lot.

Photo by Melanie Dretvic on Unsplash

References:

  1. http://thatjsdude.com/jsConcepts/concepts/scope.html
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
  3. https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4

--

--