![30 JavaScript Interview Questions - Part 2 | Theory and Practice](https://soshace.com/wp-content/uploads/2019/03/js-interview-questions-for-blog.png)
We continue the series with JavaScript interview questions, where we cover basic theory that you might be asked during a technical interview, as well as look into practical problem sets that will prepare you for coding challenges. If you’ve missed Part 1, then here it is – JavaScript Questions Part 1. Without further ado, let’s get started.
Theory
Practice
On a side note, it’s worth mentioning, that everything in this article is written using ES5, for ES6+, please, check back within a couple of weeks for more questions written using ES6 syntax.
Theory
What are the Primitive and Reference types in JavaScript? What are the most important differences between the two?
Primitives are simple types, like String, Number, or Boolean. Reference types are more complex and include Array and Object.
The most important difference can be observed in copying variables. For example, in copying a primitive (a variable holding a number), the new variable will be an actual copy, meaning if you change the first variable, the second variable (holding a copy) will not be changed. Conversely, in reference types, the variables do not store data, but rather — a pointer to a place in memory where that data is stored. Thus, when copying such a variable, you’re actually copying a pointer, and when you change the value of the first variable, the value of the second one will also be changed, because you changed the data in the memory, while pointer stays the same.
For example,
var number1 = 20; var number2 = number1; number1 = 15; console.log(number1); // → 15 console.log(number2); // → 20
Conversely,
var array1 = [1, 2, 3]; var array2 = array1; array1.push(4); console.log(array1); // → [1, 2, 3, 4] console.log(array2); // → [1, 2, 3, 4]
What’s the difference between global and local scope?
By default, all variables, objects, and functions in JavaScript belong to the global scope. When executing code in the browser, that scope is the Window object. Because of that, if you change the variable, it will be changed across all code. The functional or local scope is when you write a function and put its own scope inside the curly braces; inside those braces, you may use the same variable names as in the global scope without interfering with the rest of your code. Variables in the local scope won’t be seen in the global scope.
For example,
var carName = "Volvo"; // code here can use carName function myFunction() { // code here can also use carName var carColor = “red”; } // code here can not use carColor
What are the common ways to create objects in JavaScript? Provide examples.
There are different ways to create objects in JavaScript. Among the three common ones are:
First method (literal notation):
var myObj = { value1: ‘a value’, Fn: function() {...} }
Second method:
var country = new Object (); Contry.name = ‘Italy’;
Third method:
var house = Object.create(null); house size = 45;
Fourth method (constructor functions):
var Person = function() { this.name = ''; this.greet = function() { console.log('Hi, my name is ' + this.name + ' and I am ' + this.age + ' years old!'); } }; var max = new Person();
What is this
in JavaScript? And how can you control the value of this
? Provide examples.
this
is a very important keyword in JavaScript that allows adding properties to an object. You can control the value of this
with the bind()
, call()
and apply()
methods, which allow you to overwrite the default this value.
For example,
call
attaches this into a function and executes the function immediately:
var person = { name: "Jesus Christ", hello: function(thing) { console.log(this.name + " says hello " + thing); } } person.hello("world"); // → "Jesus Christ says hello world" person.hello.call({ name: "Virgin Mary" }, "world"); // → "Virgin Mary says hello world"
bind
attaches this into a function and it needs to be invoked separately like this:
var person = { name: "Jesus Christ", hello: function(thing) { console.log(this.name + " says hello " + thing); } } person.hello("world"); // → "Jesus Christ says hello world" var helloFunc = person.hello.bind({ name: "Virgin Mary" }); helloFunc("world"); // → Virgin Mary says hello world"
apply
is similar to call except that it takes an array-like object instead of listing the arguments out one at a time:
function personContainer() { var person = { name: "Jesus Christ", hello: function() { console.log(this.name + " says hello " + arguments[1]); } } person.hello.apply(person, arguments); } personContainer("world", "mars"); // → "Jesus Christ says hello mars", note: arguments[0] = "world" , arguments[1] = "mars"
What are closures? Provide an example.
A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.
For example,
function getCounter() { var count = 0; return function() { return count += 1; } } var add = getCounter(); // Call add() 3 times add(); add(); add(); // → the count is now 3
In this example, add is assigned the return value of getCounter
function, sets the count to zero, and returns a function expression. Now add becomes a function that is able to access the counter in the parent scope. Now, this is called closure, which makes it possible for a function to have private variables.
How can you “schedule a call” or execute a function at a later time? Provide examples.
There are two methods to execute a function at a later time: by using setTimeout
and setInterval
setTimeout
allows running a function once after the interval of time.
setInterval
allows running a function regularly with the interval between the runs.
However, these methods are outside JavaScript Specifications. But nevertheless, most environments have an internal scheduler and provide those functions (like in Node.js).
For example,
function sayHi() { alert('Hello'); } setTimeout(sayHi, 1000); // → calls sayHi() in one second
And:
let timerId = setInterval(function() { alert('tick'); }, 2000); // → repeat with the interval of 2 seconds setTimeout(function() { clearInterval(timerId); alert('stop'); }, 5000); // → after 5 seconds stop
What are the Event Listeners and why you need them?
The addEventListener()
method attaches an event handler to the specified element without overwriting existing event handlers. You can add as many event handlers to one element as you want, even if they are of the same type. The addEventListener()
method makes it easier to control how the event reacts to bubbling. Syntax: element.addEventListener(event, function, useCapture)
;
Example:
element.addEventListener("mouseover", myFunction); element.addEventListener("click", mySecondFunction); element.addEventListener("mouseout", myThirdFunction);
What is AJAX and how it works?
AJAX stands for Asynchronous JavaScript and XML. AJAX uses a combination of browser built-in XMLHttpRequest
object (to request data from a web server) and JavaScript and HTML DOM (to display or use the data). AJAX can transport data either as XML or as plain text or JSON. AJAX workflow can be represented as follows: An event occurs on a web page, an XMLHttpRequest object is created by JavaScript, the XMLHttpRequest
object sends a request to a web server, the server processes the request and sends a response back to the website, the response is then read by JavaScript and proper action is executed by JavaScript.
What is JSON and why you need one? What are the differences and similarities between JSON and XML?
JSON stands for JavaScript Object Notation and is defined as a syntax for storing and exchanging data. When the data is exchanged between browser and server, it can only be text, JSON is exactly that, and any JavaScript object can be converted to JSON and visa versa, JSON back to JavaScript object.
Similarities with XML: both are human readable and self-describing, hierarchical (values within values), can be both parsed and used by many programming languages, and can be fetched with an XMLHttpRequest
Differences: JSON can be parsed by a standard JavaScript function, while XML has to be parsed with an XML parser. JSON is much shorter, quicker to write and read, can use arrays and doesn’t use end tag.
What is jQuery and should you use it in 2019?
JQuery is a JavaScript library that was first created to handle Browser Incompatibilities and to simplify HTML DOM Manipulation, Event Handling, Animations, and Ajax. JQuery takes a lot of complicated JavaScript tasks and simplifies them into methods that you can call with a single line of code.
It used to be pretty popular back in the day, but now some of the needs for jQuery has been superseded by modern browsers and frameworks. However, this library is still in use by a lot of developers. Today, Selectors, API, and Fetch have been standardized to the browser, so the need for jQuery is declining rapidly.
Practice
Write a JavaScript program to create a Clock.
Sample Output (will come every second):
“11:17:22”
“11:17:23”
“11:17:24”
Answer
function pad(symb) { return String(symb).length == 1 ? '0' + symb : symb; } function clock() { var time = new Date(), hours = time.getHours(), minutes = time.getMinutes(), seconds = time.getSeconds(); return pad(hours) + ':' + pad(minutes) + ':' + pad(seconds); } setInterval(function() { console.log(clock()); }, 1000);
Write a JavaScript function to create random hex color.
Sample Output: “#62c0d8”
Answer
// using function pad from previous task function randHex() { return pad(Math.floor(Math.random() * 256).toString(16)); } function randHexColor() { return '#' + randHex() + randHex() + randHex(); } console.log(randHexColor());
Write a JavaScript function that accepts a number as a parameter and check if the number is prime or not.
Note : A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Answer
function isPrime(n) { if (n === 1) { return false; } else if (n === 2) { return true; } else { for (var i = 2; i < n; i++) { if (n % i === 0) { return false; } } return true; } } console.log(isPrime(23));
Write a JavaScript program to remove duplicate items from the char array.
Sample Input: [‘d’, ‘3’, ‘a’, ‘d’, ‘d’, ‘c’, ‘c’, ‘3’, ‘1’, ‘a’, ‘d’]
Sample Output : [‘1’, ‘3’, ‘d’, ‘a’, ‘c’]
Answer
function removeDuplicates(num) { var x, len = num.length, out = [], obj = {}; for (x = 0; x < len; x++) { obj[num[x]] = 0; } for (x in obj) { out.push(x); } return out; } console.log(removeDuplicates(['d', '3', 'a', 'd', 'd', 'c', 'c', '3', '1', 'a', 'd']));
Write a JavaScript program to find the most frequent item of an array.
Sample Input:[‘d’, ‘3’, ‘a’, ‘d’, ‘d’, ‘c’, ‘c’, ‘3’, ‘1’, ‘a’, ‘d’]
Sample Output : “d: 4”
Answer
function mostFrequent(arr) { var obj = {}, symb = '', max = 0; for (var i = 0; i < arr.length; i++) { if (typeof obj[arr[i]] === 'undefined') { obj[arr[i]] = 1; } else { obj[arr[i]] += 1; } } Object.keys(obj).forEach(function(key) { if (obj[key] > max) { symb = key; max = obj[key]; } }); return symb + ': ' + max; } console.log(mostFrequent(['d', 3, 'a', 'd', 'd', 'c', 'c', 3, 1, 'a', 'd']));
Write a JavaScript function to generate an array between two integers of 1 step length.
Sample Input 1: -3, 5
Sample Output 1: [-3, -2, -1, 0, 1, 2, 3, 4, 5]
Sample Input 2: 5, -3
Sample Output 2: [5, 4, 3, 2, 1, 0, -1, -2, -3]
Answer
function getRange(start, end) { var arr; if (start > end) { arr = new Array(start - end + 1); for (var i = 0; i < arr.length; i++, start--) { arr[i] = start; } } else { arr = new Array(end - start + 1); for (var j = 0; j < arr.length; j++, start++) { arr[j] = start; } } return arr; } console.log(getRange(-3, 5)); console.log(getRange(5,-3));
Write a JavaScript program to find the greatest common divisor of two positive numbers.
Sample Input: 32, 24
Sample Output: 8
Answer
function gcd(a, b) { return b ? gcd(b, a % b) : a; } console.log(gcd(32, 24));
Write a JavaScript program to get the first n Fibonacci numbers.
Note : The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . . Each subsequent number is the sum of the previous two.
Sample Input: 7
Sample Output: [0, 1, 1, 2, 3, 5, 8]
Answer
var fibonacci = function(n) { if (n === 1) { return [0]; } else if (n === 2) { return [0, 1]; } else { var s = fibonacci(n - 1); s.push(s[s.length - 1] + s[s.length - 2]); return s; } }; console.log(fibonacci(7));
Write a JavaScript function to round down an integer value to the previous multiple of 5.
Sample Input 1: 21
Sample Output 1: 20
Sample Input 2: 99
Sample Output 2: 95
Answer
function floor5(num) { return Math.floor(num / 5) * 5; } console.log(floor5(21)); console.log(floor5(99));
Write a JavaScript function to check that two words are anagrams (formed by rearranging the letters of another).
Answer
function checkAnagrams(a, b) { return a.split('').sort().join('') === b.split('').sort().join(''); } console.log(checkAnagrams('cinema', 'iceman'));
Conclusion
Please, come back a few weeks later for the continuation of the series, where we cover ES6 (and above) JavaScript interview questions.