Bogumil Wrona

IT Consultant | R&D | [...] Solutions

JavaScript Tips and Tricks

this keyword

1
2
3
4
var func = function() { return this },
    obj = { name: 'A', aFun: func };

obj.aFun(); //=> some global object, probably Window

Testing Existance

Using the loose inequality operator !=, it is possible to destinguish between null, undefined and anything else:

1
2
3
4
5
6
7
8
9
10
11
12
13
function exist(arg) {
  return arg != null;
};

// tests:
console.log(exist(null));               //=> false
console.log(exist(undefined));          //=> false
console.log(exist({}.notThere));        //=> false
console.log(exist((function() {}())));  //=> false
console.log(exist(0));                  //=> true
console.log(exist(false));              //=> true
console.log(exist({}));                 //=> true
console.log(exist([]));                 //=> true

Testing Truthy

1
2
3
function isTruthy(arg) {
  return (arg !== false) && exist(arg);
};

Comments