For over 5+ years we help companies reach their financial and branding goals. oDesk Software Co., Ltd is a values-driven technology agency dedicated

Gallery

Contacts

Address

108 Tran Dinh Xu, Nguyen Cu Trinh Ward, District 1, Ho Chi Minh City, Vietnam

E-Mail Address

info@odesk.me

Phone

(+84) 28 3636 7951

Hotline

(+84) 76 899 4959

Content Writer Development oDesk Blog Technology Websites Development
10 JavaScript Concepts Every Node.js Developer Must Master

10 JavaScript Concepts Every Node.js Developer Must Master

1. JavaScript Closures: A closure is an inner function that maintains access to its outer function’s scope, even after the outer function has finished executing. This allows for the creation of private variables and Stateful functions.

Code Example

function outerFunction() {
  let counter = 0;
  return function innerFunction() {
    counter++;
    return counter;
  };
}

const count = outerFunction();
console.log(count()); // Output: 1
console.log(count()); // Output: 2

2. JavaScript Prototypes: In JavaScript, every function has a prototype property. This property is used to attach properties and methods that will be inherited by objects created from that constructor function. JavaScript uses prototype inheritance, where objects can directly inherit properties from other objects via their prototype chain.

Code Example

function Car(make, model) {
  this.make = make;
  this.model = model;
}

Car.prototype.getDetails = function() {
  return `${this.make} ${this.model}`;
};

const myCar = new Car('Toyota', 'Camry');
console.log(myCar.getDetails()); // Output: Toyota Camry

3. Defining Private Properties using Hash Names (Modern JavaScript): With modern JavaScript classes, you can define private class members (properties and methods) using a # prefix. This provides a truly private, platform-enforced restriction on access.

Code Example

class Counter {
  #count = 0; // Private class field

  increment() {
    this.#count++;
  }

  get value() {
    return this.#count;
  }
}

const myCounter = new Counter();
myCounter.increment();
console.log(myCounter.value); // Output: 1
// console.log(myCounter.#count); // This would result in a SyntaxError

4. Defining Private Properties using Closures: Before the introduction of private class fields, closures were a common way to simulate private variables in JavaScript. By defining variables within an outer function’s scope and returning an object with methods that can access those variables, you can create a form of encapsulation.

Code Example

function createCounter() {
  let _counter = 0; // Private variable due to closure
  return {
    increment: function() {
      _counter++;
    },
    get value() {
      return _counter;
    }
  };
}

const anotherCounter = createCounter();
anotherCounter.increment();
console.log(anotherCounter.value); // Output: 1

5. JavaScript Modules: Modules allow you to organize code into reusable, independent units, improving maintainability and avoiding global namespace pollution. Node.js traditionally uses CommonJS modules (require() and module.exports), while ES6 modules (import and export) are the modern standard and are also supported in newer Node.js versions.

Code Example

// ES6 Module (myModule.js)
export default function myModule() {
  return 'Hello from ES6 Module!';
}

// Importing ES6 Module in another file
// import myModule from './myModule.js';
// console.log(myModule());

// CommonJS (commonjsModule.js)
module.exports = function commonjsModule() {
  return 'Hello from CommonJS Module!';
};

// Importing CommonJS Module in another file
// const commonjsModule = require('./commonjsModule.js');
// console.log(commonjsModule());

6. Error Handling: Effective error handling is crucial for building robust applications. In JavaScript and Node.js, common strategies include try…catch blocks for synchronous code, throwing custom errors, and handling asynchronous errors (e.g., with catch() for Promises or try…catch with async/await).

Code Example

// Synchronous error handling
try {
  throw new Error('Something went wrong synchronously!');
} catch (error) {
  console.error('Caught synchronous error:', error.message);
}

// Asynchronous error handling with Promises
const fetchData = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(new Error('Failed to fetch data!'));
    }, 1000);
  });
};

fetchData()
  .then(data => console.log(data))
  .catch(error => console.error('Caught asynchronous error:', error.message));

7. JavaScript Currying: Currying is a functional programming technique where a function that takes multiple arguments is transformed into a sequence of functions, each taking a single argument. This makes functions more flexible and allows for partial application of arguments.

Code Example

function add(a) {
  return function(b) {
    return a + b;
  };
}

const add5 = add(5);
console.log(add5(3)); // Output: 8
console.log(add(10)(7)); // Output: 17

8. JavaScript apply, call, and bind Methods: These methods are used to control the value of the this keyword within a function.

call(): Invokes a function immediately with a specified this context and arguments provided individually. apply(): Invokes a function immediately with a specified this context and arguments provided as an array.
bind(): Returns a new function with a specified this context and optional initial arguments, but does not invoke the function immediately.

Code Example

const person = {
  name: 'Alice'
};

function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

console.log(greet.call(person, 'Hello', '!')); // Output: Hello, Alice!
console.log(greet.apply(person, ['Hi', '.'])); // Output: Hi, Alice.

const greetBob = greet.bind({ name: 'Bob' }, 'Hey');
console.log(greetBob('!!!')); // Output: Hey, Bob!!!

9. JavaScript Memoization: Memoization is an optimization technique that speeds up function execution by caching the results of expensive function calls. If the function is called again with the same arguments, the cached result is returned instead of re-executing the function.

Code Example

function factorial(n, cache = {}) {
  if (n in cache) {
    return cache[n];
  }
  if (n <= 1) {
    return 1;
  }
  cache[n] = n * factorial(n - 1, cache);
  return cache[n];
}

console.log(factorial(5)); // Calculates factorial(5)
console.log(factorial(5)); // Returns cached result

10. JavaScript IIFE (Immediately Invoked Function Expression): An IIFE is a JavaScript function that runs as soon as it is defined. It’s often used to create a private scope for variables, preventing them from polluting the global namespace.

Code Example

(function() {
  const message = 'This message is private.';
  console.log(message); // Output: This message is private.
})();

// console.log(message); // ReferenceError: message is not defined

(async function() {
  await Promise.resolve('Asynchronous IIFE');
  console.log('Async IIFE executed!');
})();

Author

oDesk Software

Leave a comment