boy-Over-9
== write & share ==

44 Node.js Questions for Practice

November 20, 2024

Question 1

Which of the following lines of code will have an event emitter emit an event?

  • new EventEmitter('update')
  • new EventEmitter().emit('update')
  • EventEmitter.emit('update')
  • EventEmitter.new().emit('update')

Question 2

Which of the following modules should be used to decode raw data into string in NodeJS?

  • buffer
  • string_buffer
  • string_decoder

Question 3

Which of the following is a stream?

  • process.env
  • process.uptime
  • process.argc
  • process.stdin

Question 4

How do you check whether a value is a date object in NodeJS?

  • console.isDate(value)
  • assert.isDate(value)
  • util.date(value)
  • util.types.isDate(value)

Question 5

Which of the following lines declares readFile as a promise-based method?

  • const { readFile } = require('fs')
  • const { readFile } = require('promises')
  • const { readFilePromise: readFile } = require('fs')
  • const { readFile } = require('fs').promises

Question 6

Complete the function. Return the sum of an input integer’s digits. Example: for 432 this would be 4+3+2=9.

function main(_a) {
  // Write your code here
}

Question 7

Complete the function. Return a boolean of whether the input n number is prime (a prime number is a natural number greater than 1 that is not a product of two natural smaller numbers).

function main(_x) {
  // Write your code here
}

// Note: this function will be called when you run the test case

Question 8

Which of the following is a correct way to execute the command “ls -la” using a child process?

  • fork('ls -la')
  • spawn('ls -la')
  • exec('ls -la')
  • exec('ls', '-la')

Question 9

How can you convert a callback-based function like child_process.exec to promise-based?

  • new Promise(child_process.exec)
  • new Promise(child_process.exec())
  • util.promisify(child_process.exec)
  • util.promisify(child_process.exec())

Question 10

Which of the following Buffer class methods returns an uninitialized buffer?

  • from
  • concat
  • alloc
  • allocUnsafe

Question 11

Which of the following fs module methods can be used to read a file without buffering all of its content into memory?

  • read
  • readFile
  • readFileSync
  • createReadStream

Question 12

Complete the function. Return the sum of all digits in-between input variables a and b (inclusive). As an example, the sum of digits between 2 and 4 is 2+3+4=9.

function main(_a, _b) {
  // Write your code here
}

// Note: this function will be called when you run the test case

Question 13

=> hỏi phụ câu 12, do bai giai sai

Question 14

Complete the function. For an input integer n (greater than 1), return the sum of all its divisors (except 1 and itself). If that integer is a prime, return 0.

function main(_x) {
  // Write your code here
}

// Note: this function will be called when you run the test case

Question 15

Given the following:

console.log(iterator1.next().value); // 42

Which snippet will set up iterator1 for the above behavior?

  • [ ]
let set1 = new Set();
set1.add(42);
const iterator1 = set1.allKeys();
  • [ ]
let set1 = new Set();
set1.add(42);
const iterator1 = set1.properties();
  • [x]
let set1 = new Set();
set1.add(42);
const iterator1 = set1.values();
  • [ ]
let set1 = new Set();
set1.add(42);
const iterator1 = set1.getValues();

Question 16

The following code chooses different paths depending on whether x is an object. What will occur when x is null? Are there improvements that need to be made?

if (typeof x === "object") {
  console.log("x is an object");
} else {
  console.log("x is not an object");
}
  • The first if conditional will throw an Error because x is a null value. The code can be more defensive by enclosing the conditional in a try…catch statement to catch the potential error.
  • “x is an object” will be printed to the console; this is intended behavior, as the primitive null type behaves identical to an object in all respects. No improvements need to be made.
  • “x is an object” will be printed to the console as per JavaScript’s spec. This can be avoided by checking for null first: if (x != null && typeof x === 'object') { ... }.
  • “x is not an object” will print to the console. null is not an ‘object’, and as of the most recent JavaScript spec, typeof null === ‘null’ is the correct way to check for null values. No improvements need to be made.

