Interview Questions Flashcards

1
Q

What is JavaScript?

A

JavaScript is a client-side/server-side programming language that can be inserted into otherwise static HTML pages to add page interactivity and enable user engagement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is hoisting in JavaScript?

A

Hoisting means all the declarations are moved to the top of the scope before the code is run.

For functions, this means you can call them from anywhere in the scope, even before they are defined.

For variables, hoisting is a bit different. It assigns undefined to them at the top of the scope.

Calling a variable before defining:

console.log(dog);
var dog = "Spot";
Output:undefined

If you declare a function or variable, it is always moved on the top of the scope no matter where you declare it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does the isNan() function do?

A

You can use isNan() function to check if the type of a value is a number and it’s NaN. Returns true/false.

(And yes, NaN is of type number even though it’s a “Not-a-Number” by name. This is because it’s a numeric type under the hood, even though it does not have a numeric value.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is negative infinity in JavaScript?

A

You get a negative infinity if you divide a negative number with zero in JavaScript.

For instance:
console.log(-10/0)
Output:
-Infinity

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is an undeclared variable?

How about an undefined variable?

A

Undeclared variables do not exist in a program at all.

Undefined variables are declared in the program but don’t have a value. If the program tries to read an undefined variable, an undefined value is returned and the app does not crash.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What types of popup boxes are there in JavaScript?

A

The three types of popups are alert, confirm, and prompt. Let’s see an example use of each:
Alert
window.alert(“Hello, world!”);

Confirm
if (window.confirm("Are you sure you want to go?")) {
  window.open("exit.html", "See you again!");}
Prompt
let person = window.prompt("Enter your name");
if (person != null) {
  console.log('Hello', person);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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

A
== compares values
=== compares both the value and the type
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does implicit type coercion do? Give an example.

A

Implicit type coercion means a value is converted from one type to another under the hood. This takes place when the operands of expressions are of different types.

For example, string coercion means applying + operator on a number and a string converts the number into a string automatically. For example:
var x = 1; var y = “2”;
x + y // Returns “12”
But when dealing with subtraction, the coercion works the other way. It converts a string into a number. For instance:
var x = 10; var y = “10”;
x - y // Returns 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Is JavaScript statically or dynamically typed language? What does this mean?

A

JavaScript is dynamically typed.

This means the type of objects is checked during run-time. (In a statically typed language, the type is checked during compile-time.)

In other words, JavaScript variables are not associated with a type. This means you can change the data type with no problem.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is NaN in JavaScript?

A

NaN means “Not-a-Number”. This means a value that is not officially a number in JavaScript.
What may be confusing is that type-checking NaN with typeof() function results in Number.

console.log(typeof(NaN))
Output: Number

To avoid confusion, use isNaN() to check if the type of a value is NaN or not number.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the spread operator in JavaScript?

A

Spread operator allows iterables ( arrays / objects / strings ) to be expanded into single arguments/elements.

function sum(a, b, c) {
  return a + b + c;
}
const nums = [15, 25, 35];

console.log(sum(…nums));
Output: 75

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a closure in JavaScript?

A

A closure in JavaScript means an inner function has access to the variables of the outer function—even after the outer function has returned.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to handle exceptions in JavaScript?

A

If an expression throws errors, you can handle them with the try…catch statement.

The idea of using this structure is to try running an expression, such as a function with an input, and catch the possible errors.

function weekDay(dayNum) {
  if (dayNum < 1 || dayNum > 7) {
    throw 'InvalidDayNumber'
  } else {
    return ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][dayNum - 1];
  }
}
try { // Try to run the following
  let day = weekDay(8);
  console.log(day);
}
catch (e) { // catch an error if the above try failed
  let day = 'unknown';
  console.log(e);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What Is web storage?

A

Web storage is an API that provides a way for browsers to store key-value pairs to the user’s browser locally. Using web storage makes this process way more intuitive than using cookies.

Web storage provides two ways for storing data:

Local storage — stores data for the client without an expiration date.
Session storage — stores data for only one session. The data is gone when the browser is closed.
// Save data to sessionStorage
sessionStorage.setItem(‘favoriteColor’, ‘gray’);
// Get the color from the sessionStorage
let data = sessionStorage.getItem(‘favoriteColor’);
console.log(data);
// Remove saved color preset from sessionStorage
sessionStorage.removeItem(‘favoriteColor’);
// Remove ALL the saved data from sessionStorage
sessionStorage.clear();
And here’s how you can do the same using the localStorage:

// Save data to localStorage
localStorage.setItem(‘favoriteColor’, ‘gray’);
// Get the color from the localStorage
let data = localStorage.getItem(‘favoriteColor’);
console.log(data);
// Remove saved color preset from localStorage
localStorage.removeItem(‘favoriteColor’);
// Remove ALL the saved data from localStorage
localStorage.clear();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Why do you need web storage?

A

Web storage makes it possible to store large amounts of data locally without affecting the performance of a website.

This information is not stored in a server, making it a more preferable approach compared to cookies.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are modules?

A

Modules are units of reusable code. Usually, you can import a useful function or constructor to your project from the module.

Importing features from modules could look like this:

import { hello } from ‘./modules/helloWorld.js’;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is meant by “scope” in JavaScript?

A

Scope describes where variables, functions, and other objects are accessible in the code. Scopes are created in your code during the runtime.

For example, a block scope means the “area” between curly braces:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are higher-order functions in JavaScript?

A

A higher-order function operates on another function(s). It either takes a function as an argument or returns another function.

function runThis(inputFunction) {
  inputFunction();}

runThis(function() { console.log(“Hello world”) });
Output: Hello world

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the “this” keyword in JavaScript?

A
This refers to the object itself.
var student = { name:  "Matt",
    getName: function(){
      console.log(this.name); } }

student.getName();
Output: Matt

To make the getName() method work in the student object, the object has to access its own properties. This is possible via this keyword inside the object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What does the .call() method do?

A
The call() method can be used to call a method of an object on another object.
The call() can also accept arguments.

obj1.func.call(obj2)

var student = {
  name: "Matt",
  getName: function(){
    console.log(this.name); } }

var anotherStudent = {
name: “Sophie”};
student.getName.call(anotherStudent);
Output: Sofie

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the apply() method?

A

The apply() method does the same as the call() method. The difference is that apply() method accepts the arguments as an array.

const person = { name: ‘John’ }
function greet(greeting, message) {
return ${greeting} ${this.name}. ${message};}
let result = greet.apply(person, [‘Hello’, ‘How are you?’]);
console.log(result);
Output: Hello John. How are you?
In the line:
let result = greet.apply(person, [‘Hello’, ‘How are you?’]);
‘Hello’ is assigned to greeting and ‘How are you?’ is assigned to message in the greet() function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the bind() method?

A

The bind() method returns a new function whose this has been set to another object.

Unlike apply() and call(), the bind() does not execute the function immediately. Instead, it returns a new version of the function whose this is set to another value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is currying?

A

Currying means transforming a function with n arguments, to n functions of one or fewer arguments.
For example, say you have a function add() that sums up two numbers:

function add(a, b) {
    return a + b;}
You can call this function by: add(2,3)
Let’s then curry the function:
function add(a) {
  return function(b) {
    return a + b;}}
Now you can call this curried function by:
add(2)(3)
Currying does not change the behavior of a function. It changes the way it’s invoked.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is a promise in JavaScript?

A

A promise is an object that may produce value in the future. A promise is always in one of the possible states: fulfilled, rejected, or pending.

const promise = new Promise(function(resolve, reject) {
    // implement the promise here
})
For example, let’s create a promise that’s resolved two seconds after being called.
const promise = new Promise(resolve => {
  setTimeout(() => {
    resolve("Hello, world!");
  }, 2000);
}, reject => {});
Now the key of promises is you can execute code right after the promise is resolved by using the .then() method:

promise.then(result => console.log(result));
Output: Hello, world!
Promises can be chained together such that a resolved promise returns a new promise.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Why use promises?

A

In JavaScript, promises are useful with async operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is a callback function in JavaScript?

A

A callback function is a function that is passed as an argument to another function. This function is executed inside the function to which it’s passed as to “call back” when some action has been completed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Why use callbacks in JavaScript?

A

The callbacks are useful because JavaScript is an event-driven language. In other words, instead of waiting for a response, it keeps executing while listening for other events.

function greetName(name) {
  console.log('Hello ' + name);}
function askName(callback) {
  let name = prompt('Enter your name.');
  callback(name);}

askName(greetName);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is a strict mode in JavaScript?

A

Strict mode allows your program to operate in a strict context, preventing certain actions from being taken. Also, more exceptions are thrown.
The expression “use strict”; tells the browser to enable the strict mode.
For example:
“use strict”;
number = 1000;
This causes an error because strict mode prevents you from assigning a value to an undeclared variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is an Immediately Invoked Function?

A
An Immediately Invoked Function (IIFE) runs right after being defined.
For example:
(function(){ 
  // action here
})();
To understand how an IIFE works, look at the parenthesis around it:
When JavaScript sees the keyword function, it assumes there’s a function declaration coming.
But the declaration above is invalid because the function does not have a name.
To fix this, the first set of parenthesis around the declaration is used. This tells the interpreter that it’s a function expression, not a declaration.
(function (){
   // action here;
})
Then, to call the function, another set of parenthesis needs to be added at the end of the function declaration. This is similar to calling any other function:
(function (){
  // action here
})();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is a cookie?

A

A cookie is a small data packet stored on your computer. A website can place cookies on visitors’ browsers to remember login credentials.
Basically, cookies are text files with key-value pairs that you can create, read, or delete cookies, using the document.cookie property.

For example, let’s create a cookie that saves the username:
document.cookie = “username=foobar123”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Why use strict mode in JavaScript?

A

Strict mode helps write “secure” JavaScript code. This means bad syntax practices are converted into real errors.
For example, strict mode prevents creating global variables.
To declare strict mode, add ‘use strict’; statement before the statements which you want to be under strict mode:
‘use strict’;
const sentence = “Hello, this is very strict”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What does double exclamation do?

A
The double exclamation converts anything to boolean in JavaScript.
!!true    // true
!!2       // true
!![]      // true
!!"Test"  // true
!!false   // false
!!0       // false
!!""      // false
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

How can you delete a property and its value from an object?

A

You can use the delete keyword to delete the property and its value from an object.

var student = {name: "John", age:20};
delete student.age;
console.log(student);
Output: {name: "John"}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

How can you check the type of a variable in JavaScript?

A

Use the typeof operator.

typeof “John Abraham” // Returns “string”
typeof 100 // Returns “number”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is null in JavaScript?

A

null represents the absence of value. It highlights that a variable points to no object.

The type of null is an object:

var name = null;

console. log(typeof(name))
returns: object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Null vs undefined?

A

Null
Represents the absence of a value of a variable.
Value that indicates the variable points to no object.
Is of type object.
Represents null, empty, or non-existent reference.
Converts to 0 with primitive operations.

Undefined
Represents the absence of the variable.
A variable that has been declared but doesn’t have a value
Is of type undefined.
Converts to NaN with primitive operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Can you access history in JavaScript?

A

You can access history via window.history that contains the browser’s history.

To retrieve the previous and next URLs, use these methods:

window. history.back();
window. history.forward();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What is a global variable?

A

A global variable is available everywhere in the code.
To create a global variable, omit the var keyword:

x = 100; // Creates a global variable.

Also, if you create a variable using var outside any functions, you create a global variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Does JavaScript relate to Java?

A

They are two different programming languages that have nothing to do with one another.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What are JavaScript events?

A

Events are what happens to HTML elements. When JavaScript is used in an HTML page, it can react to the events, such as a button click.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What does the preventDefault() method do?

A

It prevents the event from taking the default behavior.

42
Q

What is the setTimeout() method?

A

The setTimeout() method calls a function (once) after a specified number of milliseconds. For example, let’s log a message after one second (1000ms):

setTimeout(function() {
console.log(“Good day”);
}, 1000);

43
Q

What is the setInterval() method?

A

The setInterval() method calls a function periodically with a custom interval.

For example, let’s periodically log a message every second:

setInterval(function() {
console.log(“Good day”);
}, 1000);

44
Q

What is ECMAScript?

A

ECMAScript is the scripting language that forms the basis of JavaScript.

ECMAScript is standardized by the ECMA International standards organization (check out ECMA-262 and ECMA-402 specifications).

45
Q

What is JSON?

A
JSON (JavaScript Object Notation) is a lightweight data format used to exchange data.
The syntax rules for JSON are:
The data is in key-value pairs.
The data is separated by commas.
Curly braces define an object.
Square brackets define an array.
46
Q

Where is JSON used?

A

When sending data to a server and vice versa, the data must be in a text format.

JSON is a text-only format that allows sending data to the server and data from the server to a browser. JSON is supported by nearly all programming languages so it can be used with other languages too.

47
Q

Why use JSON stringify?

A

When you send data to a server, it has to be a string.

To convert a JavaScript object into a string, you can use the JSON.stringify() method.

var dataJSON = {name: "Matt", age: 51};
var dataString = JSON.stringify(dataJSON);
console.log(dataString);
Output:
'{"name":"Matt","age":51}'
48
Q

How can you convert JSON string to a JSON object?

A

When you receive data from a server, it’s always in a string format. To convert a JSON string to a JavaScript object, use the JSON.parse() method.

var data = '{"name":"Matt", "age":51}';
var dataJSON = JSON.parse(data);
console.log(dataJSON);
Output:
{ name:"Matt",
    age:51 }
49
Q

How can you assign a default value to a variable?

A

Use a logical operator || in the assignment to provide a default value.

const a = b || c;
This works such that if b is falsy then c is going to be assigned to a. (Falsy means null, false, undefined, 0, empty string, or NaN.)
50
Q

Can you define properties for a function?

A

Yes, because functions are also objects.

let func = function(x) {  
};
func.property1 = "Hello there";
console.log(func.property1);
Output:
Hello there
51
Q

What is the meaning of a race method in promises?

A

Promise.race() method returns the promise which is resolved or rejected first.

52
Q

What does promise.all() method do?

A

Promise.all is a promise that takes an array of promises as input. It gets resolved when:
Either all the input promises get resolved.
Or any one of them gets rejected.
For instance, promise.all waits for all these three promises to complete:
var prom1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(“Yay!”);
}, 1000); });
var prom2 = Promise.resolve(10);
var prom3 = 100;
Promise.all([prom1, prom2, prom3]).then(values => {
console.log(values); });
Output after one second has passed:
[“Yay”, 10, 100]

