JavaScript, CSS: interview questions and algorithms

Taken from JS: Interview Algorithm:

Wanted more interview algorithms? – https://projecteuler.net/archives

1. check Prime

Question: How would you verify a prime number?

Answer: a prime number is only divisible by itself and 1. So, i will run a while loop and increase by 1. (look at the code example. If you dont get it. this is not your cake. do learn javaScript basics and come back.)


function isPrime(n){
  var divisor = 2;

  while (n > divisor){
    if(n % divisor == 0){
     return false; 
    }
    else
      divisor++;
  }
  return true;
}

> isPrime(137);
  = true
> isPrime(237);
  = false
        

Interviewer: Can you make this better?

You: yes. the divisor are increased 1 at a time. after 3 i can increase by 2. if a number is divisible by any even number, it will be divisible by 2.

Extra: if you dont have to increase the divisor up to the number. you can stop much earlier. let me explain it in the following steps (just seat back and read as many times as needed)

Show Explanation

2. Prime Factors

Question: How could you find all prime factors of a number?

Answer: Run a while loop. start dividing by two and if not divisible increase divider until u r done.


function primeFactors(n){
  var factors = [], 
      divisor = 2;
  
  while(n>2){
    if(n % divisor == 0){
       factors.push(divisor); 
       n= n/ divisor;
    }
    else{
      divisor++;
    }     
  }
  return factors;
}

> primeFactors(69);
  = [3, 23]
        

Interviewer:What is the run time complexity? can you make this better

You: this is O(n). you can increase divisor by 2 form divisor = 3. Because, if a number is divisible by any even number it would divisible by 2. Hence, you dont need to divide by even numbers. Besides, you will not have a factor bigger than half of its value. if you want make it complex use tough concept in no. 1 (try-2. if u get it)

3. Fibonacci

Question: How do get nth Fibonacci number?

Answer: I create an array and start from iterate through.

Fibonacci series is one of the most popular interview question for beginners. so, you have to learn this one.

try 1


function fibonacci(n){
  var fibo = [0, 1];
  
  if (n <= 2) return 1;

  for (var i = 2; i <=n; i++ ){
   fibo[i] = fibo[i-1]+fibo[i-2];
  }

 return fibo[n];
} 

> fibonacci(12);
  = 144       

Interviewer: What is the run time complexity?

you: O(n)

Interviewer: can you make it recursive?

try 2


function fibonacci(n){
  if(n<=1)
    return n;
  else
    return fibonacci(n-1) + fibonacci (n-2);  
}

> fibonacci(12);
  = 144
         

Interviewer: What is the run time complexity?

You: O(2n). detail about complexity

4. Greatest Common Divisor

Question: How would you find the greatest common divisor of two numbers?


function greatestCommonDivisor(a, b){
  var divisor = 2, 
      greatestDivisor = 1;

  //if u pass a -ve number this will not work. fix it dude!!
  if (a < 2 || b < 2)
     return 1;
  
  while(a >= divisor && b >= divisor){
   if(a %divisor == 0 && b% divisor ==0){
      greatestDivisor = divisor;      
    }
   divisor++;
  }
  return greatestDivisor;
}

> greatestCommonDivisor(14, 21);
  =7 
> greatestCommonDivisor(69, 169);
  = 1

        

fancy algorithm

Sorry. can’t explain it. As i myself dont understand it 80% of the times. my algorithm analysis instructor told about this and stole if from class note (i am a good student, btw!)


function greatestCommonDivisor(a, b){
   if(b == 0)
     return a;
   else 
     return greatestCommonDivisor(b, a%b);
}
        

Note: use your brain to understand it.

5. remove Duplicate

Question: How would you remove duplicate members from an array?

Answer: will start a while looping and keep an object/ associated array. If i find an element for the first time i will set its value as true (that will tell me element added once.). if i find a element in the exists object, i will not insert it into the return array.


