Sobes.tech
Middle

General understanding of JavaScript: parameter passing, asynchrony, prototypes, error handling.

sobes.tech AI

Answer from AI

In JavaScript:

Parameter Passing:

  • Primitives (numbers, strings, booleans) are passed by value — the function receives a copy.
  • Objects and arrays are passed by reference — the function receives a reference to the original object, so changes inside the function affect the external object.
function change(x) { x = 5; }
let a = 1;
change(a);
console.log(a); // 1 — primitive did not change

function changeObj(obj) { obj.prop = 5; }
let o = { prop: 1 };
changeObj(o);
console.log(o.prop); // 5 — object changed

Asynchronous Operations:

  • JavaScript is single-threaded but supports asynchronous operations via callbacks, promises, and async/await.
  • Asynchronous code allows not to block the main thread, for example, during server requests.
async function fetchData() {
  try {
    let response = await fetch('https://api.example.com/data');
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

Prototypes:

  • In JS, objects inherit properties through a prototype chain.
  • Each object has a hidden property [[Prototype]] pointing to another object.
  • Inheritance can be created via Object.create or constructor functions.
function Person(name) {
  this.name = name;
}
Person.prototype.greet = function() { console.log('Hello, ' + this.name); };
let p = new Person('Ivan');
p.greet(); // Hello, Ivan

Error Handling:

  • Uses try/catch for synchronous code.
  • For asynchronous code — error handling via catch on promises or try/catch inside async functions.
try {
  throw new Error('Something went wrong');
} catch (e) {
  console.error(e.message);
}

fetch('url')
  .then(response => response.json())
  .catch(error => console.error('Request error:', error));
General understanding of JavaScript: parameter… - sobes.tech