10 important JavaScript concepts that can help in interview

Mehnaz Ahmed Khan
10 min readMay 8, 2021

Hello developers!
Today I’ll be sharing some insights regarding 10 important JavaScript Interview questions (according to me). Hopefully it will help you to some extent for enhancing your knowledge.

  1. Truthy and Falsy values
    In JavaScript, there are certain values which by default provides Boolean values true or false. We need to know such values because knowing them comes real handy while writing code. Truthy values are:
1.‘Any number other than zero’
const age = 3; //Assign any value to age, the condition will be true except 0.
if (age){
//some code
}
The if block will execute because age is not equal to 0.
2.Not an empty string ‘ ‘
const name = ' ';
if (name){
//some code
}
The if block will execute because name isn't an empty string, it has space in it.
3.Empty array []
const name = [];
if (name){
//some code
}
The if block will execute because name is an empty array.
4.Empty object {}
const name = {};
if (name){
//some code
}
The if block will execute because name is an empty object.

Falsy values

1. When the number is 0
const age = 0; //Assign any value to age, the condition will be true except 0.
if (age){
//some code
}
The if block will not execute because age is equal to 0.
2. Empty string ''
const name = '';
if (name){
//some code
}
The if block will not execute because name is an empty string.
3. Undefined
let name;
if (name){
//some code
}
The if block will not execute because if we don't declare the value of the variable name then by default it will be undefined. Undefined results in false.
4. Null
const name = null;
if (name){
//some code
}
The if block will not execute because the value of name is null.
5. NaN
const name = NaN;
if (name){
//some code
}
The if block will not execute because the value of name is NaN.

2. Null Vs Undefined
This is a common interview question. We can get undefined in different ways and some of the examples are given below:

1. If we declare a variable and no value is assigned then by default it will be undefined.

let name;
console.log(name); //Output: undefined
2. If a function doesn’t return anything explicitly then we’ll get undefined. Even if we write return at the end of the function but doesn’t mention what to return then still we’ll get undefined.function add(num1, num2) {
const sum = num1 + num2;
return;
}
const result = add(13, 82);
console.log(result); //Output: undefined
3. While calling a function if we don't pass parameters, then by default it will be undefined.function add(num1, num2){
console.log(num1, num2);
}
const result = add(13); //Output: 13 undefined
4. If we try to access certain property in an object which doesn't exist then we'll get undefined.const friend = {name: "Al Pacino", phone: 458421};
console.log(friend.address); //Output: undefined
5. If we try to access certain index in an array which doesn't exist then we'll get undefined.let ages = [7, 9, 11];
console.log(ages[11]); //Output: undefined

But for null we need to declare explicitly meaning we need to assign the value of a variable as null. This assigning indicates that the value of that certain variable is set null by us. When we try to access something that isn’t there we get undefined but if the value returns null that means we assigned it to be null. For example

const name = null;

3. Double equal (==) vs Triple equal (===), implicit conversion

Double equal and triple equal is a very common question for interviews. We will look into examples to clear our concepts.

Using double equal (==)

const first = 2;
const second = '2';
if (first == second) {
console.log("Condition is true");
}
else {
console.log("Condition is false");
}
Output: Condition is true

In this example we can see that, even though const first is number type and const second is string type, in the if {} block, the condition is true . Let’s see how it goes using triple equal (===).

const first = 2;
const second = '2';
if (first === second) {
console.log("Condition is true");
}
else {
console.log("Condition is false");
}
Output: Condition is false

In this example, in the if {} block, the condition is false . Now this happens because double equal (==) attempts to convert the data types into a similar type and then compares the value. But triple equal (===) is strict in case of both value and the type. That is why in the second example, the values are same but data types are different so it became false.

4. Scope, block scope, access outer scope variable

function sum (first, second) {    let result = first + second;
return result;
}
const output = sum(3, 7);
console.log(result);
console.log(output);

In this example, we’ll receive an error because we can’t access variable result outside the function sum() .

Another example

let bonus = 20;
function sum (first, second) {
let result = first + second + bonus;
return result;
}
const output = sum(3, 7);
console.log(bonus);
console.log(output); //Output is 30

