Javascript and Typescript notes
- Destructuring assignment
- Disabling TLS in NodeJS
- ES6 modules
- funcion or const?
- JavaScript
- Jest testing tips
- jsdoc
- Libraries to make web service calls
- NodeJS
- nodemon
- Printing objects to console
- Reading material
- How to generate JSDoc comments for Javascript functions?
- Template strings
- To get a list of config settings in your computer for your application, use this command
- Typescript
- Variables
- Truthy and Falsy Values
- Comparing objects
- Is an object empty?
- Do all objects in an array have values?
- Checking for empty strings
- Tags
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?
- https://dev.to/skinnypetethegiraffe/function-or-const-which-do-you-prefer-typescriptjavascript-apa
- 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.
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
- https://expressjs.com/en/guide/using-middleware.html
- https://github.com/expressjs/body-parser
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
- https://momentjs.com/
- https://docs.npmjs.com/files/package.json*dependencies
- 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
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:
- 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:
- false
- 0 (zero)
- "" (empty string)
- null
- undefined
- 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
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
- Do not use
if(user)
- It does not take truthy and falsy data into consideration.
- Using
lodash.isEmpty()
is an option - Or you can write your own custom functions. See the post for more details.
Do all objects in an array have values?
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.