function removeDuplicate(arr){
  var exists ={},
      outArr = [], 
      elm;

  for(var i =0; i<arr.length; i++){
    elm = arr[i];
    if(!exists[elm]){
      outArr.push(elm);
      exists[elm] = true;
   }
  }
  return outArr;
}

> removeDuplicate([1,3,3,3,1,5,6,7,8,1]);
  = [1, 3, 5, 6, 7, 8]
        

6. merge two sorted array

Question: How would you merge two sorted array?

Answer: I will keep a pointer for each array and (read the code. and be careful about this one.)


function mergeSortedArray(a, b){
  var merged = [], 
      aElm = a[0],
      bElm = b[0],
      i = 1,
      j = 1;
  
  if(a.length ==0)
    return b;
  if(b.length ==0)
    return a;
  /* 
  if aElm or bElm exists we will insert to merged array
  (will go inside while loop)
   to insert: aElm exists and bElm doesn't exists
             or both exists and aElm < bElm
    this is the critical part of the example            
  */
  while(aElm || bElm){
   if((aElm && !bElm) || aElm < bElm){
     merged.push(aElm);
     aElm = a[i++];
   }   
   else {
     merged.push(bElm);
     bElm = b[j++];
   }
  }
  return merged;
}

> mergeSortedArray([2,5,6,9], [1,2,3,29]);
 = [1, 2, 2, 3, 5, 6, 9, 29]
        

7. swap number without temp

Question: How would you swap two numbers without using a temporary variable?

Answer: Waste time about thinking it. though u know the answer, act like you are thinking and take your time to answer this one.


function swapNumb(a, b){
  console.log('before swap: ','a: ', a, 'b: ', b);
  b = b -a;
  a = a+ b;
  b = a-b;
  console.log('after swap: ','a: ', a, 'b: ', b);  
}

> swapNumb(2, 3);
   = before swap:  a:  2 b:  3
   = after swap:  a:  3 b:  2 
        

bit manipulation: Sorry, i can’t explain this to you. Kinjal Dave suggested logical conjunction to understand it. Waste 30 min there at your own risk.


function swapNumb(a, b){
  console.log("a: " + a + " and b: " + b);
  a = a ^ b;
  b = a ^ b;
  a = a ^ b;
  console.log("a: " + a + " and b: " + b);
}

> swapNumb(2, 3);
  = a: 2 and b: 3
  = a: 3 and b: 2
        

8. string reverse

Question: How would you reverse a string in JavaScript?

Answer: I can loop through the string and concatenate letters to a new string

try 1


function reverse(str){
  var rtnStr = '';
  for(var i = str.length-1; i>=0;i--){
    rtnStr +=str[i];
  }
  return rtnStr;
}

> reverse('you are a nice dude');
  = "edud ecin a era uoy"
        

Interviewer: You know concatenation performed well in modern browsers but becomes slow in older browsers like IE8. Is there any different way, you can reverse a string?

Answer: sure. i can use an array and also add some checking. if string is null or other than string this will fail. let me do some type check as well. Using this array is like using string buffer in some server side languages.

try 2


function reverse(str){
  var rtnStr = [];
  if(!str || typeof str != 'string' || str.length < 2 ) return str;
  
  for(var i = str.length-1; i>=0;i--){
    rtnStr.push(str[i]);
  }
  return rtnStr.join('');
}
        

Interviewer: What is the run time complexity?

You: O(n)

Interviewer: Can you make this better?

You: I can loop through half of the index and it will save little bit. (this is kind of useless, might not impress interviewer)

try 3


function reverse(str) {
  str = str.split('');
  var len = str.length,
      halfIndex = Math.floor(len / 2) - 1,
      revStr;
  for (var i = 0; i <= halfIndex; i++) {
    revStr = str[len - i - 1];
    str[len - i - 1] = str[i];
    str[i] = revStr;
  }
  return str.join('');
}
        

