JavaScript Tips and Tricks you should know

Javascript tips and tricks | Code Architects

JavaScript is one of the most widely used programming languages in the world. It is a versatile language that allows developers to create interactive and dynamic web pages. However, mastering JavaScript can be a challenge for beginners and experienced developers alike. Here are few JavaScript Tips and Tricks you should know 👇

Empty an Array

let fruits = ["🍇", "🍈", "🍉", "🍊", "🍍"]
fruits.length = 0;

// []

This is a JavaScript code that declares an array of fruits using the let keyword. The array contains five different fruits represented by emojis. The length property of the fruits array is then set to 0, which essentially empties the array of all its elements.

Javascript Tips and Tricks | Code Architects

Round Numbers

let pi = 3.141592653
pi = pi.toFixed(3);

// 3.142

This is a code that declares a variable named ‘pi’ using the let keyword and assigns it a numerical value representing the mathematical constant pi, to several decimal places. The toFixed() method is then called on the pi variable, with an argument of 3, which rounds the value to 3 decimal places and returns it as a string.

Convert Array to Object

var fruits = ["🍍", "🍊", "🍉", "🍇"];
var fruitsObject = { ...fruits };

//{"0": "🍍", "1": "🍊", "2": "🍉", "3": "🍇"}

The array contains four different fruits represented by emojis. A new variable named ‘fruitsObject’ is then declared using the spread operator, which takes all the elements of the ‘fruits’ array and spreads them into a new object. This new object contains the fruits as its values and their corresponding indices as its keys.

Add CSS to Console Message

console.log("%c Hello World", "color: red, font-size: 2em");

The message to be printed is “Hello World”. However, the message is not printed in the default format. Instead, the message is styled using CSS properties passed as a string argument to the method. In this case, the message is styled in red color with a font-size of 2em using the %c placeholder.

Disable Context Menu

<body oncontextmenu="return false;"></body>

This is an HTML code that disables the context menu that appears when a user right-clicks on an element on a web page. The code is added to the <body> element of an HTML document, and it uses the oncontextmenu event attribute to trigger a JavaScript function that returns false. This prevents the default behavior of the context menu from appearing, effectively disabling it. This code can be useful in situations where a developer wants to prevent users from copying or downloading content from a web page or to prevent any unwanted actions from occurring.

Format JSON Code

console.log(JSON.stringify({name: "John", Age: 23}, null, '\t'));

  "name": "John",
  "Age": 23

The JSON.stringify() method is used to convert the object to a JSON string. This method takes in three arguments: the object to be converted, a replacer function that can be used to filter or modify the output, and a space argument that specifies the number of spaces to use for indentation. In this case, the null value is passed as the second argument, indicating that no filtering or modification is needed. The third argument, \t, is used to specify that the JSON string should be formatted with a tab character for indentation. The resulting JSON string is then printed to the console using the console.log() method.

Get Unique Values from Array

let fruits = ["🍎", "🍓", "🍇", "🍎", "🍋", "🍒", "🍅", "🍇"];
let uniqueFruits = [ ... new Set(fruits)];

//["🍎", "🍓", "🍇", "🍋", "🍒", "🍅"]

The array contains several different types of fruits, some of which are repeated. A new variable named uniqueFruits is then declared using the spread operator, which takes all the elements of the fruits array and spreads them into a new Set object. The Set object eliminates any duplicate values, ensuring that only unique values remain. The unique values in the Set object are then spread back into an array using the spread operator and assigned to the uniqueFruits variable.

Remove Falsy


The filter() method creates a new array with all the elements that pass the test implemented by the provided function. In this case, the filter() method takes the Boolean function as its argument, which acts as a filter that removes all falsy values from the myArray array. The Boolean function returns false for values that are considered falsy in JavaScript, such as false, null, 0 , "", undefined, and NaN. The resulting array contains only truthy values. This code can be useful for removing empty or false elements from an array.

Sort Array

[0, 10, 4, 9, 123, 54, 1].sort((a, b) => a - b);

// [0, 1, 4, 9, 10, 54, 123]

The sort() method arranges the elements of an array in ascending or descending order, based on a comparison function. In this case, the comparison function is defined using an arrow function that subtracts the second argument b from the first argument a. When the result is negative, the function sorts a before b. When the result is positive, the function sorts b before a. And when the result is zero, the order of the two elements is not changed.

Check if Browser is online


// true

The navigator object is a built-in object in JavaScript that provides information about the browser environment, including the online status of the browser. The onLine property of the navigator object returns a boolean value that indicates whether the browser is online or offline. If the browser is online, the property returns true, and if it is offline, the property returns false. The console.log() method is used to print the value of the onLine property to the console. This code can be useful for detecting the online status of the browser and taking appropriate actions based on that status.

Thank you for reading the blog. Follow us on our Instagram. Check out our other blogs 👇

Leave a Comment


No comments yet. Why don’t you start the discussion?

Leave a Reply

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

five × five =