53
Q

What is the eval() function?

A

The eval() function evaluates code inside a string. The string to be evaluated can be an expression, variable, statement, or sequence of statements.

For example:
console.log(eval(“5+10”));
Output: 15

54
Q

What is event bubbling?

A

In event bubbling an event starts by running the event handlers on the innermost element. Then it triggers the parents’ event handlers until it reaches the outermost element.

The best way to see this in action is by creating an HTML document with divs inside of divs.
In each div, there’s a JavaScript alert that’s triggered when one clicks the div.
If you click the Inner layer, it triggers the alert assigned to that div, and it triggers the alerts of the parent divs.

55
Q

What is the Temporal Dead Zone?

A

Temporal Dead Zone means unreachability of a variable, even though it’s already in the scope.

56
Q

What is URI?

A

A URI or Uniform Resource Identifier is a set of characters that distinguish resources from one another. URIs allow internet protocols to perform the actions between resources.

A URI can look something like this:

hello://example.com:8042/there?name=jack#sumthing

57
Q

What is the DOM?

A

When a web page has loaded, the browser creates a DOM for the page. This gives JavaScript the power to create dynamic HTML.

DOM or Document Object Model acts as an API for HTML documents. It defines the structure of the documents. It also specifies how the document is accessed and modified.

58
Q

