Nail job interviews by knowing the differences between these functions & keywords
Photo by Dex Ezekiel on Unsplash
JavaScript has a lot of functions and reserved words that sound and perform similar actions and many developers use these terms interchangeably without knowing the vital differences between them.
It is not entirely their fault though since JavaScript keeps introducing better ways to perform actions, but for the sake of backward compatibility instead of removing the pre-existing functions that perform the same thing, they tend to add the new ones alongside the old functions.
Before 2015, there was only one way to declare variables and that was with the keyword var
. There was no let
or const
.
Interviewers are keen to know if the candidates are up-to-date with these latest advancements to test how fresh and deep is the candidate's knowledge and his/her grasp on JavaScipt terms that perform similar actions.
Below are 6 differences you should know for your next technical interview.
1. let vs var
Both let
and var
are keywords that are used when declaring variables. While both var
and let
are used for variable declaration in JavaScript but differences exist.
JavaScript had support for let
only since 2015 with the release of the version ES6, whereas var
was present before and was the only way to declare a variable before let
came along.
Another difference is the variable scope, that is, which parts of your program can access and use it. While var
is function scoped, let
uses block scoping.
For a much better understanding, I will share a relevant example.
var a=10;
function myFun(){
for (var i = 0; i < 2; i++) {
console.log(`Inside the loop: ${i}`);
}
console.log(`Outside the loop: ${i}`);
}
myFun();
console.log(i)
The output of the following would be:
Inside the loop: 0
Inside the loop: 1
Outside the loop: 2
error: Uncaught ReferenceError: i is not define
As you can see that we can use the value of the variable i
even outside the for-loop but inside the same function. This is because it is declared using var which means that it will follow function scope. Since the variable a
is defined outside the function, we can use it in the global scope.
Now let’s see the scope of let
.
for (let i = 0; i < 2; i++) {
console.log(`Inside the loop: ${i}`);
}
console.log(`Outside the loop: ${i}`);
Output:
Inside the loop: 0
Inside the loop: 1
error: Uncaught ReferenceError: i is not defined
The output is different because let
follows block-scoped, which means it can be only seen and used in the for-loop in which it is declared and not outside that.
You can find a much more detailed example here.
2. Rest vs Spread
Both rest and spread operators look very similar in terms of syntax. But both are used to perform operations that are fundamentally opposite in nature.
A good developer should be able to stop the difference and know when to use the rest and spread operators.
Rest operator is used when accepting arguments when we don’t know the number of arguments we might receive.
For example, consider the following example:
function sumAll(...args) { // args is the name for the array
let sum = 0;
for (let arg of args)
sum += arg;
return sum;
}
console.log( sumAll(5) ); // 5
console.log( sumAll(5, 10) ); // 15
console.log( sumAll(5, 10, 15) ); //30
We have used rest operators to accept an unknown number of parameters as shown by …args
where ‘args’ is the array name.
Spread operators behave differently even though they look similar in syntax. The spread operator allows arrays/strings/objects to expand into a single list of arguments.
Hence, it serves the exact opposite purpose of that of the rest operators.
const arr = ["2", "3", "4"];
const newArr = ["1", ...arr];
console.log(newArr)
We have used the spread operator on the array arr
to add elements of the array to the new array named newArr
. Our code snippet will log [“1”,”2”,”3”,”4”]
to the console.
3. Function vs method
Most programmers use the term ‘function’ and ‘method’ interchangeably but there exists a subtle but noticeable difference.
In JavaScript, everything is considered to be an object. A string is an object and so is an array. A function is an object but a method is a function that belongs to another object.
In simple words, to call a method, we need to make a reference to the object it belongs to, also sometimes termed as ‘receiver’ object whereas, in the case of a function, we can directly invoke the function.
I know it can be confusing but hopefully, the following code snipper will provide a clear understanding.
var myObject= {
myMethod: function() {
console.log("Method");
}
};
myObject.myMethod;
var myFunction = ()=>{
console.log("function)
}
myFunction();
To invoke myMethod()
we had to first reference myObject
, which, in this case, is the object under which the method is declared. On the other hand, we can invoke myFunction()
without any object reference.
4. Slice vs Splice
Slice and Splice are methods that perform certain operations on arrays. As a developer myself, I always thought they performed the same operations with minimum differences when I started my coding journey.
But both of these methods are very much different, even though they sound similar. In short, the slice methods can be compared to the ‘substring’ method for Strings. The slice method retrieves elements of the array and accepts two parameters — the start and the end index of the elements you wish to retrieve.
const arr = ["Christmas", "Halloween", "New Year"];
console.log(arr.slice(0,2)) // --> ["Christmas","Halloween"]
console.log(arr) // --> ["Christmas", "Halloween", "New Year"]
The reason I have console logged the array ‘arr’ again is to highlight the fact that the slice method doesn’t have any effect on the original array.
The Splice method, on the other hand, accepts more parameters and affects the original array.
The splice methods perform the removal and replacement of elements in the array. Splice methods take a minimum of 2 parameters, that is, the start index and the number of elements to delete from that start index.
However, you can then pass the values you want to insert as parameters. The values you pass will be added after the start index you provided as the first parameter.
const arr = ["Christmas", "Halloween", "New Year"];
console.log(arr.splice(0,1))
console.log(arr);
arr.splice(0,1,"Chistmas");
console.log(arr)
The output of the above code snippet would look like:
["Christmas"]
["Halloween","New Year"]
["Chistmas","New Year"]
If you take a closer look, you can see that the splice methods return the elements it has removed as shown by the first console log where it returns the first element of the array.
Another takeaway is that when we log the array for the second time, we see that the splice method has indeed removed the first element from the original array.
Thus, the slice and splice method are used for entirely different purposes.
5. Triple equals sign (===) vs double equal sign (==)
Knowing the difference between these two can come in quite handy, and not just in interviews but also while building complex apps. One of the advantages of JavaScript is type inference, where it can determine the type for us.
For example, if we store the number 1 in a variable, it automatically determines that it’s a number, and if we try to store “1” in a variable, it can infer the type is String.
While this beginner-friendly approach is welcomed, sometimes we need to match the types for an error-free and robust code.
This is where knowing the difference between triple and double equals sign comes into play. The triple sign equals matches the type as well the value, while the double equal sign just matches the value. As demonstrated by the code snippet provided below:
let number = 1234;
let stringNumber = '1234';
console.log(number == stringNumber); //true
console.log(number === stringNumber); //false
Here, ‘1234’ is a string while 1234 is a number. The tripe operator sign differentiates on the basis of type as well as shown, while the double equals sign just matches the value and not the type.
In fact, when practicing the modern rules of JavaScript, most linting software will flag the double equals sign as a warning of bad practice.
6. Map vs forEach methods
Using these two methods can save you a lot of headaches and also benefit the readability. Although both map()
and forEach()
work on arrays, both are used for different purposes.
Both methods take a function as an argument and both apply this function on every single element of the array. However, they return different values. A forEach method will always return undefined whereas the map method returns a new array after performing the function.
Due to this, map()
becomes chainable, that is, you can attach other methods such as sort()
and reduce()
after it. This is not possible with the forEach method as it returns an undefined value.
var arr= [3,2,1];
var doubled= arr.map(currentValue => currentValue*2).sort();
console.log(doubled) // --> [2,4,6]
var Val= arr.forEach(x=>x*x)
console.log(Val) // --> undefined
console.log(arr) //--> [3,2,1]
In the code snippet above, we have used the map()
on the array, ‘arr’, as well as, chained the sort()
method and store the resulting array in ‘doubled’.
We have then use theforEach()
to square, each element of the array, and store the returned value in variable ‘Val’, which, as the console log shows, contains an undefined value.
Finally, to highlight that nothing has affected the original array, I have logged it as well.
However, just because you can use map()
to perform tasks of the forEach method and much more, doesn’t undermine the value of the forEach method. The forEach method offers a simple replacement for the for-loop as shown below:
var arr= [3,2,1];
for(let i=0;i<arr.length;i++)
console.log(arr[i]**2);
console.log('-------------')
arr.forEach(x=>console.log(x**2))
The output would look like this:
9
4
1
-------------
9
4
1
Hence, if you want to just loop through the elements without the need to store the newly formed array, using the forEach method is the best way to go otherwise you can use the map method.
Final thoughts
JavaScript is evolving to meet the new demands created by the market. Mastering such a popular language can profoundly impact your career as a programmer.
Hence it is becoming increasingly important to stay in touch with the latest development in the field of JavaScript to help keep your career on track. Some of the methods sound and perform similarly such as the forEach and Map methods, but have subtle differences which a proficient developer should be able to leverage.
Moreover, knowing the differences and use cases for some of the most widely used methods and operators is crucial to crack technical job interviews and to obtain an edge over others.
Enjoyed this article? If so, get more similar content by **subscribing to Decoded, our YouTube channel!**