Computed Property Names in Javascript

Computed Property Names is an ES6 feature which allows the names of object properties in JavaScript object literal notation to be determined dynamically, i.e. computed. JavaScript objects are really dictionaries, so it was always possible to dynamically create a string and use it as a key with the syntax object[‘property’] = value. However, ES6 Computed Property Names allow us to use dynamically generated names within object literals. Example: const myPropertyName = 'c' const myObject = { a: 5, b: 10, [myPropertyName]: 15 } console....

February 3, 2023 · 1 min · Daman Arora

Replacing Switch Statements With Object Literals

A typical switch statement in javascript looks like this example below: var type = 'coke'; var drink; switch(type) { case 'coke': drink = 'Coke'; break; case 'pepsi': drink = 'Pepsi'; break; default: drink = 'Unknown drink!'; } console.log(drink); // 'Coke' It’s similar to if and else statements below: function getDrink (type) { if (type === 'coke') { type = 'Coke'; } else if (type === 'pepsi') { type = 'Pepsi'; } else if (type === 'mountain dew') { type = 'Mountain Dew'; } else if (type === 'lemonade') { type = 'Lemonade'; } else if (type === 'fanta') { type = 'Fanta'; } else { // acts as our "default" type = 'Unknown drink!...

February 3, 2023 · 2 min · Daman Arora

Modules and Classes in ES6

Modules ES6 has added Modules to JavaScript. This means, that you may split up your code over multiple files, which of course is a good practice. This is common in ES6 already, however you always require a module loader for that. To split up your code, you basically export variables, functions, objects, … in one file and import it in another: // export.js export let myExportedVar = 42; // import.js import { myExportedVar } from '....

December 26, 2022 · 1 min · Daman Arora

Two Important Rules of ES6 Modules

There are two important Rules, which you need to understand if you’re working with ES6 Modules: Modules are always in Strict Mode (no need to define "use strict"). Modules don’t have a shared, global Scope. Instead each Module has its own Scope.

December 26, 2022 · 1 min · Daman Arora

Destructuring an Array or an Object in ES6

Destructuring is a cool new feature which allows you to easily extract values from an object or an array. It is important to note, that destructuring for arrays is position based, whereas in case of the objects it is based on the names of the keys. Array: let numbers = [1, 2, 3, 4, 5]; let [a, b] = numbers;// a => 1, b => 2 Object: let person = { name: 'Max', age: 27 }; let {name, age} = person; // Notice the {} instead of [] More information may be found here....

December 25, 2022 · 1 min · Daman Arora