Document load vs DOMContentLoaded?

A

The DOMContentLoaded event is triggered when the HTML document has been loaded and parsed. It does not wait for the assets (such as stylesheets and images).
The document load event triggers only after the full page has loaded, including all the assets.
For example, here’s how you can use DOMContentLoaded to notify when the DOM has fully loaded:
window.addEventListener(‘DOMContentLoaded’, (event) => {
console.log(‘DOM is now loaded!’); });
And here’s an example of how you can add a listener for when a specific page has loaded:

window. addEventListener(‘load’, (event) => {
console. log(‘The page is now loaded!’); });

59
Q

HTML Attribute vs DOM Property?

A

When you write HTML you can define attributes on the HTML elements. Then, when you open the page with a browser, your HTML code is parsed. At this point, a DOM node is created. This DOM node corresponds to the HTML document you’ve just written. This DOM node is an object that has properties.

For instance, this HTML element:

has three attributes, id, type, and value.

When the browser parses this HTML element:
It takes this input field and bakes an HTMLInputElement object from it.
This object has dozens of properties such as accept, accesKey, align.
It also has some of the original HTML attributes turned into properties, such as the id and the type. But for example, the value property does not refer to the value attribute.

60
Q

What is the same-origin policy?

A

The same-origin policy is a valuable security mechanism. It prevents JavaScript from making requests over the domain boundaries.

