Categories
JavaScript Tips

Useful JavaScript Tips — Variables, File Names, and Console

Spread the love

Like any kind of apps, JavaScript apps also have to be written well. Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

var and let

var is function scoped and let is block-scoped.

var is hoisted and let isn’t.

Only the variable is hoisted, but the value isn’t.

For instance, if we have:

console.log(x);
var x = 1;

then x would be undefined since var x is hoisted but 1 is not.

On the other hand, we can’t do the same thing with let :

console.log(x);
let x = 1;

We’ll get an error with the code above since we can’t use let variables unless they’ve been declared.

To reduce confusion, we should use let variables.

Breaking the forEach Iteration

We can return true inside the callback that we pass into forEach to skip an itreration.

This way, we can have the same functionality as continue .

For instance, we can write:

[0, 1, 2, 3, 4].forEach((val, i) => {
  if (val === 2) {
    return true;
  }
  console.log(val);
});

The code about would skip 2 since when val is 2, then we returned true .,

So we skipped the console log that’s below it.

Using Slice

The slice method can be used to get array entries from an array.

We can start with a negative index to return array entries from the right instead of the left.

So if we have:

const arr = [1, 2, 3];

Then:

arr.slice(-1)

returns [3] .

arr.slice(-2))

returns [2, 3] .

and:

arr.slice(-3)

returns the original array.

This is because -1 is the index of the last element of the array.

-2 is the second last and so on.

Short Circuit Conditionals

Short circuit conditionals are handy since we can do things with && and || that we might not have thought of.

For instance, instead of writing:

if(condition){
    dosomething();
}

We can write:

condition && dosomething();

since the doSomething is only run when condition is truthy with the && operator.

Likewise, we can take advantage of short-circuiting with the || operator.

For instance, we can write:

a = a || 'default';

since a is assigned to a if a is truthy.

Otherwise, 'default' is assigned to a .

Use Optional Arguments

We can make arguments optional with the default parameter syntax.

For instance, we can write:

const divide = (a, b = 1) => a / b;

Then b would be assigned to 1 if we skipped the argument.

So divide(2) would be 2.

Copy Things to the Clipboard

We can get the element from a clipboard and copy its contents by writing:

document.querySelector('#foo').select();
document.execCommand('copy');

The first line selects the element with ID foo .

Then the second line does the copying.

Extract File Extension from a File Name

There are a few ways that we can extract the file extension from the file name

Regex

For instance, we can write:

const getExt = (filename) => {
  return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename)[0] : undefined;
}

We have a regex to split the file name by the dot. Then we get the part after the dot with /[^.]+$/.exec(filename)[0] or undefined if there’s no dot.

split

Also, we can use the split method to split a file name by the dot.

For example, we can write:

const getExt = (filename) => {
  return filename.split('.').pop();
}

A string has the split method which can split a string by a separator and returns it as an array of strings.

Then we call pop to remove the last part of the split string and returns it.

Therefore, we get the extension.

Console Logging Trick

We can use the && to run console log before evaluating the expression after it.

Since console.log returns undefined the right operand will always be evaluated.

So we can write:

console.log(foo) && false

We logged the value of foo and return false all in one expression.

Print a Function to a Console

We can convert a function to a string to print out the function’s code.

For instance, we can write:

console.log(func.toString());

This way, we can see the code of the function in the console log.

Conclusion

We can log a function’s code in with the toString and console.log methods.

Also, we can use the && operator to log a value before evaluating some other expression.

There are also various ways to get the file extension from a file name.

Finally, we should use let to declare variables as much as possible.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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