Professional Documents
Culture Documents
va
Sc
rip
t.B
Book cover
A
Za
ra
@
Sold to
20
fernando93d@gmail.com
23
Ja
va
Sc
rip
t.B
A
The JavaScript
Interview
BIBLE
A Comprehensive Guide with 1000+
Essential Questions and Answers!
Throughout these pages, you'll find valuable tips and advice to help
you navigate the interview process with confidence. We hope that
by reading this book, you'll gain the skills and insights you need to
ace your next interview and secure the job you've been dreaming
of.
So, here's to you, the brave souls who keep pushing forward in the
face of adversity. We salute you and wish you all the best in your
interview journey.
Sincerely,
One of you!
Therefore, this book can serve as a helpful guide for the theoretical
part of an interview as one of the best and definitive sources of
information on JavaScript interview questions and answers. We have
done our best to provide the most useful and straightforward
answers to all of these questions, but readers also have the
freedom to use their own judgment and research to determine the
best answers for their specific situation.
I would like to thank my editor and the rest of the publishing team
for their hard work and dedication in bringing this book to fruition.
Var has function scope, while let and const have block scope.
Var and let can be re-assigned, while const cannot be re-
assigned. Additionally, const requires initialization at the time
of declaration.
The Map object allows you to store key-value pairs and can use
any value as a key, including objects and functions.
Both map and forEach are used to loop over an array, but map
returns a new array with transformed elements, while forEach
only executes a function on each element.
The Set object is used to store unique values of any type, and
provides methods for working with those values.
The pop method is used to remove and return the last element
of an array.
You can get the current date and time in JavaScript by creating
a new Date object with no arguments.
You can get the year of a Date object in JavaScript using the
getFullYear method.
You can get the month of a Date object in JavaScript using the
getMonth method, which returns a value from 0 (January) to
11 (December).
You can get the day of the month of a Date object in JavaScript
using the getDate method.
You can get the day of the week of a Date object in JavaScript
using the getDay method, which returns a value from 0
(Sunday) to 6 (Saturday).
You can get the hours of a Date object in JavaScript using the
getHours method.
You can set the year of a Date object in JavaScript using the
setFullYear method.
You can set the month of a Date object in JavaScript using the
setMonth method.
You can set the day of the month of a Date object in JavaScript
using the setDate method.
You can set the hours of a Date object in JavaScript using the
setHours method.
You can use the filter() method to filter elements from an array
in JavaScript. The method returns a new array that contains
only the elements that pass a test implemented by the
provided function. Example:
console.log(index); // Output: 1
You can use the shift() method to remove the first element of
an array in JavaScript. The method modifies the original array
and returns the removed element. Example:
You can use the push() method to add an element to the end
of an array in JavaScript. The method modifies the original
array and returns its new length. Example:
You can use the pop() method to remove the last element of
an array in JavaScript. The method modifies the original array
and returns the removed element. Example:
You can use the Math.max() method with the spread operator
to find the maximum value in an array in JavaScript. The
method returns the maximum value in the array. Example:
console.log(maxValue); // Output: 3
You can use the Math.min() method with the spread operator
to find the minimum value in an array in JavaScript. The
method returns the minimum value in the array. Example:
console.log(minValue); // Output: 1
console.log(person);
// Output: {name: "John", age: 30, city: "New York" }
function outerFunction() {
const name = "John";
function innerFunction() {
console.log(name);
}
return innerFunction;
}
function callbackFunction() {
console.log("This is a callback function");
}
higherOrderFunction(callbackFunction);
// Output: "This is a callback function"
// Output:
// "apple"
// "banana"
// "orange"
Example using a for...of loop:
// Output:
// "apple"
// "banana"
// "orange"
Example using the forEach() method:
array.forEach(function(item) {
console.log(item);
});
// Output:
// "apple"
// "banana"
// "orange"
promise.then(function(value) {
console.log(value); // Output: "Success!"
});
function displayResult(result) {
console.log(result);
}
if (true) {
var x = 5;
let y = 10;
}
console.log(x); // Output: 5
console.log(y); // Uncaught ReferenceError: y is not defined
getData()
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
try {
// Code that might throw an error
} catch (error) {
// Code to handle the error
console.log(error);
}
Example using catch():
promise.catch(function(error) {
// Code to handle the error
console.log(error);
});
try {
// Code that might throw an error
} catch (error) {
// Code to handle the error
console.log(error);
} finally {
// Code to be executed regardless of
// whether an error occurs or not
console.log("This code is always executed");
}
function outerFunction() {
const message = "Hello";
function innerFunction() {
console.log(message);
}
return innerFunction;
}
let y = null;
console.log(y); // Output: null
(function() {
const message = "Hello, world!";
console.log(message);
})();
undefined means a variable has been declared but has not yet
been assigned a value, while null is an assignment value that
represents no value or no object.
let x;
console.log(x); // Output: undefined
let y = null;
console.log(y); // Output: null
const handler = {
get: function(target, prop, receiver) {
console.log(`Getting the ${prop} property`);
return target[prop];
},
set: function(target, prop, value, receiver) {
console.log(`Setting the ${prop} property to ${value}`);
target[prop] = value;
return true;
}
};
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
There are many resources available online that can help you
learn more about Design Patterns in JavaScript, including
books, articles, tutorials, and online courses. Some popular
resources include "Design Patterns: Elements of Reusable
Object-Oriented Software" by Erich Gamma, Richard Helm,
Ralph Johnson, and John Vlissides, and "Learning JavaScript
Design Patterns" by Addy Osmani.
function isPalindrome(str) {
const reversed = str.split('').reverse().join('');
return str === reversed;
}
console.log(isPalindrome('racecar')); // true
console.log(isPalindrome('hello')); // false
// for loop
const array = [1, 2, 3];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
// forEach loop
array.forEach(item => console.log(item));
function fibonacci(num) {
const result = [0, 1];
return result;
}
console.log(fibonacci(5)); // [0, 1, 1, 2, 3, 5]
return -1;
}
function bubbleSort(arr) {
const n = arr.length;
return arr;
}
function mergeSort(arr) {
if (arr.length <= 1) {
return arr;
}
function factorial(num) {
if (num === 0) {
return 1;
} else {
return num * factorial(num - 1);
}
}
console.log(factorial(5)); // 120
class Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.push(item);
}
pop() {
return this.items.pop();
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
console.log(stack.pop()); // 3
console.log(stack.peek()); // 2
console.log(stack.isEmpty()); // false
console.log(stack.size()); // 2
class Queue {
constructor() {
this.items = [];
}
enqueue(item) {
this.items.push(item);
}
dequeue() {
return this.items.shift();
}
front() {
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
console.log(queue.dequeue()); // 1
console.log(queue.front()); // 2
console.log(queue.isEmpty()); // false
console.log(queue.size()); // 2
class HashTable {
constructor() {
this.storage = [];
this.storageLimit = 4;
}
hash(str, max) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash += str.charCodeAt(i);
}
return hash % max;
}
remove(key) {
const index = this.hash(key, this.storageLimit);
if (this.storage[index].length === 1
&& this.storage[index][0][0] === key) {
delete this.storage[index];
} else {
for (let i = 0; i < this.storage[index].length; i++) {
if (this.storage[index][i][0] === key) {
delete this.storage[index][i];
}
}
}
}
console.log(ht.retrieve('apple')); // 0.99
ht.remove('banana');
console.log(ht.retrieve('banana')); // undefined
class TrieNode {
constructor() {
this.children = {};
this.isEndOfWord = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(word) {
let current = this.root;
for (let i = 0; i < word.length; i++) {
const char = word[i];
if (!current.children[char]) {
current.children[char] = new TrieNode();
}
current = current.children[char];
}
current.isEndOfWord = true;
}
console.log(trie.search('apple')); // true
console.log(trie.search('app')); // false
function mergeSort(arr) {
if (arr.length <= 1) {
return arr;
}
const mid = Math.floor(arr.length / 2);
const left = arr.slice(0, mid);
const right = arr.slice(mid);
return merge(mergeSort(left), mergeSort(right));
}
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
}
const pivot = arr[arr.length - 1];
const left = [];
const right = [];
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
console.log(result);
//
{ score: 3,
comparative: 1,
tokens: [ 'i', 'love', 'javascript' ],
words: [ 'love' ],
positive: [ 'love' ],
negative: []
}
console.log(top5);
// Generate text
const generatedText = textModel.generate();
console.log(generatedText);
bot.dialog('/askName', [
(session) => {
bot.sendText(session, 'What is your name?');
},
(session, results) => {
const name = results.text;
bot.sendText(session, `Nice to meet you, ${name}!`);
session.endDialog();
},
]);
// Make predictions
const prediction = model.predict({ userId: 1, amount: 100,
location: 'New York' });
console.log(prediction);
console.log(predictions);
console.log(clusters);
console.log(result);
const tf = require('@tensorflow/tfjs');
// Make a prediction
const prediction = model.predict(imgTensor).
argMax(-1).dataSync();
console.log(prediction);
// Create a synth
const synth = new Synth().toDestination();
console.log(output1, output2);
console.log(result);
// Perform clustering
const kmeans = new KMeans();
const clusters = kmeans.cluster(data, { k: 2 });
console.log(clusters);
const ML = require('ml-regression');
console.log(output1, output2);
console.log(sentiment);
const tf = require('@tensorflow/tfjs-node-gpu');
const mobilenet = require('@tensorflow-models/mobilenet');
console.log(predictions);
console.log(forecast);
console.log(selected);
console.log(2 == [[[2]]]);
console.log(typeof null);
console.log(+'-0');
console.log([] == ![]);
console.log([] + []);
console.log(1 + 2 + "3");
console.log('2' - 1);
console.log([] == 0);
console.log('hello'.charAt(0));
console.log([] == ![]);
console.log(1 / 0);
console.log(+'10' + 5);
console.log('foo' + true);
console.log(typeof []);
const x = { a: 1 };
const y = { b: 2 };
const z = { ...x, ...y };
console.log(z);
console.log(3 + 4 + '5');
console.log(+'10' - 5);
console.log(typeof NaN);
console.log('2' + 2);
console.log('foo'.substring(1));
console.log('foo'.charAt(1));
console.log(typeof []);
// Using var
var x = 10;
// Using let
let y = 'hello';
// Using const
const z = true;
interface Person {
firstName: string;
lastName: string;
getSalary(): number {
return this.salary;
}
}
greet();
// Output: Hello, stranger!
To define a union type in TypeScript, you can use the pipe (|)
symbol between the types. Example:
class Person {
name: string;
age: number;
greet() {
console.log(`Hello, my name is ${this.name}
and I am ${this.age} years old.`);
}
}
promise.then((result) => {
console.log(result); // Output: Hello, world!
});
type Person = {
name: string,
age: number
};
greet() {
console.log(`Hello, my name is ${this.name}
and I am ${this.age} years old.`);
}
}
// Array of numbers
let nums1: Array<number> = [1, 2, 3];
let nums2: number[] = [1, 2, 3];
// Array of strings
let strs1: Array<string> = ["foo", "bar"];
let strs2: string[] = ["foo", "bar"];
interface Person {
name: string;
age?: number;
}
printValue("foo"); // FOO
printValue(3.14159); // 3.14
interface Person {
name: string;
age: number;
}
type Animal = {
name: string;
type: string;
}
class Person {
name: string;
age: number;
sayHello() {
console.log(`Hello, my name is ${this.name}
and I'm ${this.age} years old.`);
}
}
class Person {
readonly name: string;
age: number;
interface Dictionary {
[key: string]: number;
}
const myDictionary: Dictionary = { a: 1, b: 2, c: 3 };
interface Person {
name: string;
age: number;
}
interface Person {
name: string;
age: number;
}
namespace MyNamespace {
export const myVar = "hello";
export function myFunc() {
console.log("world");
}
}
return descriptor;
}
class MyClass {
@log
myMethod(arg1: string, arg2: number) {
console.log(`Hello, ${arg1} (${arg2})`);
return "done";
}
}
interface Person {
name: string;
age: number;
email: string;
}
You can download and install Node.js from the official website
(https://nodejs.org/). Alternatively, you can use a package
manager like npm or yarn to install Node.js.
You can use the util module to work with utilities in Node.js.
For example:
You can use the process object to access information about the
current Node.js process. For example:
console.log(`PID: ${process.pid}`);
console.log(`Platform: ${process.platform}`);
console.log(`Memory usage: ${process.memoryUsage()}`);
try {
// Code that may throw an error
} catch (error) {
// Handle the error
}
You can create a server in Node.js using the http module. For
example:
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
You can use the http or https module to send HTTP requests in
Node.js. For example:
const fs = require('fs');
const readStream = fs.createReadStream('/path/to/file');
const writeStream = fs.createWriteStream('/path/to/other/file');
readStream.pipe(writeStream);
app.listen(3000, () => {
console.log('Server started on port 3000');
});
connection.connect();
socket.on('close', () => {
console.log('Client disconnected');
});
});
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
const os = require('os');
console.log(`Hostname: ${os.hostname()}`);
console.log(`Free memory: ${os.freemem()}`);
console.log(`CPU info: ${os.cpus()}`);
console.log(`Hash: ${hash}`);
You can use the stream module to work with streams of data in
Node.js. For example:
const fs = require('fs');
const stream = fs.createReadStream('file.txt',
{ highWaterMark: 16 });
stream.on('end', () => {
console.log('Finished reading file');
});
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
https.createServer(options, app).listen(443);
app.use(express.static('public'));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
To run a Deno script, you can use the deno run command. For
example:
To use async/await in Deno, you can use the async and await
keywords. For example:
To create a server in Deno, you can use the serve method from
the deno namespace. For example:
To write a Deno test, you can use the Deno.test method. For
example:
FROM hayd/deno:latest
WORKDIR /app
COPY . .
await client.connect();
await client.end();
React hooks are a way to use state and other React features in
functional components, which were previously limited to only
using props. They work by allowing developers to use stateful
logic and lifecycle methods in functional components through
the use of special functions such as useState, useEffect, and
useContext.
State and props are both used to manage data in React, but
they have different roles and use cases. State is used to
manage internal component data that can change over time,
while props are used to pass data from a parent component to
a child component. It is important to use state when the data
needs to be managed within the component and use props
when passing data between components.
Redux and the React context API are both used for managing
application state, but they have different use cases and
tradeoffs. Redux is a standalone library that provides a
centralized store for managing state, while the React context
API is a built-in feature of React that allows for sharing data
between components. Redux is more suitable for larger and
more complex applications, while the React context API is
better suited for smaller and simpler applications.
// Example of a service
app.service('UserService', function() {
this.getUser = function() {
return { name: 'John', age: 25 };
};
});
// Example of a factory
app.factory('UserFactory', function() {
var user = { name: 'John', age: 25 };
return {
getUser: function() {
return user;
}
};
});
deferred.promise.then(function(result) {
// Handle successful promise
console.log(result);
}).catch(function(error) {
// Handle error promise
console.error(error);
});
});
{{#if this.isSuccess}}
<p>Success!</p>
{{else}}
<p>{{this.errorMessage}}</p>
{{/if}}
addItem(item) {
this.items.push(item);
}
removeItem(item) {
const index = this.items.indexOf(item);
if (index !== -1) {
this.items.splice(index, 1);
}
}
}
@action
increment() {
this.count++;
}
@action
decrement() {
this.count--;
}
}
@computed('firstName', 'lastName')
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
And in the child components template, you can use the {{on}}
helper to bind the onClick action to a
click event like this:
<button {{on "click" this.onClick}}>Click me</button>
addItem(item) {
this.items.push(item);
}
removeItem(item) {
const index = this.items.indexOf(item);
if (index !== -1) {
this.items.splice(index, 1);
}
}
}
addItemToCart(item) {
this.cart.addItem(item);
}
removeItemFromCart(item) {
this.cart.removeItem(item);
}
}
// Update a document
MyCollection.update(
{ _id: 'abc123' },
{ $set: { name: 'Jane Doe' } }
);
// Remove a document
MyCollection.remove({ _id: 'abc123' });
// Subscribe to data
Meteor.subscribe('mydata');
To use a Meteor.js template in your HTML, you can use the {{>
mytemplate}} syntax. For example:
// Handle an event
Template.mytemplate.events({
'click .mybutton': function(event, template) {
// Do something
}
});
To call a Meteor.js method from the client, you can use the
Meteor.call method. For example:
// Call a method
Meteor.call('mymethod');
To call a Meteor.js method from the server, you can use the
Meteor.call method. For example:
// Call a method
Meteor.call('mymethod', function(error, result) {
// Handle the result
});
// Define a route
Router.route('/myroute', function() {
this.render('mytemplate');
});
// Handle a route
WebApp.connectHandlers.use('/myroute', function(req, res, next) {
// Do something
});
You can bind data to an input field in Svelte using the bind
directive. This directive automatically updates the value of the
bound data whenever the input field changes.
<script>
let message = 'Hello, world!';
</script>
<script>
let message = 'Hello, world!';
function handleClick() {
message = 'Button clicked';
}
</script>
<script>
let show = true;
</script>
{#if show}
<p>Hello, world!</p>
{/if}
You can create a loop in Svelte using the each block. This block
allows you to iterate over an array and render HTML for each
item in the array.
<script>
let items = ['Apple', 'Banana', 'Cherry'];
</script>
<ul>
{#each items as item}
<li>{item}</li>
{/each}
</ul>
<p>Hello, {name}!</p>
function increment() {
counter.update(n => n + 1);
}
</script>
<button on:click={increment}>Increment</button>
<p>Count: {$counter}</p><!-- Display.svelte -->
<script>
import { counter } from './store.js';
</script>
<script>
import { slide } from './transitions.js';
</script>
return {
delay,
duration,
css: t => `transform: translateY(${(1 - t) *
offsetY}px); opacity: ${t};`
};
}
<script>
export let message = 'Hello, world!';
</script>
<style>
p {
color: red;
}
</style>
<p>{message}</p>
library.fetch({
success: function() {
// code to handle the successful fetch
},
error: function() {
// code to handle the error
}
});
book.save({
success: function() {
// code to handle the successful save
},
error: function() {
// code to handle the error
}
});
The fetch() method retrieves data from the server and updates
the model's attributes with the response, while the save()
method sends updated attribute values to the server to be
persisted.
view.on('change', myFunction);
view.off('change', myFunction);
myModel.trigger('customEvent');
myCollection.on('reset', function() {
console.log('Collection was reset');
});
fullName.dispose();
myObservable.subscribe(function(newValue) {
console.log('The new value is ' + newValue);
});
ko.bindingHandlers.myBinding = {
init: function(element, valueAccessor) {
// Initialization logic here
},
update: function(element, valueAccessor) {
// Update logic here
}
};
function ViewModel() {
this.handleClick = function() {
alert('Button clicked!');
}
}
ko.applyBindings(new ViewModel());
ko.applyBindings(new ViewModel());
function ViewModel() {
this.message = 'Hello world!';
}
ko.applyBindings(new ViewModel());
ko.applyBindings(new ViewModel());
ko.bindingProvider.instance.preprocessNode = function(node) {
if (node.nodeType === 1 && node.getAttribute('data-bind')
.indexOf('if') !== -1) {
node.removeAttribute('data-bind');
}
return node;
};
firstName('Jane');
ko.utils.arrayForEach(items(), function(item) {
item.subscribe(function(newValue) {
console.log(item() + ' changed to ' + newValue);
});
});
var viewModel = {
person: {
firstName: ko.observable('John'),
lastName: ko.observable('Doe')
}
};
Polymer({
is: 'my-element',
properties: {
name: {
type: String,
value: 'World'
}
},
ready: function() {
console.log('Hello, ' + this.name + '!');
}
});
To use a custom element in HTML, you can use its tag name.
For example:
<my-element></my-element>
<my-element name="{{username}}"></my-element>
Polymer({
is: 'my-element',
properties: {
firstName: {
type: String,
value: 'John'
},
lastName: {
type: String,
value: 'Doe'
}
},
computed: {
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
}
});
To use events in Polymer.js, you can use the on-* syntax. For
example:
<my-element on-click="handleClick"></my-element>Polymer({
is: 'my-element',
handleClick: function() {
console.log('Element clicked');
}
});
<dom-module id="my-element">
<template>
<p>First name: {{firstName}}</p>
<p>Last name: {{lastName}}</p>
<p>Full name: {{fullName}}</p>
</template>
<script>
Polymer({
is: 'my-element',
properties: {
firstName: String,
lastName: String,
fullName: {
type: String,
value: '',
notify: true
}
},
<iron-form>
<form>
<input name="username" type="text">
<input name="password" type="password">
<button type="submit">Submit</button>
</form>
</iron-form>
<iron-ajax
auto
url="https://api.example.com/data"
handle-as="json"
on-response="handleResponse"
></iron-ajax>Polymer({
is: 'my-element',
handleResponse: function(response) {
console.log(response.detail.response);
}
});
<script>
const MyBehavior = {
properties: {
myProperty: {
type: String,
value: "default value"
}
}
};
Polymer({
is: "my-element",
behaviors: [MyBehavior],
ready() {
console.log(this.myProperty);
}
});
</script>
<dom-module id="my-element">
<template>
<p>First name: {{firstName}}</p>
<p>Last name: {{lastName}}</p>
<p>Full name: {{fullName}}</p>
</template>
<script>
Polymer({
is: 'my-element',
properties: {
firstName: String,
lastName: String
},
computed: {
fullName: '_computeFullName(firstName, lastName)'
},
<dom-module id="my-element">
<template>
<p>Name: {{name}}</p>
</template>
<script>
Polymer({
is: 'my-element',
properties: {
name: String
}
});
</script>
</dom-module>
To listen for events in Mithril, you use the oncreate hook and
provide a callback function that sets up event listeners.
To use animations in Mithril, you define CSS styles and use the
m.route.animate() method to specify the animation.
Riot.js uses two-way data binding to keep the view and model
in sync.
Riot.js uses a custom event system that allows you to listen for
and trigger events on a tag.
To listen for events in Riot.js, you use the on() method and
provide the name of the event and a callback function.
To use the each loop in Riot.js, you use the data attribute and
provide a reference to an array or object and a callback
function that defines how to render each item.
Alpine.js may not be the best choice for very large or complex
projects, as it is designed to be lightweight and easy to use.
You can create a loop in Alpine.js using the x-for directive. This
directive allows you to iterate over an array and render HTML
for each item in the array.
She was too reserved and didn't like to try new things - like
async/await.
A VanillajavaScript!
They didn't like being told to "just kick it" without any context.
A lost cause.
A Nodejitter!