Interviewer: That works, but can u do it in a recursive way?

You: sure.

try 4


function reverse (str) {
    if (str === "") {
        return "";
    } else {
        return reverse(str.substr(1)) + str.charAt(0);
    }
}
        

try 5

Interviewer: Can you use any build in method to make it little cleaner?

You: yes.


function reverse(str){
  if(!str || str.length <2) return str;
  
  return str.split('').reverse().join('');
}
        

try 6

Question: Can you make reverse function as string extension?

Answer: I need to add this function to the String.prototype and instead of using str as parameter, i need to use this


String.prototype.reverse = function (){
  if(!this || this.length <2) return this;
  
  return this.split('').reverse().join('');
}

> 'abc'.reverse();
  = 'cba'
        

9. reverse words

Question: How would you reverse words in a sentence?

Answer: You have to check for white space and walk through the string. Ask is there could be multiple whitespace.


//have a tailing white space
//fix this later
//now i m sleepy
function reverseWords(str){
 var rev = [], 
     wordLen = 0;
 for(var i = str.length-1; i>=0; i--){
   if(str[i]==' ' || i==0){
     rev.push(str.substr(i,wordLen+1));
     wordLen = 0;
   }
   else
     wordLen++;
 }
 return rev.join(' ');
}
        

A quick solution with build in methods:


function reverseWords(str){
  return str.split(' ').reverse();
}
        

10. reverse in place

Question: If you have a string like “I am the good boy”. How can you generate “I ma eht doog yob”? Please note that the words are in place but reverse.

Answer: To do this, i have to do both string reverse and word reverse.


function reverseInPlace(str){
  return str.split(' ').reverse().join(' ').split('').reverse().join('');
}

> reverseInPlace('I am the good boy');
 = "I ma eht doog yob"
        

Interviewer: ok. fine. can you do it without using build in reverse function?

you: (you mumbled): what the heck!!


//sum two methods.
//you can simply split words by ' '
//and for each words, call reverse function
//put reverse in a separate function


//if u cant do this, 
//have a glass of water, and sleep
        

11. First non repeating char

Question: How could you find the first non repeating char in a string?

Answer: You must ask follow up questions.

Clarification: Is it case sensitive?

Interviewer: interviewer might say no.

Clarification: is it very long string or couple hundred?

Interviewer: Why does that matter

you: for example, if it is a very long string say a million characters and i want to check whether 26 English characters are repeating. I might check whether all characters are duplicated in every 200 letters (for example) other than looping through the whole string. this will save computation time.

Interviewer: For simplicity, you string is “the quick brown fox jumps then quickly blow air”

Clarification: (silly question) ascii or unicode.


function firstNonRepeatChar(str){
  var len = str.length,
      char, 
      charCount = {};
  for(var i =0; i<len; i++){
    char = str[i];
    if(charCount[char]){
      charCount[char]++;
    }
    else
      charCount[char] = 1;
  }
  for (var j in charCount){
    if (charCount[j]==1)
       return j;
  }
}  

>firstNonRepeatChar('the quick brown fox jumps then quickly blow air');
 = "f"
        

this has one problem. It is not guaranteed that for in loop will be executed in order.

12. remove duplicate char

Question: How will you remove duplicate characters from a sting?

You: This is very similar to first non repeating char. You will asks similar question. Is it case sensitive.

If interviewer says, this is case sensitive then life become easier you. If he says no. you can either use string.toLowercase() to make whole string lower. he might not like it. because return string will not posses the same case. So


function removeDuplicateChar(str){
  var len = str.length,
      char, 
      charCount = {}, 
      newStr = [];
  for(var i =0; i<len; i++){
    char = str[i];
    if(charCount[char]){
      charCount[char]++;
    }
    else
      charCount[char] = 1;
  }
  for (var j in charCount){
    if (charCount[j]==1)
       newStr.push(j);
  }
  return newStr.join('');
}

