JavaScript – quick tips #1

1. Console logging done right

var  images = {
  'img1': 'http://foo.bar',
  'text1': 'Foo',
}

var  texts = {
  'text1': 'Lorem',
}

// Colored text in the console: 
console.log('%c Images and Texts:', 'color: orange; font-weight: bolder;')
// View the properties in a table (common properties grouped together)
console.table([images, texts])

2. Timer for code

// start timer
console.time('loooop');

let i = 0;
while(i < 10000000) { i++ }

// end timer
console.timeEnd('loooop');

3. Tracing function calls

When we want to see where the code was trigerred it shows where the code was defined (VM227:1) and where it was called (VM227:3) and (VM227:4).

const doSayHello = () => console.trace('saying hello')

doSayHello();
doSayHello();

4. How to display properties of an object in a more concise way

STANDARD WAY:

const vehicle = {
   'fuel': 'diesel',
   'milage': '100000 km',
   'upholstery': 'leather',
}

function viewVehicleProps(vehicle) {
   return `The vehicle runs on ${vehicle.fuel}, the upholstery is ${vehicle.upholstery} and it has run for ${vehicle.milage}`;
}

BETTER – OPTION 1:

In the argument of the function you can just specify the properties of an object and exclude the repeatable name from the inside of it.

const vehicle = {
   'fuel': 'diesel',
   'milage': '100000 km',
   'upholstery': 'leather',
}

function viewVehicleProps({fuel, milage, upholstery}) {
   return `The vehicle runs on ${fuel}, the upholstery is ${upholstery} and it has run for ${milage}`;
}

BETTER – OPTION 2:

let vehicle = {
   'fuel': 'diesel',
   'milage': '100000 km',
   'upholstery': 'leather',
}

function viewVehicleProps(vehicle) {
   let {fuel, milage, upholstery} = vehicle;
   return `The vehicle runs on ${fuel}, the upholstery is ${upholstery} and it has run for ${milage}`;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: