10 JavaScript Tips to Help You Build Better Projects (PART — I)

Yes, These will make you a Better Programmer😉

Prince Gupta
Published in
7 min readAug 20, 2023

--

JavaScript is a popular programming language for the web. If you’re interested in coding or software engineering, especially in web development, learning JavaScript is a great choice.

Mastering JavaScript enables you to build lively and engaging web interactions. It empowers you to enhance websites and web apps, making them more interactive, functional, and responsive, resulting in an improved user experience.

Whether you’re new to JavaScript or an experienced developer, this article has something valuable for you.

Let’s Start 🏃

Tip 1: Use console.table()to Show Arrays and Objects in the Console

While console.log displays arrays or objects as usual, console.table arranges them in a table format with indexes and values for clarity.

Here’s how it works with arrays:

const arr = ['Prince', 'Gupta', 17, true];

console.log(arr);
console.table(arr);

console.log()

Output of console.log(arr)

Now see the magic of console.table()

Output of console.table(arr)

Not only does it arrange the array neatly in a table, but it also presents it similarly to how a console.log() would display it.

It operates similarly with objects:

const Obj = {
name : 'Prince',
surname : 'Gupta',
age : 17,
undertaking : true
};

console.log(Obj);
console.table(Obj);

console.log(Obj)

Output of console.log(Obj)

console.table(Obj)

Tip 2: Opt for Template Interpolation to Build Strings Instead of Using the Assignment Operator

Template interpolation presents a tidier and easier-to-read syntax compared to the usual concatenation using the plus (+)symbol. This technique allows you to effortlessly incorporate variables within strings.

const name = 'Prince';
const age = 18;

// Using plus (+) concatenation
const plusConcat =
'Hi there 👋🏽 \nMy name is ' + name + ' and I am ' + age + ' years old.';

// Using template literal concatenation
const templateLiteralConcat = `Hi there 👋🏽 \nMy name is, ${name} and I am ${age} years old.`;

Tip 3: Transform Strings into Numbers Using Unary Plus and Number Constructor

To change strings into numbers, you can take advantage of the unary plus operator (+)and the number constructor (Number()).

To employ the unary plus for converting, just add a plus sign before the string. And for the number constructor method, enclose the number within Number().

This allows you to switch seamlessly between strings and numerical values.

const myNum = '5';

// Conversion with Unary (+)
convertNum1 = +myNum;

// Conversion with Number() Constructor
convertNum2 = Number(myNum);

console.log(convertNum1, typeof convertNum1); // 5 'number'
console.log(convertNum2, typeof convertNum2); // 5 'number'
Transforming Strings to Numbers via + and Number().

Tip 4: No Need to Declare Each Variable with a Keyword

Here’s a nifty trick: when you have several variables in a row, you can skip using const, let, or var for each one after the first.

The only thing to remember is that when declaring variables without a keyword, you should use a comma (,) to separate them instead of a semi-colon.

It works like this:

// EXAMPLE NUMBER 1
let x, y, z;

x = 1;
y = 2;
z = 3;

console.log(x, y, z); // 1, 2, 3


// EXAMPLE NUMBER 2
let x;
let y;
let z;

x = 1;
y = 2;
z = 3;

console.log(x, y, z); // 1, 2, 3

Tip 5: Employ console.group()Alongside Multiple console.log()’sto Organize Connected Items in the Console.

Imagine you have various interconnected details like username, bio, and more that you want to display in the console. In such cases, make use of console.group() and console.groupEnd() to create a grouped section.

This approach provides a dropdown list containing all the related items:

console.group('My Introduction:');

console.log(`Hello, My name is Prince`);
console.log(`and my Twitter username is: princedevelops`);
console.warn("You should Follow me now..");
console.error('Guess why you are witnessing an error');

console.groupEnd();

See the RESULT 👇

What a way for your Twitter Promotion 😂😂

Tip 6: Enhance Your Console Output with the %cFormat Specifier

The %cspecifier isn’t a built-in part of JavaScript. it’s a tool offered by modern browsers for styling console output. When you employ %c, it must be the initial parameter within the console.log()method.

You can define the styling you wish to use for the console:

const MillionDollar_Styling = `padding: 20px;
background-color: #9411d1;
color: white`;

console.log('%c Your Console has been hacked by A White Hat Hacker', MillionDollar_Styling);

or you can use it Directly via console.log()

console.log('%c Your Console has been hacked by A White Hat Hacker', "padding: 20px; background-color: #9411d1; color: white");