Question 17

Given the following:

var bar = foo(10);
bar(2); // 12

Which function returns these results?

  • [ ]
function foo(x, y) {
  return x + y;
}
  • [x]
function foo(x) {
  return function (y) {
    return x + y;
  };
}
  • [ ]
function foo(x) {
  return function (y) {
    return function () {
      return x + y;
    };
  };
}
  • [ ]
      function bar(x) {
          return bar(y) {
              return x + y;
          };
      }

Question 18

Which RegExp literal pattern has the global search flag?

  • [x]
const re = /\w+\s/g;
  • [ ]
          const re = /g/\w+\s;
  • [ ]
const re = /\w+\s/.global();
  • [ ]
const re = /\w+\s/i;

Question 19

What occurs when a script tag is present on a web page and it contains a src attribute?

  • Page parsing is paused while the resource specified by src is loaded and executed.
  • The page continues to be parsed while the resource at src is loaded and executed asynchronously.
  • Page parsing is paused by the resource at src is loaded, but nothing is executed.
  • The page continues to be parsed while the resource at src is loaded asynchronously, but nothing is executed.

Question 20

What syntax can separate an iterable expression into all of its individual pieces?

  • Array.prototype.slice() (iterable.slice())
  • The decompose syntax (::iterable)
  • Array.prototype.flat() (iterable.flat())
  • Spread syntax (...iterable)

Question 21

A web app has a performance-impacting function, impactFoo(), that is called around the same time that a series of AJAX calls reach completion. How can the function be deferred to be called after any pending event handlers to avoid blocking the application?

  • deferTask(impactFoo);
  • setInterval(impactFoo, 1);
  • window.addEventListener("impactFoo", () => { impactFoo(); });
  • setTimeout(impactFoo, 0);

Question 22

What is a valid identifier?

  • 1stName
  • first$name
  • first-name
  • first+name

Question 23

What does the following code print to the console? Why?