An origin refers to the URI scheme, hostname, and port number. The same-origin policy makes it impossible for a script on one page from obtaining access to sensitive data on another.

61
Q

Is JavaScript a compiled or interpreted language?

A

JavaScript is an interpreted language.

An interpreter in the browser reads the JavaScript code, interprets each line, and runs it.

62
Q

Is JavaScript a case-sensitive language?

A

JavaScript is a case-sensitive language.

The keywords, variables, function names, and so on need to be capitalized consistently.

63
Q

How many threads are there in JavaScript?

A

JavaScript works with a single thread. It does not allow to write code that the interpreter could run in parallel in multiple threads or processes.

This means it executes code in order and must finish executing a piece of code before moving to the next one.

A good example of seeing this in action is when you show an alert on a web page. Once the alert pops up, you cannot interact with the page until the alert is closed.

alert(“Hello there!”);

64
Q

What does the “break” statement do?

A

The break statement jumps out of a loop and continues executing the code outside of the loop.

For example, this loop terminates after it encounters a number 5:

for (var i = 0; i < 100; i++) {
  if (i === 5) {
    break;}
  console.log('Number is ', i);}
console.log('Yay');
65
Q

What does the “continue” statement do?

A
The continue statement jumps over one round of a loop.
For example, this loop skips numbers 2 and 3:
for (var i = 0; i < 5; i++) {
  if (i === 2 || i === 3) {
    continue; }
  console.log('Number is ', i); }
