Skip to main content

During the development, we use objects and we are always confused which approach is the best. That was the main reason why I decided to write a blog about it, so I really hope in near future most of your obstacles will be resolved and you will be more confident in choosing which is the best approach.

In this blog, I will explain some of the object features and I will make some comparisons, so let’s start!

Switch vs object literals

We all know what is a switch – case statement and we used them at least one time in our life, no matter which programming language. But since we are talking about JavaScript, have you ever asked yourself if it is clever to use it?

Well, of course, the answer is NO. Now you are asking yourself, then it must be if-else statements, but still, the answer is NO. The best approach is to use objects.

Let’s see why…

Problems:

  • switch-case
    • Hard to maintain which leads you to difficult debugging and testing
    • You are manually forced to use break within each case
    • Nested errors
    • Restrictions, like not allowing to use the same constant in two different cases…
    • In JavaScript, everything is based on curly braces, but not switch
    • Evaluates every case until it finds the right one
  • If-else statements
    • Hard to maintain which leads you to difficult debugging and testing
    • Hard to understand when there is complex logic
    • Hard to test
    • Evaluates every statement until it finds the right one if you don’t end it explicitly

According to these problems, the best solution is objects. The reason for that is the advantages that objects are offering us, like:

  • You are not forced to do anything
  • You can use functions inside the objects which means you are much more flexible
  • You can use closure benefits
  • You are using the standard JavaScript objects, which makes the code friendlier
  • Gives you better readability and maintainability
  • Since the objects approach is like a hash table the performance gets better rather than the average cost of switch case
  • All these advantages lead us to the conclusion that objects are more natural and are part of many design patterns in JavaScript where switch-case is an old way of coding

Let’s see an example with objects how they look like:

<!DOCTYPE html>
<html> 
<body>
<script>
      function getById (id) {
            var ids = {
                  'id1': function () {
                        return 'Id 1';
                  },
                  'id2': function () {
                        return 'Id 2';
                  },
                  'default': function () {
                        return 'Default';
                  }
            }
            return (ids[id] || ids['default'])();
      };

      var ref = getById('id1')
      console.log(ref)         // Id 1

      var ref1 = getById()
      console.log(ref)         // Default

      var ref1 = getById(‘noExistingId’)
      console.log(ref)         // Default
</script>
</body>
</html>

hasOwnProperty(key) vs in

hasOwnProperty() – method which returns Boolean or true only if the object contains that property as its own property.

in – operator which returns Boolean or true only if the object contains that property as its own property or in its prototype chain.

function TestObj(){
      this.name = 'TestName';
}
TestObj.prototype.gender = 'male';

var obj = new TestObj();

console.log(obj.hasOwnProperty('name'));       // true
console.log('name' in obj);                    // true
console.log(obj.hasOwnProperty('gender'));     // false 
console.log('gender' in obj);                  // true

Object properties

There are two ways: dot notation and bracket notation. Most of the developers often ask themselves which approach they should use or maybe if there is any difference? In the end, they use one of them wherein most of the cases both solutions work fine without knowing why and without paying attention to its differences. Let’s make an overview.

Dot notation:

  • s can only be alphanumeric, which means it can only include two special characters “_” and “$”
  • Property identifiers can’t start with numbers and variables

Bracket notation:

  • Property identifiers must be String or a variable which references to a String
  • Property identifier can contain any character in their name
var obj = {
      '$test': 'DolarValue',
      '%test': 'PercentageValue'
      …
}

console.log(obj["$test"])                      // 'DolarValue'
console.log(obj.$test)                          // 'DolarValue'

These both will give the same result because both support `$` in their name, but what happens if we use another special character like `%`?

console.log(obj["%test"])    // 'PercentageValue'
console.log(obj.%test)       // It will throw an error:              
                            Uncaught SyntaxError: Unexpected token ‘%’

In the next blog, I will cover loops optimization using the object properties and testing code speed.