> removeDuplicateChar('Learn more javascript dude');
  = "Lnmojvsciptu"
        

Note:this has one problem. It is not guaranteed that for in loop will be executed in order.

For case insensitive: when u r setting property of charCount or increase counter, just make the char.toLowerCase(). or you can do something fancy with charCode (if you can deal with it.)

13. check palindrome

Question: How will you verify a word as palindrome?

Answer: if you reverse a word and it becomes same as the previous word, it is called palindrome.


function isPalindrome(str){
  var i, len = str.length;
  for(i =0; i<len/2; i++){
    if (str[i]!== str[len -1 -i])
       return false;
  }
  return true;
}

> isPalindrome('madam')
  = true
> isPalindrome('toyota')
  = false
        

or you can use build in method


function checkPalindrom(str) {
    return str == str.split('').reverse().join('');
}
        

Similar: Find whether a string contains a contiguous palindromic substring in O(n) time. Can you solve the problem in O(1) time?

14. random between 5 to 7

Question:If you have a function that generate random number between 1 to 5 how could u generate random number 1 to 7 by using that function?

Answer: Very simple. think of some basic arithmetic and you will get it.


function rand5(){
   return 1 + Math.random() * 4;
}

function rand7(){
  return 5 + rand5() / 5 * 2;
}
        

15. missing number

Question: from a unsorted array of numbers 1 to 100 excluding one number, how will you find that number.

Explanation: You have an array of numbers 1 to 100 in an array. Only one number is missing in the array. The array is unsorted. Find the missing number.

Answer: You have to act like you are thinking a lot. and then talk about the sum of a linear series of n numbers = n*(n+1)/2


function missingNumber(arr){
  var n = arr.length+1, 
  sum = 0,
  expectedSum = n* (n+1)/2;
  
  for(var i = 0, len = arr.length; i < len; i++){
    sum += arr[i];
  }
  
  return expectedSum - sum;
}

> missingNumber([5, 2, 6, 1, 3]);
  = 4
        

Note: this one will give u missing one number in any array of length

16. Sum of two

Question: From a unsorted array, check whether there are any two numbers that will sum up to a given number?

Answer: Simplest thing in the world. double loop


function sumFinder(arr, sum){
  var len = arr.length;
  
  for(var i =0; i<len-1; i++){  
     for(var j = i+1;j<len; j++){
        if (arr[i] + arr[j] == sum)
            return true;
     }
  }
  
  return false;
}

> sumFinder([6,4,3,2,1,7], 9);
  = true
> sumFinder([6,4,3,2,1,7], 2);
  = false
        

Interviewer: What is the time complexity of this function

You: O(n2)

Interviewer: Can you make this better

You: Let me see. I can have an object where i will store the difference of sum and element. And then when i get to a new element and if i find the difference is the object, then i have a pair that sums up to the desired sum.

try 2


function sumFinder(arr, sum){
  var differ = {}, 
      len = arr.length,
      substract;
  
  for(var i =0; i<len; i++){
     substract = sum - arr[i];

     if(differ[substract])
       return true;       
     else
       differ[arr[i]] = true;
  }
  
  return false;
}

> sumFinder([6,4,3,2,1,7], 9);
  = true
> sumFinder([6,4,3,2,1,7], 2);
  = false
        

similar problem: find the maximum difference of two numbers in an array max difference

Even tougherFinding three elements in an array whose sum is closest to an given number

17. Largest Sum

Question: How would you find the largest sum of any two elements?

Answer: this is actually very simple and straight forward. Just find the two largest number and return sum of them


function topSum(arr){
  
  var biggest = arr[0], 
      second = arr[1], 
      len = arr.length, 
      i = 2;

  if (len<2) return null;
  
  if (biggest<second){
    biggest = arr[1];
    second = arr[0];
  } 
  
  for(; i<len; i++){

   if(arr[i] > biggest){
      second = biggest;
      biggest = arr[i];
    }
   else if (arr[i]>second){
      second = arr[i];
   }
    
 }
 return biggest + second;
}
        

