Javascript - Utilities Flashcards

1
Q

Write a function which returns another function and execute it after calling

A
function higherOrderFunction(){
    function displayHello(){
        console.log("Hello")
    }
    return displayHello;
}
// driver code
var func = higherOrderFunction();
func();                                 // Hello
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Write a function which executes another function recieved as an argument

A
function callbackExecutor(callback){
    if(typeof callback === "function"){
        callback();
    }
}
// driver code
function callbackFunc(){
    console.log("Callback function executed");
}

callbackExecutor(callbackFunc); // Callback function executed

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

Create a function having no parameters declared and print all the arguments passed to it
(Method1)

A
function func(){
    for(let key in arguments){
        console.log(arguments[key]);
    }
}
// driver code
func(1, "Hello", true);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Create a function having no parameters declared and print all the arguments passed to it
(Method2)

A
function func(){
    for(let value of arguments){
        console.log(value);
    }
}
// driver code
func(1, "Hello", true);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Write a function which executes only if the number of arguments match the number of parameters the function is expecting

A
function func(a, b, c){
    if(func.length === arguments.length){
        console.log("Number of arguments passed match the expected arguments");
    }
    else {
        throw new Error("Number of arguments passed do not match the expected arguments");
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Design a function which can recieve variable number of arguments in parameters and print them

A
function varArgsFunc(...params){
    params.forEach(function(value, index){
        console.log(index, ": ", value);
    })
}
// driver code
varArgsFunc("Hello", ",", "World", "!!!");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Write a function which can return multiple values from a function
(Method Array)

A
function multipleValueReturnFunc(){
    const a = 5, b = 10;
    return [a, b];
}
// driver code
const [x, y] = multipleValueReturnFunc();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Write a function which can return multiple values from a function
(Method Obj)

A
function multipleValueReturnFunc(){
    const a = 'Java', b = 'Script';
    return {
        a, b
    };
}
// driver code
const {x, y} = multipleValueReturnFunc();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Write a function which can return multiple values from a function
(Method Iterator)

A
function* multipleValueReturnFunc(){
    const a = 5, b = 10;
    yield a;
    yield b;
}
// driver code
const iterator = multipleValueReturnFunc();
const x = iterator.next().value;
const y = iterator.next().value;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Display all the keys of an object

Method “IN”

A
for(let key in obj){
    if (obj.hasOwnProperty(key)) {
        console.log(key);
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Display all the keys of an object

Method “OF”

A
for(let key of Object.keys(obj)){
    if (obj.hasOwnProperty(key)) {
        console.log(key);
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Display all the keys of an object

Method “FOR EACH”

A
Object.keys(obj).forEach((key) => {
    if (obj.hasOwnProperty(key)) {
        console.log(key);
    }
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Display all the values of an object

A

console.log(Object.values(obj));

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

Display all the values of an object

Method “OF Obj”

A

for(let value of Object.values(obj)){
console.log(value);
}

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

Display all the values of an object

Method “KEY IN”

A
for(let key in obj){
    if (obj.hasOwnProperty(key)) {
        console.log(obj[key]);
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Write a function which can check if a given object is empty or not

A
function isObjectEmpty(obj){
    if(obj !== null && typeof obj !== "undefined" && typeof obj === "object")
        return Object.keys(obj).length === 0 && JSON.stringify(obj) === "{}";
    else
        return false;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Show the usage of ‘Object.entries’ to create an object from key value pairs
(Method “ARRAY”)

A
const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ];
const obj = Object.fromEntries(arr);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Show the usage of ‘Object.entries’ to create an object from key value pairs
(Method “MAP”)

A
const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
const obj = Object.fromEntries(map);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Connect 2 objects so that one object is prototypically connected to the other
(Method “setPrototype”)

A
const obj1 = { a: 1 };
const obj2 = { b: 2 };
obj2.setPrototypeOf(obj1);
20
Q

Connect 2 objects so that one object is prototypically connected to the other
(Method ‘__porto__’)

A
const obj1 = { a: "Object 1 value" };
const obj2 = { b: "Object 2 value" };
obj2.\_\_proto\_\_ = obj1;
21
Q

Create an object with getter and setter for property

A

const obj = {};

Object.defineProperty(obj, 'data', {
    _data: 0,                           // closure variable to hold the data
    get() {
        return this._data;
    },
    set(value) {
        this._data = value;
    }
});
22
Q

Write a class which uses private variable and function

A
class ClassWithPrivateFields {
    #privateVar;
    publicVar;
    #privatFunc() {
        this.#privateVar = 7;
        this.publicVar = 10;
    }
    publicFunc() {
        this.#privatFunc();
        return [this.#privateVar, this.publicVar];
    }
}
// driver code
const instance = new ClassWithPrivateFields();
// can't access private variable
instance.privateVar;                     // undefined

// can’t access private function

instance. privatFunc(); // Error
instance. publicFunc(); // 7, 10

23
Q

Show how can we use for..of loop to iterate on a range with given start and end values in an object

A
// Example
let range = {
    start: 1,
    end: 10
};

for (let i of range) console.log(i); // 1 2 3 4 5 6 7 8 9 10

24
Q

Write a program to iterate over an array and print all the values of it
(Method “traditional for loop”)

A
for(let i =0; i < arr.length; i++){
    console.log(arr[i]);
}
25
Q

Write a program to iterate over an array and print all the values of it
(Method “IN”)

A

for(let index in arr){
console.log(arr[index]);
}

26
Q

Write a program to iterate over an array and print all the values of it
(Method “OF”)

A

for(let value of arr){
console.log(value);
}

27
Q

Write a program to append and prepend, single or multiple values in to an array
(Method “single”)

A

const arr = [2, 3];

arr. push(4); // [2, 3, 4]
arr. unshift(1); // [1, 2, 3, 4]

28
Q

Write a program to append and prepend, single or multiple values in to an array
(Method “multiple”)

A

const arr = [3, 4];

arr. push(5, 6); // [3, 4, 5, 6]
arr. unshift(1, 2); // [1, 2, 3, 4, 5, 6]

29
Q

Write a program to append and prepend, single or multiple values in to an array
(Method “continuous”)

A

const arr = [1, 2, 3];
const otherArr = [4, 5, 6];
arr.push(…otherArr); // [1, 2, 3, 4, 5, 6]
arr.unshift(…otherArr); // [4, 5, 6, 1, 2, 3, 4, 5, 6]

30
Q

Show insertion and removal of elements can happen in the array for given index

A

const arr = [1, 2, 2, 3];
const position = 2;
const count = 1;
arr.splice(position, count); // [2]
console.log(arr); // [1, 2, 3]

31
Q

Show the different ways of emptying an array which has values
(Method “re-init”)

A

arr = [];

32
Q

Show the different ways of emptying an array which has values
(Method “SPLICE”)

A

arr.splice(0, arr.length)

33
Q

Check if given input is an array or not

Method “ARRAY”

A

Array.isArray(arr);

34
Q

Check if given input is an array or not

Method “OBJECT”

A

Object.prototype.toString.call(arr) === ‘[object Array]’

35
Q

Show how an array in JavaScript can act like a stack and queue

A
// To add the value to the stack
arr.push(value);
// To remove the value from the stack
arr.pop();
// To remove the value from the queue
arr.shift();
36
Q

Create an array by removing all the holes of the array

A

const uniqueArr = arr.filter(value => true);

37
Q

Optimize the given statements having lot of logical checks to use a compact and cleaner logic

A

browser === “chrome” || browser === “firefox” || browser === “IE” || browser === “safari”

38
Q

Optimize the given statements having lot of logical checks to use a compact and cleaner logic
(Method “variable INCLUDES”)

A
const browserList = ["chrome", "firefox", "IE", "safari"];
!browserList.includes(browser);
39
Q

Write a program to iterate over a 2 dimensional array and print all the values of it
(Method “TRADITIONAL”)

A
for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[i].length; j++) {
        console.log(arr[i][j]);
    }
}
40
Q

Write a program to iterate over a 2 dimensional array and print all the values of it
(Method “VAR of ARRAY”)

A
for (let rowArr of arr) {
    for (let value of rowArr) {
        console.log(value);
    }
}
41
Q

Write a code to make xmlHTTPRequest to get data from the server asynchronously

A
const xhr = new XMLHttpRequest();
xhr.open("GET", url);

xhr.onload = function() {
console.log(this.response);
};

xhr.onerror = function() {
console.log(this.statusText);
};

xhr.send();

42
Q

Show the usage of typeof operator on different types of values

A
typeof 50                 //   "number"
typeof "text"             //   "string"
typeof true               //   "boolean"
typeof undefined          //   "undefined"
typeof function(){}       //   "function"
typeof 10n                //   "bigint"
typeof Symbol()           //   "symbol"
typeof [1, 2]             //   "object"
typeof {}                 //   "object"
43
Q

Write a code to iterate over a string

Method “TRADITIONAL”

A
for(let i =0; i < str.length; i++){
    console.log(str.charAt(i));
}
44
Q

Write a code to iterate over a string

Method “VAR in STR”

A

for(let index in str){
console.log(str[index]);
}

45
Q

Write a code to iterate over a string

Method ‘VAR of STR”

A

for(let value of str){
console.log(value);
}

46
Q

Show the creation of Regular Expression in JavaScript

A
// literal form
let re = /ab+c/g;
// constructor form
let re = new RegExp('ab+c', 'g');
47
Q

Show the usage of template literals with expression interpolation and tagged templates

A
// Template literals with expression interpolation
const num1 = 10, num2 = 20;
`The sum of ${num1} and ${num2} is ${num1 + num2}`;         // The sum of 10 and 20 is 30