We can also reverse an array without modifying it by creating a reverse for loop, and in each iteration, adding the array element whose index is the current value of the loop counter to a new array. The new array will contain all the elements reversed at the end of the loop.
Let’s look at some ways to quickly get the length of an object in JavaScript.
1. The Object.keys() Method
To get the length of an object, we can pass the object to the static Objectkeys() method, and access the length property of the resulting array. For example:
Note: Object.keys() only returns the enumerable properties found directly on the object. If you want to include non-enumerable properties in the count, use Object.getOwnPropertyNames() instead:
Note: Object.keys() and Object.getOwnPropertyNames() don’t work for symbolic properties. To count symbolic properties, use Object.getOwnPropertySymbols():
Another method to get the length of an object is to use the JavaScript for...in loop to iterate over the properties of the object and increment a variable in each iteration. The variable will contain the object length after the loop.
const obj = {
color: 'red',
topSpeed: 120,
age: 2,
};
let objectLength = 0;
for (let key in obj) {
if (obj.hasOwnProperty(key)) objectLength++;
}
console.log(objectLength); // 3
Because the for...in loop also iterates over the inherited properties of the object, we use the hasOwnProperty() method to ensure that the property exists directly on the object before incrementing the variable.
In this article, we’ll be learning how to concatenate a bunch of strings in JavaScript with a separator of our choice, like a comma or hyphen.
The Array join() Method
To concatenate strings with a separator, we can create an array containing the strings and call the join() method, passing the separator as an argument. The join() method will return a string containing the array elements joined with the separator. For example:
While this works, it’s better to be explicit by passing the comma as an argument if you need comma separation, as not everyone is aware of the default behaviour.
Note: The join() method will return an empty string if we call it on an empty array. For example:
console.log([].join(',')); // ''
Note: Elements like undefined, null, or empty array values get converted to an empty string during the join:
Summary: target is the innermost element in the DOM that triggered the event, while currentTarget is the element that the event listener is attached to.
We use the HTML DOM Event object to get more information about an event and carry out certain actions related to it. Events like click, mousedown, and keyup all have different types of Events associated with them. Two key Event properties are target and currentTarget. These properties are somewhat similar and sometimes return the same object, but it’s important that we understand the difference between them so we know which one is better suited for different cases.
An event that occurs on a DOM element bubbles if it is triggered for every single ancestor of the element in the DOM tree up until the root element. When accessing an Event in an event listener, the target property returns the innermost element in the DOM that triggered the event (from which bubbling starts). The currentTarget property, however, will return the element to which the event listener is attached.
Let’s use a simple example to illustrate this. We’ll have three nested div elements that all listen for the click event with the same handler function.
Clicking the div triggered the event which invoke the handler for div3. The click event bubbles, so it was propagated to the two outer divs. As expected, the target stayed the same in all the listeners but currentTarget was different in each listener as they were attached to elements at different levels of the DOM hierarchy.
In camelcase, the first word of the phrase is lowercased, and all the following words are uppercased. In this article, we’ll be looking at some simple ways to convert a JavaScript string to camelcase.
String Regex Replace
We can use the Stringreplace method with regex matching to convert the string to camel case:
The first regular expression matches the first letter with ^\w and the first letter of every word with \b\w. It also matches any capital letter with [A-Z]. It lowercases the letter if it’s the first of the string and uppercases it if otherwise. After that, it removes any whitespace in the resulting word with \s+ in the second regex.
Lodash camelCase Method
We can also use the camelCase method from the lodash library to convert the string to camelcase. It works similarly to our camelize function above.
The static Stringraw() method is so named as we can use it to get the raw string form of template literals in JavaScript. This means that variable substitutions (e.g., ${num}) are processed but escape sequences like \n and \t are not.
For example:
const message = String.raw`\n is for newline and \t is for tab`;
console.log(message); // \n is for newline and \t is for tab
We can use a raw string to avoid the need to use double backslashes for file paths and improve readability.
For example, instead of:
const filePath = 'C:\\Code\\JavaScript\\tests\\index.js';
console.log(`The file path is ${filePath}`); // The file path is C:\Code\JavaScript\tests\index.js
We can write:
const filePath = String.raw`C:\Code\JavaScript\tests\index.js`;
console.log(`The file path is ${filePath}`); // The file path is C:\Code\JavaScript\tests\index.js
We can also use it to write clearer regular expressions that include the backslash character. For example, instead of:
const patternString = 'The (\\w+) is (\\d+)';
const pattern = new RegExp(patternString);
const message = 'The number is 100';
console.log(pattern.exec(message)); // ['The number is 100', 'number', '100']
We can write:
const patternString = String.raw`The (\w+) is (\d+)`;
const pattern = new RegExp(patternString);
const message = 'The number is 100';
console.log(pattern.exec(message)); // ['The number is 100', 'number', '100']
Vuetify provides a wide range of built-in transitions we can apply to various elements to produce smooth animations that improve the user experience. We can use a transition by setting the transition prop on supported components, or wrapping the component in a transition component like v-expand-transition.
Vuetify Expand Transition
To apply the expand transition to an element, we wrap it in a v-expand-transition component. This transition is used in expansion panels and list groups.
Components like v-menu have an origin prop that allows us to specify the point from which a transition should start. For example, we can make the scale transition start from the center point of both the x-axis and y-axis:
A slide x transition makes the element fade in while also sliding in along the x-axis. Unlike a scroll transition, the element slides out in the same direction it slid in from when closed.
Vuetify comes with a built-in transition system that allows us to easily create smooth animations without writing our own CSS. We can scale, fade or translate a UI element with the various transitions available.
As you might know, ternary operators in JavaScript are a single statement alternative to if...else statements frequently used to make code more concise and easier to understand. For example, we could have a function that returns “yes” or “no” depending on whether a number passed to it is odd or not.
JavaScriptCopied!
function isOdd(num) {
if (num % 2 === 1) return 'yes';
else return 'no';
}
We can refactor the isOdd function to use a one-line conditional statement like this:
JavaScriptCopied!
function isOdd(num) {
return num % 2 === 1 ? 'yes' : 'no';
}
Nested ternary operator in JavaScript
We can nest a ternary operator as an expression inside another ternary operator. We can use this to replace if…else if…else statements and switch statements. For example, we could have a piece of code that sets the English word for the numbers 1, 2, and 3 to a variable. With if...else:
JavaScriptCopied!
let num = 1;
let word;
if (num === 1) word = 'one';
else if (num === 2) word = 'two';
else if (num === 3) word = 'three';
else num = 'unknown';
With switch...case:
JavaScriptCopied!
let num = 1;
let word;
switch (num) {
case 1:
word = 'one';
break;
case 2:
word = 'two';
break;
case 3:
word = 'three';
break;
default:
word = 'unknown';
break;
}
And now with nested ternary operators:
JavaScriptCopied!
let num = 1;
let word =
num === 1
? 'one'
: num === 2
? 'two'
: num === 3
? 'three'
: 'unknown';
The above code example works exactly like the previous two and is less cluttered. Notice we are now able to declare and set the variable in the same statement with this nested ternary approach.
Truncating a string sets a limit on the number of characters to display, usually to save space. We can truncate a string in JavaScript by writing a truncate function that takes the string as the first argument and the maximum number of characters as the second argument.
function truncate(str, length) {
if (str.length > length) {
return str.slice(0, length) + '...';
} else return str;
}
The function truncates the string with the slice method if it has a character count greater than the specified length. Otherwise, it just returns the same string.
Vuetify comes with helper classes for easily customizing the border radius of an element without creating our own CSS. We’re going to explore these classes in this article.
Pill Class
We can use the rounded-pill class to create a rectangle with rounded corners.
The rounded-0 class removes all border radius from an element. To remove border radius from a specific side, we can use a class of the format rounded-{side}-0, where side can be any of t, r, b, and l. For removing border radius from specific corners, we can use a class of the format rounded-{corner}-0 where corner can be any of tl, tr, br and bl.
To apply border radius to a specific side, we can use a helper class of the format rounded-{side} or rounded-{side}-{size}, where side can be one of t, r, b, and l, and size can be one of sm, lg, and xl.
To set the border radius of a specific corner, we can use a helper class of the format rounded-{corner} or rounded-{corner}-{size}, where corner can be any of tl, tr, br and bl, and size can be any of sm, lg, and xl.