18. Counting Zeros

Question: Count Total number of zeros from 1 upto n?

Answer: If n = 50. number of 0 would be 11 (0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100). Please note that 100 has two 0. This one looks simple but little tricky

Explanation: So the tick here is. if you have a number 1 to 50 the value is 5. just 50 divided by 10. However, if the value is 100. the value is 11. you will get by 100/10 = 10 and 10/10. Thats how you will get in the more zeros in one number like (100, 200, 1000)


function countZero(n){
  var count = 0;
  while(n>0){
   count += Math.floor(n/10);
   n = n/10;
  }
  return count;
}

> countZero(2014);
  = 223
        

19. subString

Question: How can you match substring of a sting?

Answer: Will use to pointer (one for string and another for the substring) while iterating the string. And will have another variable to hold the starting index of the initial match.


function subStringFinder(str, subStr){
  var idx = 0,
      i = 0,
      j = 0,
      len = str.length,
      subLen = subStr.length;

   for(; i<len; i++){
   
      if(str[i] == subStr[j])
         j++;
      else
         j = 0;
      
      //check starting point or a match   
      if(j == 0)
        idx = i;
      else if (j == subLen)
        return idx;
  }

  return -1;
}

> subStringFinder('abbcdabbbbbck', 'ab')
  = 0
> subStringFinder('abbcdabbbbbck', 'bck')
  = 9

//doesn't work for this one.
> subStringFinder('abbcdabbbbbck', 'bbbck')  
  = -1
            

Question: How can you fix the last problem?

Answer: figure out yourself.

20. Permutations

Question: How would you create all permutation of a string?

Answer: This could be a tough one based on you level of knowledge about algorithm.


function permutations(str){
var arr = str.split(''),
    len = arr.length, 
    perms = [],
    rest,
    picked,
    restPerms,
    next;

    if (len == 0)
        return [str];

    for (var i=0; i<len; i++)
    {
        rest = Object.create(arr);
        picked = rest.splice(i, 1);

        restPerms = permutations(rest.join(''));

       for (var j=0, jLen = restPerms.length; j< jLen; j++)
       {
           next = picked.concat(restPerms[j]);
           perms.push(next.join(''));
       }
    }
   return perms;
}
        

Explanation:

  • Idea: Idea is very simple. We will convert the string to an array. from the array we will pick one character and then permute rest of it. After getting the permutation of the rest of the characters, we will concatenate each of them with the character we have picked.
  • step-1 First copy original array to avoid changing it while picking elements
  • step-2 Use splice to removed element from the copied array. We copied the array because splice will remove the item from the array. We will need the picked item in the next iteration.
  • step-3 [1,2,3,4].splice(2,1) will return [3] and remaining array = [1,2,4]
  • step-4 Use recursive method to get the permutation of the rest of the elements by passing array as string
  • step-5 Finally, concat like a+permute(bc) for each

similar question

  • display prime numbers up to n.
  • Display number which is repeated for event times in an array
  • Fist non repeating character not case sensitive programming praxis
  • count words in a string
  • In an integer array, there is 1 to 100 number, out of one is duplicate, how to find ?
  • implement substring of a string. also make it case sensitive
  • Find a square of a number. but you can only use addition or subtraction but no multiplication or division Odd way to Square

medium level

ref: Coding interview tips

more problems

Need more: CSS Interview Questions, HTML Interview Questions

Taken from http://www.sitepoint.com/5-typical-javascript-interview-exercises/:

  • (function() {
       var a = b = 5;
    })();
    
    console.log(b);

    What will be printed on the console?

Answer

The code above prints 5.

The trick of this question is that in the IIFE there are two assignments but the variable a is declared using the keyword var. What this means is that a is a local variable of the function. On the contrary, b is assigned to the global scope.