Output:
0
1
4
66
Q

What is a regular expression?

A

A regular expression, also known as regex or regexp, is a group of characters that form a search pattern. It’s a pattern-matching tool that is commonly used in JavaScript and other programming languages.

For example, let’s find any numbers from a string using a regular expression:
var regex = /\d+/g;
var string = “You have 100 seconds time to run”;
var matches = string.match(regex);
console.log(matches);
Output is an array of all the matches:
[100]

67
Q

What is the purpose of a breakpoint when debugging code?

A

Breakpoints allow you to find bugs in your JavaScript code.

You can set breakpoints in your code when a debugger statement is executed and the debugger window appears.

At a breakpoint, JavaScript stops executing and lets you inspect the values and the scope to solve possible issues.

68
Q

What is a conditional operator?

A

A conditional operator is a shorthand for writing if-else statements. A conditional operator is sometimes known as a ternary operator.

69
Q

Can you chain conditional operators?

A
function example() {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}
// Shorthand for the above function
function example() {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}
70
Q

What does the freeze() method do?

A

The freeze() method freezes an object. It makes an object immutable.

After freezing an object, it’s not possible to add new properties to it.

For example:

const item = { name: "test" };
Object.freeze(item);
item.name = "Something else"; // Error
71
Q

How can you get the list of keys of an object?

A
Use the Object.keys() method.
const student = {
  name: 'Mike',
  gender: 'male',
  age: 23 };
console.log(Object.keys(student));

Output: [“name”, “gender”, “age”]

72
Q

What are JavaScript’s primitive data types?

A
A primitive data type has a primitive value. There are seven different primitive data types in JavaScript:
string— words. For example “John”.
number — numeric values. For example 12.
boolean — true or false. For example true.
null — absence of a value. For example let x = null;
undefined —type where a variable is declared but does not have a value. For example, when creating variable x this way let x; , x becomes undefined.
bigint — An object meant to represent whole numbers greater than 2^53–1. For example BigInt(121031393454720292)
symbol — A built-in object for creating unique symbols. For example let sym1 = Symbol(‘test’)
73
Q

What ways are there to access properties of an object?

A

There are three ways to access properties.

The dot notation.
For example: obj.property

The square brackets notation.
For example: obj[“property”]

The expression notation.
For example: obj[expression]

74
Q

How to execute JavaScript code after the page has loaded?

