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
Write a program to iterate over an array and print all the values of it (Method "IN")
for(let index in arr){ console.log(arr[index]); }
26
Write a program to iterate over an array and print all the values of it (Method "OF")
for(let value of arr){ console.log(value); }
27
Write a program to append and prepend, single or multiple values in to an array (Method "single")
const arr = [2, 3]; arr. push(4); // [2, 3, 4] arr. unshift(1); // [1, 2, 3, 4]
28
Write a program to append and prepend, single or multiple values in to an array (Method "multiple")
const arr = [3, 4]; arr. push(5, 6); // [3, 4, 5, 6] arr. unshift(1, 2); // [1, 2, 3, 4, 5, 6]
29
Write a program to append and prepend, single or multiple values in to an array (Method "continuous")
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
Show insertion and removal of elements can happen in the array for given index
const arr = [1, 2, 2, 3]; const position = 2; const count = 1; arr.splice(position, count); // [2] console.log(arr); // [1, 2, 3]
31
Show the different ways of emptying an array which has values (Method "re-init")
arr = [];
32
Show the different ways of emptying an array which has values (Method "SPLICE")
arr.splice(0, arr.length)
33
Check if given input is an array or not | Method "ARRAY"
Array.isArray(arr);
34
Check if given input is an array or not | Method "OBJECT"
Object.prototype.toString.call(arr) === '[object Array]'
35
Show how an array in JavaScript can act like a stack and queue
``` // 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
Create an array by removing all the holes of the array
const uniqueArr = arr.filter(value => true);
37
Optimize the given statements having lot of logical checks to use a compact and cleaner logic
browser === "chrome" || browser === "firefox" || browser === "IE" || browser === "safari"
38
Optimize the given statements having lot of logical checks to use a compact and cleaner logic (Method "variable INCLUDES")
``` const browserList = ["chrome", "firefox", "IE", "safari"]; !browserList.includes(browser); ```
39
Write a program to iterate over a 2 dimensional array and print all the values of it (Method "TRADITIONAL")
``` for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[i].length; j++) { console.log(arr[i][j]); } } ```
40
Write a program to iterate over a 2 dimensional array and print all the values of it (Method "VAR of ARRAY")
``` for (let rowArr of arr) { for (let value of rowArr) { console.log(value); } } ```
41
Write a code to make xmlHTTPRequest to get data from the server asynchronously
``` 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
Show the usage of typeof operator on different types of values
``` 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
Write a code to iterate over a string | Method "TRADITIONAL"
``` for(let i =0; i < str.length; i++){ console.log(str.charAt(i)); } ```
44
Write a code to iterate over a string | Method "VAR in STR"
for(let index in str){ console.log(str[index]); }
45
Write a code to iterate over a string | Method 'VAR of STR"
for(let value of str){ console.log(value); }
46
Show the creation of Regular Expression in JavaScript
``` // literal form let re = /ab+c/g; ``` ``` // constructor form let re = new RegExp('ab+c', 'g'); ```
47
Show the usage of template literals with expression interpolation and tagged templates
``` // 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 ```