The other trick of this question is that it doesn’t use strict mode ('use strict';) inside the function. If strict mode was enabled, the code would raise the error Uncaught ReferenceError: b is not defined. Remember that strict mode requires you to explicitly reference to the global scope if this was the intended behavior. So, you should write:

(function() {
   'use strict';
   var a = window.b = 5;
})();

console.log(b);

2. “Native” methods

Define a repeatify function on the String object. The function accepts an integer that specifies how many times the string has to be repeated. The function returns the string repeated the number of times specified. For example:

console.log('hello'.repeatify(3));

Should print hellohellohello.

Answer

A possible implementation is shown below:

String.prototype.repeatify = String.prototype.repeatify || function(times) {
   var str = '';

   for (var i = 0; i < times; i++) {
      str += this;
   }

   return str;
};

3.

Question 3: Hoisting

What’s the result of executing this code and why.

function test() {
   console.log(a);
   console.log(foo());
   
   var a = 1;
   function foo() {
      return 2;
   }
}

test();

Answer

The result of this code is undefined and 2.

The reason is that both variables and functions are hoisted (moved at the top of the function) but variables don’t retain any assigned value. So, at the time the variable a is printed, it exists in the function (it’s declared) but it’s still undefined. Stated in other words, the code above is equivalent to the following:

function test() {
   var a;
   function foo() {
      return 2;
   }

   console.log(a);
   console.log(foo());
   
   a = 1;
}

test();

4.

What is the result of the following code? Explain your answer.

var fullname = 'John Doe';
var obj = {
   fullname: 'Colin Ihrig',
   prop: {
      fullname: 'Aurelio De Rosa',
      getFullname: function() {
         return this.fullname;
      }
   }
};

console.log(obj.prop.getFullname());

var test = obj.prop.getFullname;

console.log(test());

Answer

The code prints Aurelio De Rosa and John Doe. The reason is that the context of a function, what is referred with thethis keyword, in JavaScript depends on how a function is invoked, not how it’s defined.

In the first console.log() call, getFullname() is invoked as a function of the obj.prop object. So, the context refers to the latter and the function returns the fullname property of this object. On the contrary, when getFullname() is assigned to the test variable, the context refers to the global object (window). This happens because test is implicitly set as a property of the global object. For this reason, the function returns the value of a property called fullname of window, which in this case is the one the code set in the first line of the snippet.

5.

What are JavaScript types?

Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures

JavaScript is a loosely typed or a dynamic language. That means you don’t have to declare the type of a variable ahead of time. The type will get determined automatically while the program is being processed.

Data types

The latest ECMAScript standard defines seven data types:

  • Six data types that are primitives:
  • and Object

    Null type

    The Null type has exactly one value: null. See null and Null for more details.

    Undefined type

    A variable that has not been assigned a value has the value undefined. See undefined and Undefined for more details.

    Number type

    In addition to being able to represent floating-point numbers, the number type has three symbolic values: +Infinity, -Infinity, and NaN (not-a-number).The number type has only one integer that has two representations: 0 is represented as -0 and +0. (“0” is an alias for +0). In the praxis, this has almost no impact. For example +0 === -0 is true. However, you are able to notice this when you divide by zero:

    > 42 / +0
    Infinity
    > 42 / -0
    -Infinity

String type

JavaScript’s String type is used to represent textual data. It is a set of “elements” of 16-bit unsigned integer values.

