Now that you have made a quality JD, it can still be tricky to evaluate the skills of your applicants when you hire developers. To help you with that, we have created a pool of questions that a good developer should be comfortable with.
It is important to note that the ability to answer these questions doesn't imply that you have a top quality candidate. But it definitely is a big step in that direction.
To help you navigate through these questions, we’ve categorized the interview questions in 3 parts:
A. Basic concepts: Includes all basic concepts used across languages.This will give you an understanding of how strong their programming foundation is.
B. Advanced concepts: Includes all concepts that someone with higher expertise should know.
C. DS/Algorithm questions: To test the logical capability of the candidate.
A. Basic concepts
What is the difference between the operators ==
& ===
in JavaScript?
The comparison operator double equals transform operands of the same type before comparison.
Therefore, JavaScript turns any string into a number when comparing it to a number. Zero is always added to an empty string. A string that contains no numbers is converted to NaN (Not a Number), which produces a false result.
In JavaScript, the triple equals comparison operator is a strict equality comparison operator that returns false for values that are not of the same type. With this operator, type casting is done for equality. For example, the comparison operator ===
will return a false result if we compare 2 with "2".
The main distinction between the ==
and ===
operators is that the former compares variables by correcting for type. For example, if you compare a number with a string with a numeric literal, ==
allows that, whereas ===
doesn't allow that because it checks both the value and the type of two variables. ===
returns false if two variables are not of the same type. ==
, however, returns true.
What is the popular open standard file format (like XML) used with javascript and node.js? And what are the popular commands to convert string to that and vice versa?
It is JSON which stands for Javascript Object Notation. It is a lightweight data interchange format. It is easy for humans to read. Even though it has Javascript in its full form, it is language independent.
It’s built on 2 structures:
- Collection of key-value pairs. This is called an object, dictionary, hashmap, associative array, in different languages
- Ordered list of values, This is called an array, list, vector, in different languages
These are universal data structures which is important for a file format which is language independent.
Example of JSON:
{
"flexiple": {
"top": "1%",
"location": "remote"
},
"blog": {
"topic": "engineering",
"title": "What are stable coins and how do they work?"
}
}
This in XML would look like this:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<blog>
<title>What are stable coins and how do they work?</title>
<topic>engineering</topic>
</blog>
<flexiple>
<location>"remote"</location>
<top>1%</top>
</flexiple>
</root>
Valid JSON
Few of the rules to remember while handling JSON are that:
- Empty objects and arrays are okay
- Strings can contain any unicode character, this includes object properties
- null is a valid JSON value on its own
- All object properties should always be double quoted
- Object property values must be one of the following: String, Number, Boolean, Object, Array, null
- Number values must be in decimal format, no octal or hex representations
- Trailing commas on arrays are not allowed
These are all examples of valid JSON: -
{"name":"John Doe","age":32,"title":"Vice President of JavaScript"}
["one", "two", "three"]
// nesting valid values is okay
{"names": ["John Doe", "Jane Doe"] }
[ { "name": "John Doe"}, {"name": "Jane Doe"} ]
{} // empty hash
[] // empty list
null
{ "key": "\uFDD0" } // unicode escape codes
These are all examples of bad JSON formatting:-
{ name: "John Doe", 'age': 32 } // name and age should be in double quotes
[32, 64, 128, 0xFFF] // hex numbers are not allowed
{ "name": "John Doe", "age": undefined } // undefined is an invalid value
// functions and dates are not allowed
{ "name": "John Doe",
"birthday": new Date('Fri, 26 Jan 2019 07:13:10 GMT'),
"getName": function() {
return this.name;
}
}
Javascript provides 2 methods to encode data structures to JSON and to convert JSON to objects or arrays. These methods are JSON.stringify() and JSON.parse().
JSON.stringify()
It takes a Javascript object or array as input and returns a serialised string form of it.
const obj = {
name: "Flexiple",
city: "Bengaluru"
}
const jsonStr = JSON.stringify(obj)
console.log(jsonStr)
// output is {"name":"Flexiple","city":"Bengaluru"}
JSON.stringify() can take 3 arguments in total, the first one being the data structure.
The second argument, called the replacer parameter, can either be a function or an array. It is used to manipulate the properties (keys and values) in JSON.
let cost = {
candy: 5,
bread: 20,
cheese: 100,
milk: 15
}
let func = (key, value) => {
if (value < 15) {
return undefined
}
return value
}
let arr = ['candy', 'bread']
let jsonStrWithFunc = JSON.stringify(cost, func)
console.log(jsonStrWithFunc)
// Output is {"bread":20,"cheese":100,"milk":15}
let jsonStrWithArr = JSON.stringify(cost, arr)
console.log(jsonStrWithArr)
// Output is {"candy":5,"bread":20}
The third argument, called the space parameter, takes in either a number or a string. It is used to control the spacing of the final string by deciding the size of indentation.
let cost = {
candy: 5,
bread: 20,
cheese: 100,
milk: 15
}
let jsonStrWithNum = JSON.stringify(cost, null, 2)
console.log(jsonStrWithNum)
// Output is
// {
// "candy": 5,
// "bread": 20,
// "cheese": 100,
// "milk": 15
// }
let jsonStrWithStr = JSON.stringify(cost, null, 'xx')
console.log(jsonStrWithStr)
// Output is
// {
// xx"candy": 5,
// xx"bread": 20,
// xx"cheese": 100,
// xx"milk": 15
// }
JSON.stringify() is also popularly used for debugging, as trying to see a JSON object using console.log() isn’t always successful
const obj = {
"nest1": {
"ex": "ex",
"nest2": {
"nest3": {
"ex": "ex",
}
}
}
}
console.log(obj)
// Output is { nest1: { ex: 'ex', nest2: { nest3: [Object] } } }
As we can see that after a certain level of nesting the log just displays ‘[Object]’. Therefore, JSON.stringify() can be used to make debugging easier.
const obj = {
"nest1": {
"ex": "ex",
"nest2": {
"nest3": {
"ex": "ex",
}
}
}
}
console.log(JSON.stringify(obj,null,2))
// Output is
// {
// "nest1": {
// "ex": "ex",
// "nest2": {
// "nest3": {
// "ex": "ex"
// }
// }
// }
// }
JSON.parse()
It takes a JSON string and converts it into its respective data structure
const jsonStr = '{"name":"Flexiple","city":"Bengaluru"}'
const obj = JSON.parse(jsonStr)
console.log(obj)
// output is { name: 'Flexiple', city: 'Bengaluru' }
Calling JSON.parse() on invalid JSON string will throw a SyntaxError.
Cloning Objects in Javascript
These 2 functions of JSON can be used together to clone javascript objects.
const obj = {
"prop1": {
"ex": "ex",
"prop2": {
"ex": "ex"
}
}
}
const objCopy = JSON.parse(JSON.stringify(obj))
console.log(objCopy)
// Output is { prop1: { ex: 'ex', prop2: { ex: 'ex' } } }
But this is not recommended, because of multiple reasons:
- It is slower than alternatives
- This works properly only for valid JSON, but not all javascript objects fall in that category
A better alternative for deep cloning objects would be to either use an npm library called ‘lodash’ or write a custom recursive function to do the same. The spread operator can be used for shallow cloning of objects.
B. Advanced concepts
What are some important JavaScript Unit Testing Frameworks?
Unit.js, QUnit, Jasmine, Karma, Mocha, Jest, and AVA are a few well-known JavaScript unit testing frameworks and tools.
The open-source assertion library Unit.js is known for running on browsers and Node.js. With JavaScript unit testing frameworks like Mocha, Karma, Jasmine, QUnit, Protractor, etc., it has a very high degree of compatibility and provides the assertion list's entire documented API.
Both client-side and server-side JavaScript unit testing is done using QUnit. jQuery projects use this Free JavaScript testing framework. It adheres to the Common JS unit testing Specification for JavaScript unit testing. In addition, the Node Long-Term Support Schedule is supported.
Jasmine is a framework for behavior-driven development used for unit testing JavaScript programs that are both synchronous and asynchronous. It has a simple syntax that can be written for any test and does not require DOM.
Karma is a free and open-source environment for productive testing. Simple workflow management using the command line. It allows the freedom to write tests using QUnit, Mocha, and Jasmine. The test can be executed on actual hardware with simple debugging.
Mocha is browser- and Node.js-based. As a result, asynchronous testing can be done more easily with Mocha. In addition, it delivers precision and adaptability in reporting and provides outstanding support for numerous rich features, including JavaScript APIs and test-specific timeouts.
Facebook has so far tested all of the JavaScript code using jest. In addition, the "zero-configuration testing experience" is offered. It supports running tests that are independent and conflict-free and requires no additional setup, configuration, or libraries.
AVA is a basic framework for unit testing in JavaScript. Both parallel and serial test runs are being performed. The execution of parallel tests proceeds uninterrupted. This testing framework also supports asynchronous testing. JavaScript unit tests are run by AVA using subprocesses.
What is CORS?
CORS stands for Cross Origin Resource Sharing. It is a mechanism that uses additional HTTP headers instructing the browser to allow applications on one origin to accept resources from another origin. A different origin means either different domain, protocol or port.
This is required because browsers, as a security measure, do not allow cross origin HTTP requests initiated from scripts. This is the case with XMLHttpRequest (mostly used method for resource requests) and Fetch API. By default, they allow only same-origin requests.
For example, let’s assume that the front end is hosted on https://a-domain.com and the backend on https://b-domain.com. In such a case, if the front end makes a GET request to https://b-domain.com/posts, it will receive the following error in the console:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://b-domain.com
To prevent this CORS is utilised. Basically, additional headers need to be provided - this is the Access-Control-Allow-Origin header. This can take 2 forms of values:
- Access-Control-Allow-Origin : [origin]
An example of this would be ‘Access-Control-Allow-Origin: https://a-domain.com. This allows requests only from the specified origin to be able to access resources provided.
- Access-Control-Allow-Origin : *
Using the wildcard character (*) means that any site can access the resources provided by your application.
As standard practice, if cross origin requests are being made it is recommended to not use the wildcard character, and instead mention the origin. If the front end is not rendered by the server itself then CORS needs to be used for the client to be able to interact with the server.
In Node.js, you can either directly write the headers for each request or there exists npm packages which plug into frameworks like Express.js. One such example is the ‘cors’ npm package. It is very simple to use:
// declaring app to use express framework
let app = express()
// this is using wildcard character
app.use(cors())
// this is specifying origin
app.use(cors({
origin: 'https://a-domain.com'
}))
// this is specifying cors for specific route
app.get('/', cors(), (req, res) => {
});
In this way CORS can easily be incorporated into your backend server.
What are the vulnerabilities of using cookies? What about the usage of local storage?
Cookies and local storage are primarily used for session management in web application development. What this means is that once the user is authenticated, there needs to be a way for the application to remember the user for a period of time without asking the user to login again.
In an architecture design it is standard to keep the server stateless, but this would mean that the user information cannot be stored on the server. Therefore, the decision was taken to store it on the client. This was originally done using cookies. Cookies are basically a storage facility with the browser, which the client side javascript or the server (using headers) can interact with.
Each item stored in cookies is called a cookie, and each cookie has an expiration time which can be manually set too. The cookie persists in the browser for that duration and is not removed by page refreshes or window being shut. When a client interacts with a server using HTTP requests, then the cookies are also sent along in headers.
The data which is stored in a cookie is generally a token such as a JSON Web Token (JWT). JWT consists of a payload which is used to fetch information about the user. JWT tokens are signed on the server using a secret key. The routes allow only authorized users to check whether the token is present in the cookies. This is the outline of the architecture followed for session management.
Difference between Cookie and Local Storage
Primarily both function in similar ways - i.e. both involve persistent storage in the browser. The differences come in slight nuances of their functioning:
- Local storage does not have the concept of expiration time. So, the developer dealing with it needs to handle the expiration of tokens stored in it. Whereas, the expiration time for cookies can be set while storing the cookie and the browser handles the rest.
- Local storage is not sent with every HTTP request, like a cookie is sent. This reduces load on especially those HTTP requests which are public and do not require to use the token stored.
- The server can directly interact with cookies, whereas only the client side script can interact with local storage.
- Local storage has a much larger storage capacity of 5mb compared to 4kb of cookie. This is primarily because cookies are meant to be read by the server, whereas local storage is meant for the client side to be able to persistently store data.
Vulnerabilities
Local storage
Local storage is accessible only by client-side javascript code. This makes it particularly vulnerable to XSS attacks. XSS (Cross-Site Scripting) attacks are a type of injections in which malicious scripts are injected into otherwise trusted websites due to a vulnerability.
This script then executes on the client’s browser and can access the local storage quite easily. XSS attacks are mainly used to steal cookies, session tokens and other information. After obtaining session tokens they can access protected routes using it. Therefore, storing authentication tokens on local storage is very risky.
Cookies
Cookies function similarly as they can also be accessed by client-side javascript code. They are also vulnerable to XSS attacks, but there can be a further layer of protection added to prevent this.
If the ‘httpOnly’ flag is marked as true while setting cookies then client side javascript cannot access that cookie. This allows only the server side code to interact with it. So this protects it from XSS attacks. However, due to its property of sending a cookie on every request, it gets vulnerable to CSRF/XSRF attacks.
CSRF/XSRF (Cross-Site Request Forgery) attacks are when malicious web apps can influence the interaction between a client browser and a web server that trusts the browser. Therefore, further measures need to be taken like using CSRF tokens and proper use of the Same-Site cookie attribute.
C. Data Structure/ Algorithm
1. Write a program to find whether a string or number is palindrome or not.
import java.util.Scanner;
public class Palindrome {
public static void main (String[] args) {
String original, reverse = "";
Scanner in = new Scanner(System.in);
int length;
System.out.println("Enter a number or a string");
original = in.nextLine();
length = original.length();
for (int i =length -1; i>;=0; i--) {
reverse = reverse + original.charAt(i);
}
System.out.println("The reverse is: " +reverse);
if(original.equals(reverse))
System.out.println("The string is a palindrome");
else
System.out.println("The stringis not a palindrome");
}
}
2. Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.
class ValidParenthesesF {
func isValid(_ s: String) -> Bool {
var stg = [Character]()
for char in s {
if char == "(" || char == "[" || char == "{" {
stg.append(char)
} else if char == ")" {
guard stg.count != 0 && stg.removeLast() == "(" else {
return false
}
} else if char == "]" {
guard stg.count != 0 && stg.removeLast() == "[" else {
return false
}
} else if char == "}" {
guard stg.count != 0 && stg.removeLast() == "{" else {
return false
}
}
}
return stg.isEmpty
}
}
The above code will input 0(false).
3. What will the output of the following code be?
var i = 10;
var f = 5;
var g = 3;
if (i / f / g)
document.write("hi");
else
document.write("hello");
a) hi
b) hello
c) error
d) no output
The answer is A because the floating-point division returns a non zero value = 0.66 which evaluates
to true and outputs ‘hi’.