let xhr = new XMLHttpRequest();
xhr.open("GET", "https://someapi.endpoint/v1/", true);
let res = xhr.send();
console.log(res.responseText);
  • function responseText() { ... ; responseText is a function and must be invoked to get the body of the response to xhr.send().
  • undefined. The object referenced at res.responseText does not have the lexical scope needed to access the body of the response.
  • It prints the body of the response to the console along with the status code; for example: { "data": "value" }, 200 OK.
  • undefined. You cannot get the response from the send() method; you must add an event listener or give xhr.onreadystatechange a handler function.

Question 24

What is the output in the console?

const foo = (bar) => ({ bar });
console.log(foo(1));
  • {bar: 1}
  • 1
  • foo is not a function
  • SyntaxError
  • undefined

Question 25

What does the code print?

let elem = { a: 1 };
const array = [elem];

elem.a += 1;
elem = null;

console.log(array[0]);
  • null
  • { a: 1 }
  • { a: 2 }
  • ReferenceError

Question 26

Complete the function so that it returns the input string with all redundant space removed.

function main(_x) {
  // Write your code here
}

// Note: this function will be called when you run the test case

Example test cases

  • Input: (too much whitespace)
  • Expected Output: too much whitespace

Question 27

Complete the function to return the total number of elements in 2 arrays.

function main(_x, _y) {
  // Write your code here
}

// Note: this function will be called when you run the test case

Example test cases

  • Input: (["a", "b"], ["c"])
  • Expected Output: 3

Question 28

Complete the function to reverse an array, then join the elements with space.

function main(_x) {
  // Write your code here
}

// Note: this function will be called when you run the test case

Example test cases

  • Input: (["world", "Hello"])
  • Expected Output: "Hello world"

Question 29

Given Code:

function f2() {
  "use strict";
  return this;
}

Question: Which is correct?

  • f2() === undefined
  • f2() === window
  • f2() === null
  • f2() === function

Question 30

Question: Which call signature is NOT valid for setState?

  • this.setState({})
  • this.setState({}, () => {})
  • this.setState([])
  • this.setState(() => {})

Question 31

Question: How can you change a name property inside a React.Component class component?

  • props["name"] = "new name"
  • props.name = "new name"
  • You cannot do that because the properties of a component are read-only.
  • None of the above

Question 32

Question: What is the component’s life cycle in React?

  • Initializing -> Rendering -> Destroying
  • Rendering -> Unmounting
  • Mounting -> Unmounting
  • Mounting -> Updating -> Unmounting

Question 33

Question: The lifecycle methods are mainly used for ___?

  • Keeping track of event history
  • Enhancing components
  • Freeing up resources
  • None of the above

Question 34

Question: Which React component return type is invalid?

  • const MyComponent = () => ""
  • const MyComponent = () => []
  • const MyComponent = () => false
  • Neither. They are all valid return types

Question 35

Question: How do you use component spread attributes in JSX?

  • <Component foo="a" bar="b"/>;
  • <Component {foo="a" bar="b"}/>;
  • const opts = {foo: "a" bar: "b"} <Component {...opts}/>;
  • const opts = {foo: "a" bar: "b"} <Component spread={...opts}/>;

Question 36

Question: Which method is not part of ReactDOM?

  • ReactDOM.destroy()
  • ReactDOM.hydrate()
  • ReactDOM.createPortal()
  • ReactDOM.findDOMNode()

Question 37

Question: The prop-types modules allow React to perform type checking for component properties. Which of the following PropTypes does not exist?

  • PropTypes.array
  • PropTypes.boolean
  • PropTypes.func
  • PropTypes.object
  • PropTypes.node
  • PropTypes.shape
  • None of the above

Question 38

Question: Which of the following methods in a React Component should be overridden to stop the component from updating?

  • willComponentUpdate
  • shouldComponentUpdate
  • componentDidUpdate
  • componentDidMount

Question 39

Question: What kind of error types are not caught by Error Boundaries?

  • Lifecycle methods
  • Rendering errors
  • Event handlers
  • Constructor errors

Question 40

Question: React uses a “diff” algorithm to optimize the DOM update in the browser. Which of the following codes is optimized to avoid unnecessary rendering?

return (
  <ul>
    {list.map((item) => {
      return <li id={item.id}>{item.label}</li>;
    })}
  </ul>
);
return (
  <ul>
    {list.map((item, index) => {
      return <li key={index}>{item.label}</li>;
    })}
  </ul>
);
return (
  <ul>
    {list.map(function (item) {
      return <li key={item.id}>{item.label}</li>;
    })}
  </ul>
);
return (
  <ul>
    {list.map((item) => {
      return <li>{item.label}</li>;
    })}
  </ul>
);

Question 41

Câu hỏi:

Which of the following is true about rules of hook?

  • Only call hook at top level
  • Only call hook at bottom level
  • Only call hook inside loops, conditions, or nested functions
  • Only call hook from regular Javascript functions

Question 42

Which of the following examples is a “controlled” component compared to a “noncontrolled” component? (Controlled Component vs. Uncontrolled Component).

  • <input type="text" ref={(input) => this.input = input} />
  • <input type="text" value={this.state.value} onChange={this.onChangeHandler} />
  • <input type="text" name={this.state.name} onChange={this.onChangeHandler} />
  • <input type="text" onChange={this.onChangeHandler} />
  • <input type="text" />

Question 43

What is a higher-order component (HOC)?

  • A function that adds extra functionality to a component it is called with.
  • A component that wraps multiple smaller components.
  • A component with higher priority than other components.
  • A function component that has a state.

Question 44

What happens after the component state is being updated?

  • The state value is updated and you can manually call the render function to reflect the updates.
  • The state value is updated and you can optionally pass a callback function which can trigger a render of the component if it returns true.
  • The state is updated just like any other regular property.
  • The state value is updated and the component is re-rendered to reflect the changes.

Profile picture

written by boy-Over-9
Eat, sleep, code, Judo repeat... Twitter