Categories
Blog Front End Development Javascript Self Improvement

Improving My JavaScript Skills – 5 Things

I’m always improving my javascript skills when I’m learning something new. Sometimes it’s worth going over existing skills again to reinforce that knowledge. I’ve found these 5 things to be pretty powerful.

1. Underscoring Variables and Namespacing events

These is more helpful for code readability, rather than it being a particular feature. The first uses underscored variables that are otherwise not used. Let me give you an example:

array.forEach(function(currentValue, index), thisValue);

This function requires currentValue. But what if you only wanted to output the index value? You can underscore the first, like so:

 array.forEach(function(_currentValue, index), thisValue);

This is basically a visual placeholder saying, “hey, this needs to be here, but we’re not actually doing anything with it.”

You can also do something similar with namespacing events, like so:

$('#element').on('click.namespace', someFunction);

//remove all event handlers in that namespace
$('#element').off('.namespace');

Note that this depends on JQuery. When using namespaced events in vanilla js, expect a bit more effort.

2. Ternary operators and the nullish coalescing operator

The ternary operator is your friend. It streamlines your code for smaller conditionals, i.e:

// regular if statement
if(someVar != null) {
  console.log("hurray!");
} else {
 console.log("aww!")
};

// ternary equivalent
console.log(someVar != null? "hurray!" : "aww!"); 

This is useful for ensuring a variable has a value whether or not it has been set. You can also use this very effectively within JQuery:

$('.element')[someVar != null? 'addClass' : 'removeClass']('active');

The curly brackets are removed, the question mark becomes the opening bracket, and the colon is the else declaration.

The nullish coalescing operator (what a mouthful!) is a magnificent beast, utilising the double ?? to check the nullish value of a variable:

// if the variable here is null, it will fallback to return the value after the ??
console.log( jobRole ?? 'Unemployed');
// because jobRole has not been set, the console will return 'Unemployed'

It’s important to note that you can’t use this with logical operators, or you’ll get a syntax error:

null || undefined ?? 'default value';
// console says 'nope!' (syntax error)

3. arrow functions and implicit return

A small one but powerful. Depending on the context of your arrow function, like a single expression, you don’t need to explicitly declare a return.

function regularFunction() {
 return 'wat?' // requires a return statement
};

regularFunction(); // returns 'wat?'

// new ES6 way
const donk = () => { return 'put a donk on it' };
donk() // returns 'put a donk on it'

OR

const donk2 = () => 'yeh yeh yeh';
donk2() // returns 'yeh yeh yeh'

4. Destructuring assignment

This is a way for javascript to extract values from arrays. or properties from objects and put them into distinct variables. This has been around in other programming languages for a while (Perl, Python), so it’s a nice addition to ES6. Arrays and objects are of course handled slightly differently.

const villains = ["Bane", "Riddler", "Penguin"];
const [venom, q, umbrella] = villains;
console.log(venom); // returns Bane

Note that the destructured const value needs to match the order of the original array. So if you want to skip everything but the last value, you’d need to write it like this:

const villains = ["Bane", "Riddler", "Penguin"];
const [,,umbrella] = villains;
console.log(umbrella); // returns Penguin

Objects are handled like so:

const dcu = { name: 'joker', nemesis: 'batman' };
const { name, nemesis } = dcu;

// is equivalent to:
// const a = dcu.name
// const b = dcu.nemesis

If you have nested objects, you can still handle them too, just treat your const value as a new object:

const dcu = { 
  name: "joker", 
  nemesis: "batman", 
  movies: [ 
    {title: "The Dark Knight", release: 2008},
    {title: "Batman", release: 1989}
  ]
};

const { name, nemesis, movies: [{title: movie}] } = dcu;

console.log(movie); // returns 'The Dark Knight'

Note that this only returns the first value, if you need to iterate over multiple values, you’ll have to handle it differently, like so:

const movies = [ 
  {title: "The Dark Knight", release: 2008},
  {title: "Batman", release: 1989}
];

for (const { title: t, release: y } of movies) {
  console.log(`Name: ${t}, Release: ${y}`);
};

/// returns:
// Name: The Dark Knight, Release: 2008
// Name: Batman, Release: 1989

5. Using Classes in Javascript

This is trickery in that, javascript doesn’t actually use classes in same the way that C#, php etc uses them. They are actually built with prototypes, but are pimped up to look like classes. What this means is nicer looking, tidy code. This to me was also massive in improving my javascript skills. To set up a class, you use the class keyword. You can then use a constructor function to initialise any variables you may need:

class Hero {
 constructor({name, occupation}) {
   this.name = name,
   this.occupation = occupation
 }
};

I placed the variables in an object here, so we don’t need to worry about ordering when we come to creating our first Hero instance. We use the new keyword to do this:

const darkknight = new Hero (
{
name: "Bruce Wayne",
occupation: "Batman"
}
);

// we can return the values from this:
console.log(`${darkknight.name} is the ${darknight.occupation}`);

// "Bruce Wayne is the Batman"

We can also set up methods within our Hero class, and use them as follows:

class Hero {
 constructor({name, occupation}) {
   this.name = name,
   this.occupation = occupation
 }

 whatAreYou(){
  alert(`I'm ${this.occupation}!`);
 }
};

const darkknight = new Hero(...);

darkknight.whatAreYou();

// alert: "I'm Batman!"

If you want to get or set values, you can use the appropriate keyword values. Including creating new variables for the class (like vehicle):

class Hero {
...
  set setVehicle(vehicle) {
    this.vehicle = vehicle;
  }
  
  get getVehicle() {
    return `${this.occupation} got into the ${this.vehicle}`;
  }
}

// set the vehicle,
darkknight.setVehicle = "batmobile";

// get the value
darkknight.getVehicle;

// returns 'Batman got into the batmobile'

This just scratches the surface of just what you can do with javascript classes. You can use other keywords etc, similar to actual classes, such as static etc. Here is the complete code to have fun with:

class Hero {
  constructor({name, occupation}) {
    this.name = name,
    this.occupation = occupation
  }
  
  whatAreYou() {
    alert(`I'm ${this.occupation}!`);
  }
  
  set setVehicle(vehicle) {
    this.vehicle = vehicle;
  }
  
  get getVehicle() {
    return `${this.occupation} got into the ${this.vehicle}`;
  }
}

const darkknight = new Hero({name:"Bruce Wayne", occupation:"Batman"});

console.log(`${darkknight.name} is the ${darkknight.occupation}`);
darkknight.whatAreYou();
darkknight.setVehicle = 'batmobile';
console.log(darkknight.getVehicle); 

I’m always learning something new when I’m improving my javascript skills. If you learned something new, let me know!

via GIPHY

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.