Web Developer Interview Questions

Génesis García Morilla
10 min readFeb 11, 2020

--

May Stack Overflow Be With You by gengns

A nice list of General Web, HTML, CSS and JavaScript questions that we used during interviews in my previous job : )

General

What is HTTP?

HTTP stands for HyperText Transfer Protocol, a protocol for transmitting resources across the internet.

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML, a set of tecnniques for asynchronous calls that fetch data from a server and update the web without reloading.

What is a SPA?

SPA stands for Single Page Application, a web app / site that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from a server.

What is the difference between SPA and AJAX?

SPA is a way to make applications, and they can make use of AJAX or not. For example, if all the content of the SPA is static and don’t require custom data from a server we don’t need AJAX.

What is CORS?

CORS stands for Cross-Origin Resource Sharing. It allows you to make requests from one domain to another domain, which is normally prohibited by another policy called the Same-Origin Policy.

Loading images or scripts/styles always works, but AJAX calls to another server will fail, unless that server implements a way to allow the connection.

What is the difference between HTTP (short) polling and long polling?

Both are client asking server for updates periodically.

const fetchData = () =>
fetch('https://httpbin.org/ip')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err))
.finally(() => fetchData())

fetchData()

However, in long polling if the server does not have any information available for the client, then instead of sending an empty response, the server holds the request and waits for information to become available.

What is the main difference between Server Sent Events (SSE) and Websockets?

Server Sent Events are one-way only from the server to the browser and Websockets establish a two-way communication.

Socket.IO makes Websockets easy and fun.

What are Microservices?

It is an architectural style that structures an application as a collection of small independent services modeled around a business domain.

What is the main difference between Local Storage and Session Storage?

Data in localStorage doesn’t expire, whereas in sessionStorage is cleared when the page session ends, for example when the tab is closed.

sessionStorage.user = 'alice'
sessionStorage.password = '1234'

What is XHR?

XHR stands for XMLHttpRequest and allows you to fetch different types of data from the server. However, nowdays we have Fetch that is similar but provides a more powerful and flexible feature set.

What will happen if the browser executes the following command for the first time?

navigator.geolocation.getCurrentPosition(pos => {})

The first time it will request the user’s permission to enable querying the current GPS position of the device.

What is MVC?

MVC stands for Model (data) - View (front) - Controller (request and updates), a software design pattern used for developing user interfaces.

JavaScript

What is a callback?

A callback is a function that is executed after another function has finished.

What is the Event Loop?

The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into that queue. The JavaScript engine doesn’t start processing the event loop until the code after that async function has executed.

For a further better understanding I highly recommend you to watch: What the heck is the event loop anyway? by Philip Roberts.

How are parameters passed to functions?

It is always pass by value (copy), but for objects the value of the variable is a reference.

What is the different between the double equal and the triple equal?

The double comparation == is for equality and the triple one === is for equality and type.

How can we check if a variable is undefined?

a === undefined // and the same for null

How can you copy an object?

Shallow copy where all nested sub-objects are still copied as reference, so any change in those nested objects in objB will change objA.

const objB  = {...objA}

Deep copy where the two objects will be completely different even with nested sub-objects.

const objB = JSON.parse(JSON.stringify(objA))

How can you merge 2 objects?

We need to to analize keys and values and use recursion everytime we find a sub-object.

function merge(target, source) {
for (const key of Object.keys(source))
if (source[key] instanceof Object && key in target)
Object.assign(source[key], merge(target[key], source[key]))
Object.assign(target || {}, source)
return target
}

Recursion is the act of a function calling itself. Recursion is used to solve problems that contain smaller sub-problems. A recursive function can receive two inputs: a base case (ends recursion) or a recursive case (continues recursion).

What are Promises?

Objects that represent the eventual resolution or rejection of an asynchronous operation, and its resulting value.

const myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve('someData'), 1000)
})
myPromise.then(data => console.log(data))
console.log('appears first')

What is a callback hell?

It consists of multiple nested callbacks which makes code hard to read and debug.

const p1 = callback => setTimeout(() => callback(1), 1000)
const p2 = callback => setTimeout(() => callback(2), 100)
const p3 = callback => setTimeout(() => callback(3), 0)
p1(data1 => {
p2(data2 => {
p3(data3 => {
console.log(data1, data2, data3)
})
})
})

We can solve this with Promises:

const p1 = new Promise(ok => setTimeout(() => ok(1), 1000)) 
const p2 = new Promise(ok => setTimeout(() => ok(2), 100))
const p3 = new Promise(ok => setTimeout(() => ok(3), 0))
Promise.all([p1, p2, p3]).then(values => console.log(values))

What is a closure?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical enviroment). In other words, the function defined in the closure remembers the environment in which it was created.

const math = (() => {
let offset = 0 // state
return option => { // option for our basic counter
switch (option) {
case '+': offset++; break
case '-': offset--; break
default: offset = 0
}
console.log(offset)
}
})()
math('+')
math('-')

What is an IIFE?

IIFE stands for Immediately Invoked Function Expression, a function that runs as soon as is defined.

It prevents accessing variables within the IIFE as well as polluting the global scope.

What is the Module Design Pattern?

The Module Design Pattern is the most prevalently used design patterns for keeping particular pieces of code independent.

// talk.js
const talk = (() => {
function sayHello(user) {
return `Hello, ${user}!`
}
return {
sayHello
}
})()

Then we can access from any code that follows.

<script src="js/talk.js"></script>
<script>
document.body.innerHTML = talk.sayHello('Alice')
</script>

What are ES Modules?

ES Modules are files that can load each other and use special directives to interchange functionality.

export allows to export functionality outside the current module.

// talk.js
export function sayHello(user) {
return `Hello, ${user}!`
}

import allows to import functionality from other modules.

<script type="module">
import * as talk from 'js/talk.js'
document.body.innerHTML = talk.sayHello('Alice')
</script>

What will you expect in the following JavaScript operations?

[1, 2, 3] == [1, 2, 3]['10', '10', '10', '10'].map(parseInt)[101, 920, 4].sort()typeof [](() => {
return
{
name: 'Alice'
}
})()
const a = 1
(a + a).toString()

HTML

Which is the most basic structure of an HTML document?

<!DOCTYPE html>
<html>
<head></head>
<body></body>
</html>

What is the meaning of the following meta tag?

<meta charset="utf-8">

It indicates the character set that is used on a page.

What is the DOM?

It stands for Document Object Model and is an object-based representation of the HTML document. The HTML you write is parsed by the browser and turned into the DOM: objects, properties, methods and events.

The DOM is a standard for how to get, change, add, or delete HTML elements.

Which is the different between property and attribute?

A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.

What is the purpose of the beforeunload event?

It fires just before the user tries to navigate to another page or close the window.

onbeforeunload = e => {
e.preventDefault()
e.returnValue = '' // Chromium requires returnValue to be set
}

How can you trigger a change event manually?

document.querySelector('input').dispatchEvent(new Event('change'))

What do you use the <mark> element for?

It represents text which is marked or highlighted for reference or notation purposes.

Most <mark>erasmus</mark> are nocturnal

How can we use the FileReader object?

<input type="file" accept="image/*">
<img>
<script>
const $input = document.querySelector('input')
const $img = document.querySelector('img')
$input.onchange = () => {
const reader = new FileReader()
reader.onload = () => $img.src = reader.result
reader.readAsDataURL($input.files[0])
}
</script>

How can we add a placeholder text in an input element?

<input placeholder="name">

How can we add a process indicator?

<progress max="100" value="80"></progress>

What does the following HTML show?

<details>
<summary>Open Source</summary>
<p>To promote and protect open source software and communities</p>
</details>

It will show a collapsible element with the summary text and when we click on it the rest of the content will show.

What does the <canvas> element do?

It is an HTML element which can be used to draw graphics.

<canvas></canvas>

How can we make any element in the DOM editable?

<p contenteditable="true">To promote and protect open source software and communities</p>

How can we make the entire document editable?

document.designMode = 'on'

How can we check inputs with HTML?

We can use the pattern attribute to specify a regular expression but those inputs have to be located inside forms.

<form>
<input pattern="[0–9]{3}" required>
</form>

How to disable form validation?

<form novalidate>
<input pattern="[0–9]{3}" required>
</form>

What is the Constraint Validation API?

The Constraint Validation API enables custom validation rules and change the default error messages natively.

document.querySelector('input').setCustomValidity('Number with 3 digits')

How can we get the value of an input element as number without using JavaScript?

document.querySelector('input').valueAsNumber

What is the main difference between a <datalist> element and a <select> element?

The HTML <datalist> element is used to define autocompletion values as suggestions whereas the HTML <select> element asks the user to select a value from the available list.

<input list="ice-cream">
<datalist id="ice-cream">
<option value="Chocolate">
<option value="Strawberry">
<option value="Vanilla">
</datalist>
<select id="ice-cream">
<option value="Chocolate">Chocolate</option>
<option value="Strawberry">Strawberry</option>
<option value="Vanilla">Vanilla</option>
</select>

What is the difference between simple script, async and defer?

The HTML <script> element will stop the HTML parsing when it appears, until the JavaScript file in the attribute src finishes download and execution. That’s why a common practices is to set it at the bottom of <body>.

<script src="script.js"></script>

If we use the async (asynchronous) attribute, then the script will continue downloading in parallel with the rest of the HTML. However, the script will stop the HTML parsing for execution.

<script async src="script.js"></script>

If we use defer (deferred) attribute, the script will wait until the HTML parsing ends and only then it will be downloaded and executed.

<script defer src="script.js"></script>

However, if the script with defer is in the <head> it will be fetched asynchronously, and then its execution will be only after the HTML parsing is done.

CSS

What is the Box Model?

The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content.

What are the posible values of the position property?

static, relative, fixed , absolute and sticky.

HTML elements are positioned static by default. Static positioned elements are not affected by the top, bottom, left, and right properties, they are always positioned according to the normal flow of the page.

What are the different states of a link element?

unvistited, visited, hover and active.

Explain what elements will match each of the following CSS selectors:

  1. div, p - Selects all <div> and all <p>
  2. div p - Selects all <p> that are anywhere inside a <div>
  3. div > p - Selects all <p> where the immediate parent is a <div>
  4. div + p - Selects all <p> that are placed immediately after a <div>
  5. div ~ p - Selects all <p> that are anywhere preceded by a <div>

Which is the browser preference in case of conflicting declarations?

The browser checks the origin of the scripts then checks the inline scopes then checks the specificity and lastly it checks the order of the declaration rules.

What is CSS Grids and CSS Flexbox?

They are grid layout methods. CSS Flexbox works with one dimension, either a row or a colum. CSS Grid works with two dimensions, rows and columns at the same time.

How could you use CSS to add automatic numbering to heading titles?

:root {
counter-reset: heading;
}
h1::before {
content: counter(heading)') ';
counter-increment: heading;
}

What is the difference between rem and em?

They are CSS units, rem takes the value from the root whereas em takes it from the parent element.

What is the computed value of the margin in pixels?

body {
font-size: 14px;
}

div {
font-size: 1.5em;
margin: 1.5em;
}

It’s 14 * 1.5 * 1.5 = 31.5 px because the value of the margin is calculated after the value of the font-size.

What is Mobile-first?

It’s a concept in web design where an optimized version for mobile devices is created first and then expanded.

Explain the cascade, specificity and inheritance in CSS

The cascade means that the last rule will be used with identical selectors.

The specificity represents how specific is a selector, the more specific the better chance for a rule to be applied. Identical selectors carry the same specificity. The universal selector * and combinators >, +, ~ selectors have no effect on specificity.

Some CSS property values set on parent elements are inherited by their child elements if they don’t have cascaded value.

What represents : and :: in CSS?

One colon represents a special state of an element: :hover, :focus, :active, etc.

Double colons represents a specific part of the element: ::first-line, ::after, ::before, etc.

What is the difference between :nth-child and :nth-of-type?

We use :nth-of-type to target an element position among it’s siblings starting from 0 like we use :nth-child but also of the same type.

How can we fit the background image into a div?

We can achieve this with the background-size property.

To fit inside the div we can set it to contain and to cover it to cover.

How would you select every <a> element whose href attribute value ends with ".pdf"

a[href$=".pdf"]

How can you center content inside a page?

body {
display: grid;
justify-items: center;
}

How can you center content horizontaly and vertically?

body {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: grid;
justify-items: center;
align-items: center;
}

How can we select all input elements that are not of type radio or checkbox?

input:not([type=radio]):not([type=checkbox])

Keep in touch

Do you think every Web Developer should know the above answers? How many did you get? What do you ask to your candidates? What did you encounter in your interviews? Leave a comment to let us know!

And if you liked this article don’t forget to hand clapping (Flamenco style) and/or subscribe, cheers guys!

T-Shirts

★ Now you can have some of my coolest T-Shirts for programmers, check it out!

--

--

Génesis García Morilla
Génesis García Morilla

Written by Génesis García Morilla

We humans are really bad at math and logic, so I don't know what the hell are we doing programming...

No responses yet