In this case, we can access the variable bonus outside the function sum() . This says that if we declare a variable inside a block or function, the scope of that variable is limited to that block or function. Another example

let bonus = 20;
function sum (first, second) {
let result = first + second + bonus;
if(result > 9){
const mood = "happy";
}
console.log(mood);
return result;
}
const output = sum(3, 7);
console.log(output);

In this example, we’ll get an error because we’re trying to access const mood outside the if {} block (inside which we initialized). const mood can only be accessed inside the if {} block. But if we used var instead of const or let some strange things happen.

let bonus = 20;
function sum (first, second) {
let result = first + second + bonus;
if(result > 9){
var mood = "happy";
mood = "cranky";
}
console.log(mood);
return result;
}
const output = sum(3, 7);
console.log(output);
Output: cranky
30

Here, we can access the var mood outside the if {} block and this is strange. This strange behaviour of var variables is what we call hoisting. In JavaScript, when a var variable is declared in a scope, then that variable is hoisted to it’s parent scope. But only the variable name is hoisted, not the value assigned to it. The following example will clear this one.

console.log(day); //Output: undefined
var day = "Friday";
console.log(day); //Output: Friday

5. Let, const, array declared with const, object declared with const

Previously before ES6, we used to initialize a variable using var which created some confusions because of hoisting. Now we are relieved from such dilemma because of introduction of let and const . Now the question is how does const and let solves our problem and what’s the differences between these two?

const name = 'Adam Sandler';
name = 'Michael Keaton';
This is not possible in case of const. Once the value is assigned, you can't change the value of const.let name = 'Adam Sandler';
name = 'Michael Keaton';
This is possible for let. You can change the value later on. This is the primary difference between let and const.

Moreover, let and const both are scope variables and takes away our worries regarding hoisting confusions. We can get some clarity regarding const and let variables of array type using the following examples.

CONST
const numbers = [12, 45];
numbers[1] = 88; //We can change the value of certain index of an array.numbers.push(12); //We can push elements.numbers = ['Omar', 'Salman', 'Omit Hasan']; / numbers = [78, 90, 99];
//But we can't initialize new values.
LET
let numbers = [12, 45];
numbers[1] = 88; //We can change the value of certain index of an array.numbers.push(12); //We can push elements.numbers = ['Omar', 'Salman', 'Omit Hasan']; / numbers = [78, 90, 99];
//For let variables, we can initialize new values.

We can get some clarity regarding const and let variables of object type using the following examples.

CONST
const hero = { name: 'Tom Cruise', phone: 4578 };
hero.name = 'Keanu Reeves'; //We can change property values
hero.bikeLover = true; //We can add properties
hero = {name: "Russel Crowe", phone: 6597};
//We can't initialize new values
LET
let hero = { name: 'Tom Cruise', phone: 4578 };
hero.name = 'Keanu Reeves'; //We can change property values
hero.bikeLover = true; //We can add properties
hero = {name: "Russel Crowe", phone: 6597};
//We can initialize new values

6. Arrow function, multiple parameter, function body

Generally we write function like these.

//Most common way of writing function
function doubleIt(num) {
return num * 2;
}
//Another way of writing function
const doubleIt = function myFunc(num) {
return num * 2;
}
const result = doubleIt(5);

Arrow function is something introduced on ES6 and made developers life very easy when it comes to using map, filters, find, forEach. The above function can be written like this.

const doubleIt = num => num * 2;

Here num is the parameter we are passing for the function named doubleIt. num * 2 is basically what we wanted to return but without writing return. In arrow function, if the return statement isn’t more than a single line then we don’t have to write return explicitly. But if it is more than a single line then follow the format shown below.

const doMath = (x, y) => {
const sum = x + y;
const diff = x - y;
const result = sum * diff;
return result;
}

Also in our previous example, when we passed num as a parameter we didn’t use any circular brackets like (x,y) the example shown above. This is because if the number of parameter we are passing is singular then it isn’t mandatory to give brackets. But if the parameters we’re passing is more than one then using brackets and separating them with comma is mandatory. In absence of parameters we write like this.

