Falsy and truthy values in Javascript

Falsy values in JavaScript are false, null, undefined, 0, NaN, ““ (empty strings). The following construct:

let val = ...;
        if (!val) {
     // Execute
}

… will always Execute if the val contains one of the above values.

Truthy values are all others. Some examples are: {} (empty object), [] (empty array), function () {} (empty function), ‘0’ (string with 0 as value). This enables us to write:

if (val) {
// We’re guaranteed val will not be null, undefined or any other 
// falsy value.
}

Use this when writing if statements, instead of writing val == null or val == undefined.

Arrow functions in JavaScript

Arrow functions were introduced in ES6 and represent a shorter syntax for function declaration. They don’t have their own this (or arguments) and they preserve this context of the outer function. The following examples will print test on the output if the fn function is called on object. Observe the console.log argument in the example below, with and without arrow function.

Without arrow function

With arrow function.

{
  test: 'test',
  fn: function() {
    const that = this;

function sub() { console.log(that.test); } sub();

   } 
}
{
  test: 'test',
fn: function() {
const sub = () => console.log(this.test);

     sub();
    } 
}

 

Use the arrow functions on the reduce, map, forEach, filter and similar functions and only if the function body is short.


“Falsy and Truthy values & Arrow Functions in JS” Tech Bite was brought to you by Kenan Klisura, Lead Software Engineer at Atlantbh.

Tech Bites are tips, tricks, snippets or explanations about various programming technologies and paradigms, which can help engineers with their everyday job.

Dynamic programming
Software DevelopmentTech Bites
December 9, 2022

Dynamic Programming

Dynamic programming is both a mathematical optimization method and a computer programming method. By definition, it is a technique in computer programming that helps to efficiently solve a class of problems with overlapping subproblems and optimal substructure properties. It refers to simplifying a complicated problem by breaking it into simpler…

Leave a Reply