Tip 7: Manage White Spaces with trim(), trimStart(), and trimEnd()

Use the trim()method to eliminate white spaces from both ends of a string. Employ trimStart() to remove white spaces from the start, and trimEnd()to eliminate white spaces from the end of a string.

These methods come in handy when you want to clean up user inputs or get rid of leading/trailing spaces in strings.

Here are some examples:

const greet = '   Hello world! Good Morning   ';
console.log(greet.trim());
// Output: 'Hello world! Good Morning'

const greet2 = ' Hello world! Good Evening ';
console.log(greet2.trimStart());
// Output: 'Hello world! Good Evening '

const text = ' Hello world! Good Night ';
console.log(text.trimEnd());
// Output: ' Hello world! Good Night'

const input = ' ';
if (input.trim() === '') {
console.log('The input contains whitespace characters.');
} else {
console.log('The input contains non-whitespace characters.');
}

// Output: The input contains whitespace characters.

Tip 8: Utilize startsWith()and endsWith()String Methods for String Beginnings and Endings

The startsWith() and endsWith() methods assist in checking whether a string commences or concludes with a specific part. As they yield either trueor false, these methods prove helpful for a range of string operations and conditional assessments.

Here’s how you use them:

Basic Example :

const message = 'Hello Readers!, How are you?';

console.log(message.startsWith('H')); // true
console.log(message.startsWith('h')); // false
console.log(message.endsWith('?')); // true

You can use these two methods to programmatically extract specific text or filenames, as demonstrated here:

Medium Example :

const files = [
'ReadME.txt',
'License.txt',
'MyGirlfriedImage.jpg',
'Prince.js',
'EveryReadersPhoneNumber.txt',
];

// Extract .txt files
const textFiles = files.filter((file) => file.endsWith('.txt'));
console.log(textFiles); // Output: ['ReadME.txt', 'License.txt', 'EveryReadersPhoneNumber.txt']

Both startsWith() and endsWith() methods offer the flexibility to include optional start and end positions, allowing you to narrow down the part of the string where the examination occurs.

For instance, consider the following example:

const text = 'Discover the wonders of coding';

console.log(text.startsWith('D', 0)); // Output: true
console.log(text.startsWith('wonders', 16)); // Output: false
console.log(text.endsWith('g', 15)); // Output: false

Tip 9: Use Destructuring to Get Properties from Objects

Destructuring is a useful JavaScript feature that allows you to extract object properties and assign them to variables in a more concise and clear manner than using traditional dot notation.

Here’s how you can apply destructuring to extract properties:

const socials = {
twitter: 'https://twitter.com/princedevelops',
instagram: false,
GitHub: 'https://github.com/myselfprincee'
};

// Traditional way
const twitter2 = socials.twitter;
const instagram2 = socials.instagram;
const GitHub2 = socials.GitHub;

console.log(twitter2, instagram2, GitHub2); // John Doe 30 male

// with destructuring
const { twitter, instagram, GitHub } = socials;

console.log(twitter, instagram, GitHub);
// John Doe 30 male

Tip 10: Utilize the Spread Operator for Copying and Merging Arrays

The spread operator serves various purposes, including copying arrays, merging arrays, duplicating objects, and passing multiple arguments to functions.

Here’s how you can use it to copy and merge arrays:

const originalArr = ["original", true, "OK?"];
const copiedArr = [...originalArr];

console.log(copiedArr); // ["original", true, "OK?"]

// Merge two or more arrays
const arr1 = [10, 12, 13];
const arr2 = [45, 52, 60];

const mergedArr = [...arr1, ...arr2];

console.log(mergedArr); // [10, 12, 13, 45, 52, 60]

You can also clone objects using the spread operator:

const Obj = { name: 'Unknown', age: 179 };
const clonedObj = { ...Obj };

console.log(clonedObj); // { name: 'Unknown', age: 179 }

Additionally, the spread operator enables you to pass multiple arguments into a function:

const addNumbers = (a, b, c) => {
return a + b + c;
}

const numbers = [10, 12, 8];
const sum = addNumbers(...numbers);

console.log(sum); // 30

So, Let’s end this Blog Today. I hope these tips will surely help you in Building Better and Huge Projects. If you are still here and Reading this. Consider Following me & Subscribing to Email Notifications to Stay Updated with the crazy Content I will upload.

For any Discussions, you can add a comment.

&&

For more content, you can follow me on Twitter : )

Love you & Bye Bye ❤️

--

--