A

There are three ways you can do this:
Set the property window.onload as a function that executes after the page loads:
window.onload = function …

Set the property document.onload as a function that executes after the page loads:
document.onload = function …

Set the onload property of an HTML attribute as a JS function:

75
Q

What is an error object?

A

An error object is a built-in object that gives you detailed error info if an error happens to occur.
The error object has two properties: name, message
For example, let’s assume that the sayHi() function throws an error. When this happens, the catch block gives you an error object you can print to the console for example.

  sayHi("Welcome");
}
catch(error) {
  console.log(error.name + "\n" + error.message);
}
76
Q

What does the NoScript tag do?

A

Noscript tag is for detecting and reacting to browsers that have JavaScript disabled.

You can use the NoScript tag to execute a piece of code that notifies the user.

For example, your HTML page can have a noscript tag like this:

document.write(“Hello World!”);

Your browser does not support JavaScript!

77
Q

What is an entry controlled loop?

A

In an entry-controlled loop, the condition is tested before entering the body of the loop.

For example, for loops and while loops fall into this category:

let nums = [1,2,3];
for (let num of nums) {
console.log(num);
}

78
Q

What is an exit controlled loop?

A

In an exit controlled loop, a condition is evaluated at the end of the loop. This means the loop body executes at least once regardless of whether the condition was true or false.

For example, the do-while loop falls into this category:
const i = 0;
do {
  console.log('The number is', i);
} while (i !== 0);
Output: The number is 0
79
Q

What is an anonymous function?

