My favorite JavaScript
shortcuts
As I have been working on content for my personal website and portfolio, I have been using lots of JavaScript
(and PHP
, but that’s for another post). So I decided to compile a list of commonly used shortcuts I found myself using.
String to Number with Unary “+”
Most often seen in its binary form like 2 + 2, I was surprised that this works as claimed. You can convert a numeric string to a number by preceding the string with the unary “+”
sign.
Recently I programmed a BMI calculator, and since the values from the form were coming in as strings, I needed to convert them to numbers to get a proper result.
let numericStr = "10";
console.log(+numericStr); //10
Object as a function parameter
One of the most annoying things is a function
definition with a long parameter list. When it comes time to pass the arguments to the function
, you may forget the order of variables needed to properly call the function
. Objects as arguments to the rescue!
Because the calculateCI
function was defined with an object as the parameter, you can pass the values in any order you want. Note: just because you can, doesn’t mean you should. Never sacrifice clarity just to use a cool feature.
function calculateCI({principal, annualRate, yearsInvested, yearlyTimesCompounded}) {
let interestRate = +annualRate / 100;
const amount = (+principal * ((1 +(interestRate / +yearlyTimesCompounded) ) ** (yearlyTimesCompounded * annualRate)) )
return +amount.toFixed(2); // Number.toFixed(decimalPlaces) returns a string, so we use the unary "+" operator to make the return value a number
}
console.log(calculateCI({annualRate: 4.3, principal: 1500,yearlyTimesCompounded: 4, yearsInvested: 6})) //1802.87
speaking of objects… How about a quick way to differentiate between variables in the console?
Object literal shorthand
In the process of debugging, I think we have all logged too many values to the console. It can quickly become a mess. Let’s see what the syntax looks like:
let var1 = "value1";
let var2 = "value2";
console.log({ var2 }); //{ var2: "value2" }
The variable is logged in the console as an object, with the variable name as the object key and the variable value as the object value.
Default parameters
Ever call a function and forget to pass an argument, and get NaN (Not a number)? This is the result of doing a mathematical operation on data that isn’t a number, or can’t be coerced to one. Here’s an example:
function getSum(num1, num2) {
return num1 * num2;
}
console.log(getSum(2)); // NaN
In this case since the second argument (num2
) isn’t being passed, num1
is being multiplied by undefined. This is a nonsensical operation and JavaScript
lets us know by returning NaN. Thanks JavaScript
!
To avoid such a scenario, we could define the function with a default parameter:
function getSum(num1, num2 = 1) {
return num1 * num2;
}
console.log(getSum(2)); // 2
Because num2
has a default parameter, when you omit it in the function call, it uses the default value 1.
Object and array destructuring
Arrays and objects are the compound data types (in converse to scalar data types, like strings, booleans, and numbers) in JavaScript. wouldn’t it be cool if we could grab data out of these data structures and reference them using variables of the same name as the object key? Well, you can with object/array destructuring:
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
const { firstName, lastName, age } = person; //destructuring the object
console.log(firstName); // "John"
It’s worth noting, in order to successfully use destructuring, you don’t have to use all the values. You can just grab only the variables you need. In other words, you could have stopped at firstName
. The same concept works for arrays:
let randomNums = [9,2,5,1];
const [firstNum, secondNum] = randomNums;
console.log(firstNum); // 9
Handling null values gracefully
Let’s face it, things don’t always work out. You may not get that value from the form or query parameter. You will need to fall back to a default value to avoid ugly errors and confusing your users.
JavaScript introduced the nullish coalescing operator just for this purpose. It returns the value on its right side when it encounters a null or undefined value.
function getName(name) {
return name ?? "Hello! you forgot to enter a name! enter one and try again";
}
console.log(getName()); //"Hello! you forgot to enter a name! enter one and try again"
Cool console methods
I learned this one from one of Wes Bos’s JavaScript fundamentals courses (thanks Wes!). Let’s say you want to inspect the properties of an object. of course, you can console.log it
let perpetualEducation = {
url: "https://perpetual.education",
instructors: ["Derek", "Ivy"],
teaches: ["web design", "programming", "design thinking"],
}
console.log(perpetualEducation.url) // "https://perpetual.education"
But let’s say you wanted to see all the properties, console.log-ing() every object property would be tedious, and you’d quickly lose sight of the bigger picture (the overall structure of the object). This is where console.table()
is so helpful. It formats the contents of the object as you guessed it… a table!
As you can see, instead of the data being logged out on one line (like we see in console.log()), it is neatly formatted as a table.
To be continued
I will be coming back to this article as I remember/learn more JavaScript
tips. If you know any, leave them in the comments!