Javascript and Typescript notes

Destructuring assignment

You have to use the same names as the ones used in the object from which you are destructuring.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Disabling TLS in NodeJS

NODE_TLS_REJECT_UNAUTHORIZED

If value equals ‘0’, certificate validation is disabled for TLS connections. This makes TLS, and HTTPS by extension, insecure. The use of this environment variable is strongly discouraged. This can be set using the local “.env” file or using `process.env.NODE_TLS_REJECT_UNAUTHORIZED=0`

NODE_TLS_REJECT_UNAUTHORIZED=0

ES6 modules

Allows code and data to be isolated. They help with organizing and grouping code logically. They are also called packages or libraries.

Browsers do not understand modules or imports. That is why we need module loaders (Webpack, RequireJS, SystemJS, etc.)

funcion or const?

  1. https://dev.to/skinnypetethegiraffe/function-or-const-which-do-you-prefer-typescriptjavascript-apa
  2. https://dev.to/ugglr/react-functional-components-const-vs-function-2kj9

JavaScript

https://developer.mozilla.org/en-US/docs/Web/JavaScript

A Web scripting language that is used in both browsers and Web servers. Like all scripting languages, it is used primarily to tie other components together or to accept user input.

Jest testing tips

If you need to chain more than one call after another you can do something like this:

const callAService(value) => {
    const firstResponse = serviceOne(value)
    return serviceTwo(firstResponse)
}

it('should behave some way when provided a value', ()=> {
      serviceOne.mockImplementation((value)=> if(value === 1) return 2 )
      serviceTwo.mockImplementation((value)=> if(value === 2) return 3)

      const actual = callAService(1)
      expect(actual).toEqual(3)
})

jsdoc

How to write JSDoc: https://jsdoc.app/tags-param.html

Libraries to make web service calls

Fetch vs Axios

Fetch doesn’t treat 404, 4XX and 5XX as errors. It is a gotcha we have to keep in mind. How to deal with it? We have to explicitly look for OK property.

if (!resp.ok) {
  // there was an error
}

Axios does treat 404 as an error.

  1. Axios proxy issues

NodeJS

  1. Basic steps for setting up a NodeJS application
  2. Express Web Framework for Nodejs

nodemon

To install and use it in an application, run npm i --save-dev nodemon

This is to make things easy during the development process.

It will restart the server anytime we make changes (instead of having to do it manually).

Printing objects to console

If the default console.log(xx) doesn’t work (because of deeply nested objects), use this:

console.log(JSON.stringify(output, null, 2));

Reading material

  1. https://expressjs.com/en/guide/using-middleware.html
  2. https://github.com/expressjs/body-parser
  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
  4. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
  5. https://momentjs.com/
  6. https://docs.npmjs.com/files/package.json*dependencies
  7. https://rclayton.silvrback.com/speaking-intelligently-about-java-vs-node-performance

How to generate JSDoc comments for Javascript functions?

Using Webstorm, position the caret before the declaration of the method/function or field to document, type the opening block comment `/**`, and press `Enter`. Describe the listed parameters, return values, and so on.

Template strings

Insert data inside strings. Don’t use concatenation anymore.

Example

var name = "john";
var age = 30;
console.log(name + 's age is ' + age);
let name = "john";
let age = 30;
console.log(`${name}'s age is ${age}`);

To get a list of config settings in your computer for your application, use this command

npm config list

https://node.green/

Typescript

Features

Types, Interfaces and Decorators

Plus all the ES6 features like classes, arrow functions, modules, block scoped variables.

Decorators

Functions that are invoked with a prefixed @ symbol.

They return the same thing that was passed in, but it has been argument in some way.

We can decorate classes, methods, properties and parameters.

Variables

Difference between the old way of using “var” and the new ECMAScript way of using “let” and “const” for variables:

  1. The new types are “scoped”.

Truthy and Falsy Values

Vanilla JS

In JavaScript, a value is considered truthy if it is evaluated to true when used in a boolean context. A value is considered falsy if it is evaluated to false when used in a boolean context.

Here is a list of values that are considered falsy in JavaScript:

  1. false
  2. 0 (zero)
  3. "" (empty string)
  4. null
  5. undefined
  6. NaN (Not a Number)

All other values, including objects and arrays, are considered truthy.

For example:

const x = 'Hello';
const y = '';
const z = 0;

if (x) {
  console.log('x is truthy');
}

if (y) {
  console.log('y is truthy');
} else {
  console.log('y is falsy');
}

if (z) {
  console.log('z is truthy');
} else {
  console.log('z is falsy');
}

// Output:
// "x is truthy"
// "y is falsy"
// "z is falsy"

In this example, the variable x is a non-empty string, which is considered truthy, so the first if statement is executed. The variable y is an empty string, which is considered falsy, so the else block of the second if statement is executed. The variable z is the number 0, which is considered falsy, so the else block of the third if statement is executed.

Comparing objects

https://stackoverflow.com/questions/31683075/how-to-do-a-deep-comparison-between-2-objects-with-lodash

Using lodash

An easy and elegant solution is to use _.isEqual, which performs a deep comparison:

var a = {};
var b = {};

a.prop1 = 2;
a.prop2 = { prop3: 2 };

b.prop1 = 2;
b.prop2 = { prop3: 3 };

console.log(_.isEqual(a, b)); // returns false if different

What are the differences?

To see differences between two objects, look at the answers from the post.

Is an object empty?

https://stackoverflow.com/questions/43233102/lodash-isempty-and-has-method-vs-simple-check

  1. Do not use if(user)
    1. It does not take truthy and falsy data into consideration.
  2. Using lodash.isEmpty() is an option
  3. Or you can write your own custom functions. See the post for more details.

Do all objects in an array have values?

https://stackoverflow.com/questions/36148546/return-true-if-all-objects-in-array-has-value-in-property

var isTrue = objectArray.every(obj => obj.Value);

Checking for empty strings

Using lodash

You can use lodash: _.isEmpty(value).

https://lodash.com/docs/4.17.15#isEmpty

Lodash’s _.isEmpty() method checks if a value is an empty object, collection, map, or set. For strings, it returns true if the string is empty ("") and false otherwise. It also returns true for null, undefined, and NaN. JavaScript

CAVEAT: Be careful about the type of the variables that you are comparing with this function. If the variable is a number, this will give unexpected results.

const _ = require('lodash');

_.isEmpty(''); // true
_.isEmpty('abc'); // false
_.isEmpty(null); // true
_.isEmpty(undefined); // true
_.isEmpty(NaN); // true
_.isEmpty(0); // true
_.isEmpty(123); // true
_.isEmpty(true); // true
_.isEmpty(false); // true
_.isEmpty([]); // true
_.isEmpty([1, 2, 3]); // false
_.isEmpty({}); // true
_.isEmpty({ a: 1 }); // false
_.isEmpty(new Map()); // true
_.isEmpty(new Map([['key', 'value']])); // false
_.isEmpty(new Set()); // true
_.isEmpty(new Set([1, 2, 3])); // false

Other ways

Use str === "" when you want a strict and precise check for empty strings only. Use !str when you want a broader check that also covers null, undefined, 0, NaN, and other falsy values.

Tags

  1. Set-up linter and prettier for a React application
  2. Javascript - fetch requests with Bearer tokens

Links to this note