A
An anonymous function is a function that does not have a name.
Anonymous functions are commonly assigned to a variable name or used as a callback function.
Here is a function with a name for a reference:
function example(params) {
    // do something}
Here is an anonymous function that’s assigned to a variable:
const myFunction = function() {
    // do something };
And here’s an anonymous function used as a callback:
[1, 2, 3].map(function(element) { 
     // do something });
80
Q

What is an iterator?

A

The iterator protocol makes it possible for an object to generate a sequence of values.

The iterator must implement the next() method for getting the next value in the sequence. This method returns an object with

value— The next value in the iteration sequence
done—If this value is the last in the sequence, this is true. If not, then it’s false.

81
Q

What is an iterable?

A

The iterable protocol means that an object can be iterated over, and thus implements the iterator protocol (question 80.)

In other words, you can use the for…of loop on any iterable to loop through the sequence of values it generates.

For example, an Array or Map are iterables in JavaScript, but an Object is not.

82
Q

What is a generator?

A

The generator is an alternative for iterators. You can write iterative code with non-continuous execution. In other words, the execution of a generator function can be paused.

Generators are defined using function* syntax. Instead of returning values, they yield values.

When created, generators do not execute their code. Instead, they return a Generator object, which is essentially an iterator. When you call next() on the generator object, it runs the code until it encounters a yield statement, and stops.

83
Q

What is a for of loop?

A

For…of loop can be used to iterate over iterables in JavaScript.

For example, you can print the contents of an array using a for…of loop:

const nums = [1,2,3];
for (const num of nums) {
    console.log(num);
}
84
Q

What is nodejs?

A

Node. js is a popular open-source development platform.

It is used for executing JavaScript code server-side.

Node.js is handy for developing apps that need a persistent connection from the browser to the server.

Node.js is commonly used to build real-time apps such as a chat, news feed, or similar.

85
Q

What is an event loop?

A

An event loop is a queue of callback functions. It handles all the asynchronous callbacks.
When an asynchronous function executes, a callback function is pushed into the queue. The JavaScript engine doesn’t trigger the event loop before the async task has finished.
For example, the structure of an event loop could look like this:
while (queue.waitForMessage()) {
queue.processNextMessage();
}

86
Q

What is a Unary Operator?

A
The unary + operator is used to convert a variable to a number.
If the variable cannot be converted, it is converted to NaN (which is a special case of being a number, so the type is still a number).
let str = "10";
let num = +str;
console.log(typeof str, typeof num);
let word = "Hello";
let n = +word;
console.log(typeof word, typeof n, n);

Output:
string, number
string, number, NaN

87
Q

How to sort elements of an array?

A

Use the sort() to sort the items of an array. This does not create a new array but sorts the original array “in-place”, that is, modifies it directly.

88
Q

What is TypeScript?

A
TypeScript is JavaScript with types. It’s a superset of JavaScript created by Microsoft.
TypeScript adds types such as optional types, classes, async/await, and so on to plain JavaScript.
Here is a simple example of a TypeScript function:
function greet(name: string): string {
   return "Hello, " + name; }
The type information is explicitly expressed in the function’s parameter type and return type.
89
Q

What is a constructor in JavaScript?

A
A constructor is a method for creating and initializing a class object. It’s executed when you instantiate a new object from a class.
For example:
class Student {
  constructor() {
    this.name = "Mike"; } }
let student = new Student();
console.log(student.name);
Output: Mike
90
Q

What is ES6?

A

ES6 (ECMAScript 6) is the sixth version of the JavaScript programming language.

The ES6 was released back in June 2015.

91
Q

What are template literals?

A

Template literals allow you to embed expressions directly inside a string.

When using a template literal, do not declare the string with quotation marks, but use backtick instead (`).
To embed a variable or expression into the string, you need to add it between ${}
For example:

console.log(This is the ${10 * 10}th time)

92
Q

How can you swap two variables without a third?

A

Use destructuring to pull apart values from an array. This can also be used to swap two variables without a third helper:

let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b)
Output:

2 1

93
Q

What is an ArrayBuffer?

A

An ArrayBuffer is a generic and fixed-length binary data buffer.

For instance:

let buffer = new ArrayBuffer(16);
console.log(buffer.byteLength)
Output:

16

94
Q

What is a prototype?

A

All JavaScript objects inherit properties from a prototype.
For example: Math objects inherit properties from the Math prototype.
Array objects inherit properties from the Array prototype.
A prototype is a characteristic of an object. It describes the attributes associated with it. It acts as a blueprint of an object.

You can for example access an object’s prototype to add a new property to an object constructor for example:
function Fruit(name, weight) {
  this.name = name;
  this.weight = weight;}
Fruit.prototype.description = "Yum!";
95
Q

What are arrow functions?

A
Arrow functions provide a shorthand for creating functions in JavaScript.
You can use arrow functions in function expressions only. Here’s a comparison of a regular function and an arrow function:
// Traditional function
var sum = function(a,b){
  return a + b;}
// Arrow Function
var sum = (a,b) => a + b;
Let’s examine it a bit more:

Arrow functions are declared without the function keyword.
If there is only one (returning) expression, you don’t need to use the return keyword.
In the above, also the curly braces are missing. This is only possible if the arrow function consists of only one expression. If there’s more, then you need to add curly braces after the arrow.

96
Q

What is the use of dir() method?

A

The console.dir() displays an interactive list of the properties of a JavaScript object as JSON.

For example:
const student = { “name”:”Mike”, “id”: 132123, “city”: “New York”};
console.dir(student);
Results in a following interactive list in the console.

97
Q

How do you disable right-click on the web page?

A

You can disable the right click on a webpage by returning false from the oncontextmenu attribute on the body element.

98
Q

What is a unary function?

A

A unary function is a function that accepts only one argument.

99
Q

What is a pure function?

A
A pure function is a function that returns the same result with the same arguments regardless of when and where it’s called. A function is pure if it does not depend on the state, or data change during a program’s execution.
For example, a function that calculates the area of a circle is pure:
function circleArea(radius) {
  return Math.PI * Math.pow(radius, 2);
}
100
Q

What is object destructuring?

A
Object destructuring is a way to extract properties from an object (or an array).
const PersonDetails = {
  name: "Matty",
  age: 42,
  married: false}
const {name, age, married} = PersonDetails;
101
Q

What Is an API?

A

An API stands for Application Programming Interface.
APIs are used to allow communication between different applications and parts of the application.
API is not a server. It is an intermediary piece of code that is used to access a server. In other words, API is an access point to a database.

102
Q

What Is the Epoch Time?

A

The Epoch time is the number of seconds since Jan 1, 1970.
This is also called the Unix timestamp.
An epoch time is necessary because computers need to have a starting point in time. Otherwise, they would not be able to tell the time.
Currently, the Epoch time is around 1.6 billion seconds.
Sometimes you see servers store timestamps as epoch times.
{
“item”: “T-shirt”,
“last_modified”: 1647425869
}