const give5 = () => 5;

7. When and how to use JavaScript callback function

function welcomeGuest(name){
console.log("Welcome", name);
}
const actorName = 'Tom Hanks';
welcomeGuest(actorName);

When we declare a function named welcomeGuest() we set a parameter named name . When we are calling the function welcomeGuest() , we are passing a variable named actorName whose value is Tom Hanks . This means

welcomeGuest(actorName);Behind the scenesname = actorName 
or name = 'Tom Hanks'
function welcomeGuest('Tom Hanks'){
console.log("Welcome", 'Tom Hanks');
}

We can also pass functions inside functions as parameters.

const actorName = 'Tom Hanks';function welComeGuest(name, greetHandler){
greetHandler(name);
}
function greetMorning(name){
console.log('Good Morning', name);
}
function greetEvening(name){
console.log('Good Evening', name);
}
welComeGuest(actorName, greetEvening);Output: Good Evening Tom Hanks.

8. Check whether a number is a Prime Number or not

A very common question in interview that developers faces. I will write the code first and will try to explain it.

function isPrime(n){
for (let i = 2; i < n; i++) {
if (n % i === 0) {
return "This isn't a prime number";
}
}
return "This is a prime number";
}
const result = isPrime(121);
console.log(result);

Here we declared a function named isPrime where it takes an input of parameter n and after calculating the function will return if the number is a prime number or not. Here we used for loop to reiterate and test the condition n % i == 0 . The loop variable started from 2 because i can’t be 0 or 1. In the for loop, i will run till the value less than n and if {} block will test for each values of i, if there is any factor available for n . If there is any, then it will be divisible by that number and return This isn’t a prime number . If that isn’t the case then the loop will complete and then the function will return This is a prime number.

9. Count the number of words in a string

Another common question in interview that developers faces. I will write the code first and will try to explain it.

function countWords(speech) {
let count = 0;
for (let i = 0; i < speech.length; i++) {
const char = speech[i];
if (char === ' ' && speech[i - 1] !== " ") {
count++;
}
//speech[i-1] != " " This part is added to not calculate unintended spaces
}
count++;
console.log(count);
}
const speech = "Kate Winslet is the sweetest person I have ever known.";countWords(speech);Output: 10

Here the function countWords() will basically count the number of words a sentence has. Inside the function countWords() we used the variable count which will count the number of words present in the sentence that we passed as a parameter named speech. Just like an array, we can find the length and index of a string data type. We know that the words in a sentence are separated with a single space and that is what we’ll be looking for to count the number of words present in a sentence. Whenever this test is passed (char === ‘ ‘ && speech[i — 1] !== “ “) , the value of count is increased by 1 to mark the number of words present in the sentence so far. speech[i — 1] !== “ “ is basically used to avoid error in counting when there are unintended spaces along with the singular spacing between two words. Before displaying the number of words present in a sentence, we increased the value of count once more because the initial value of count was 0.

10. Reverse a string

This is the final gig in this blog. Here we’ll get to see how to reverse a string using functions.

function reverseString(str){
let reverse = "";
for (let i=0; i<str.length; i++){
const char = str[i];
reverse = char + reverse;
}
return reverse;
}
const statement = "Keanu Reeves";
console.log(reverseString(statement));
Output: seveeR unaeK

The function reverseString() takes any string through the parameter str which we intend to reverse. We initialized a variable reverse to store the reversed string data. We used for loop to capture each string data and added the string data one by one is reverse order. The single line is the game changer here reverse = char + reverse; . If we write this single line like this reverse = reverse + char; , then we won’t get our desired outcome, so we need to be extra careful when we try to apply our logic. Other than that the entire code is preety basic and self explanatory.

This was all from me for now. I hope to learn from the community by contributing and share our conflict of opinions in a respectful mannner. Please leave a comment below if you feel like I need to improve in my writings. Till then Happy Coding!

--

--

Mehnaz Ahmed Khan
0 Followers

Web Developer | React | JavaScript | Programmer