Indexed collections: Arrays and typed Arrays

Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the ‘length’ property. Additionally, arrays inherit from Array.prototype which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push (adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.

Typed Arrays are new to JavaScript with ECMAScript Edition 6 and present an array-like view of an underlying binary data buffer.

Keyed collections: Maps, Sets, WeakMaps, WeakSets

These data structures take object references as keys and are introduced in ECMAScript Edition 6. Set and WeakSet represent a set of objects, while Map and WeakMap associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.

Determining types using the typeof operator

The typeof operator can help you to find the type of your variable. Please read the reference page for more details and edge cases.

Taken from Commonly asked JavaScript interview questions

6.

Difference between window.onload and onDocumentReady?

The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means there’s a huge delay before any code is executed.
That isnt what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that.

7.

What is the difference between == and === ?

The == checks for value equality, but === checks for both type and value.

8.

What is the difference between undefined value and null value?

undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.
Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically.

9.

What are Javascript closures?When would you use them?

Two one sentence summaries:

* a closure is the local variables for a function – kept alive after the function has returned, or
* a closure is a stack-frame which is not deallocated when the function returns.

A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created.

The following code returns a reference to a function:

function sayHello2(name) {
var text = ‘Hello ‘ + name; // local variable
var sayAlert = function() { alert(text); }
return sayAlert;
}

Closures reduce the need to pass state around the application. The inner function has access to the variables in the outer function so there is no need to store the information somewhere that the inner function can get it.

Taken from Top 85 JavaScript Interview Questions

10.

What is the difference between ViewState and SessionState?

‘ViewState’ is specific to a page in a session.

‘SessionState’ is specific to user specific data that can be accessed across all pages in the web application

11.

What are all the types of Pop up boxes available in JavaScript?

  • Alert
  • Confirm and
  • Prompt

12.

What are escape characters?

Escape characters (Backslash) is used when working with special characters like single quotes, double quotes, apostrophes and ampersands. Place backslash before the characters to make it display.

13.

Explain the for-in loop?

The for-in loop is used to loop through the properties of an object.

The syntax for the for-in loop is –
for (variable name in object){
statement or block to execute
}

14.

Write the point of difference between web-garden and a web-farm?

Both web-garden and web-farm are web hosting systems. The only difference is that web-garden is a setup that includes many processors in a single server while web-farm is a larger setup that uses more than one server.

Taken from Most Common Technical Interview Question for FrontEnd Developers

15.

How can you declare a class in Javascript?

In javascript there’s no classes like in Java, what we actually call a class is in reality a function simulating a class behaviour. For being so flexible, there are many ways to create a class in javascript, below you’ll find 3 ways of doing that.

  • Class using function as a constructor:
function Person(name) {  
    this.name = name;
}
// Creating an object
var person = new Person("Rafael");  
person.name; // "Rafael"  

It’s very important to notice that you have to use the keyword new when creating a newinstance of that class otherwise you will have logical problems regarding the this will reference window object.

  • Class Literal notation:
var person = {  
    name: "",
    setName: function(name) {
        this.name = name;
    }
}
person.setName("Rafael");  
person.name; // "Rafael"  

In this example we don’t use a function to define our class, we are creating a singleton object person with one attribute and one method. You can use that object straightaway, no instantiation in this case.
That notation is useful when you don’t need to create instances of that class or you’ll use it just once in your application.

  • Singleton through a function:
var person = new function() {  
    this.setName = function(name) {
        this.name = name;
    }
    this.sayHi = function() {
        return "Hi, my name is " + this.name;
    }
}
person.setName("Rafael");  
alert(person.sayHi()); // Hi, my name is Rafael  

As you can see in the code snippet above, we have a function like the first example and besides we also have the new keyword before the function declaration. It means that we are creating one instance of that class at the same time we are declaring it.

16.

Difference between null and undefined

This can be tricky and the best way to keep in your head is to memorise because if you try to relate javascript null to other languages, it will get more confusing.
In javascript, null is an object with no value and undefined is a type.

typeof null; // "object"  
typeof undefined; // "undefined"  
var a;  
var b = null;  
a == b; // "true" because their values are the same  
a === b; // "false". they have different types 

17.

When would you use CSS float?

Float is used when you want to make an element of your page (usually an image) be pushed to the right or left and make other elements wrap around it.

18.

When would you use CSS clear?

When you want an element on the left or right of the floating element not to wrap around it, you can use clear.

Taken from Javascript Tasks

19.

Find the biggest element in the array of numbers. Use function Math.max for this

var numberArray = [1, 2, 3, 4, 10, 5, 6, 7];
imGreater = Math.max.apply(null, numberArray);
console.log(imGreater);//10

20.

Make this syntax possible: var a = (5).plus(3).minus(6); //2

This seems like an impossible syntax. But when I think about prototype and Number object everything is possible. JavaScript objects have an attribute, a pointer to another object. This pointer is called as prototype.

Here I will add plus and minus function to Number object’s prototype , so it will be available for all numbers

Number.prototype.plus = function (n) {
    return this + n;
};
Number.prototype.minus = function (n) {
    return this - n;
};
var a = (5).plus(3).minus(6);
console.log(a);//2

21.

Make this syntax possible: var a = add(2)(3); //5

This is my favorite question, and i like to play with closure.

var add = function (a) {
    return function (b) {
        return a + b;
    };
};

console.log(add(2)(3));//5

22.

Object Equality

Question: How would you compare two objects in JavaScript?

Basics: JavaScript has two different approaches for testing equality. Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and user defined objects are compared by their reference. This means it compares whether two objects are referring to the same location in memory.

Answer: Equality check will check whether two objects have same value for same property. To check that, you can get the keys for both the objects. If the number of properties doesn’t match, these two objects are not equal. Secondly, you will check each property whether they have the same value. If all the properties have same value, they are equal.


function isEqual(a, b) {
    var aProps = Object.getOwnPropertyNames(a),
        bProps = Object.getOwnPropertyNames(b);

    if (aProps.length != bProps.length) {
        return false;
    }

    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];
        
        if (a[propName] !== b[propName]) {
            return false;
        }
    }
    return true;
}
        

Limitation:

  • If one of the property values is itself an object
  • If one of the property values is NaN (the only value in JavaScript that is not equal to itself?)
  • If one object has a property with value undefined, while another object doesn’t have the property (which thus evaluates as undefined). Btw, you can solve this problem by using hasOwnProperty

23.

bind

Question: If you want to use an arbitrary object as value of this, how will you do that?

Answer: There are at least three different ways to doing this by using bind, call and apply. For example, I have a method named deductMontlyFee in the object monica and by default value of this would be monica inside the method.


var monica = {
  name: 'Monica Geller',
  total: 400,
  deductMontlyFee: function(fee){
     this.total = this.total - fee;
     return this.name + ' remaining balance is '+ this.total; 
  }
}
        

If I bind the deductMontlyFee of monica with another object rachel and pass rachel as first parameter of the bind function, rachel would be the value of this.


var rachel = {name: 'Rachel Green', total: 1500};
var rachelFeeDeductor = monica.deductMonthlyFee.bind(rachel, 200);

rachelFeeDeductor(); //"Rachel Green remaining balance is 1300"
rachelFeeDeductor(); //"Rachel Green remaining balance is 1100"
        

bind allows you to borrow a method and set the value of this without calling the function. It simply returns an exact copy of the function with new value of this. You can reuse the same function with new value of this without harming the old one.

More questions are in github: Front-end Job Interview Questions

Author: Yauhen Bichel

Software Engineer and Co-Founder 2AY Ltd (https://www.twoay.co.uk, Co-Founder) Our products: MoleCare https://apps.apple.com/us/app/molecare/id1448635328 Secret Lock https://apps.apple.com/by/app/secret-lock/id1470843759 2AY Facebook Page https://web.facebook.com/2ayteam 2AY Ltd messenger bot for our 2AY Facebook Page https://web.facebook.com/2ayteam -> open messenger MoleCare is in Live on NHS App Library https://www.nhs.uk/apps-library/molecare/

Leave a comment