10 JavaScript Tricky Hacks - Part 1
Sayuj Sehgal
Posted on March 7, 2024
Are you ready to learn cool JavaScript tricks? These tricks will make your code better, easier to understand, and faster to write. In this post, we'll explore hidden features and shortcuts that will help you unlock the full power of JavaScript!
1. Nullish Coalescing Operator (??)
The Nullish Coalescing Operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. This can be useful when you want to provide a default value for a variable that might be null or undefined.
Here's a simple code example:
let value = null;
let defaultValue = "Default Value";
let result = value ?? defaultValue;
console.log(result); // Outputs: "Default Value"
In this example, because value is null, the nullish coalescing operator returns defaultValue, so "Default Value" is logged to the console.
If value was not null or undefined, it would be returned instead:
let value = "Not Null Value";
let defaultValue = "Default Value";
let result = value ?? defaultValue;
console.log(result); // Outputs: "Not Null Value"
In this case, because value is neither null nor undefined, it is returned by the nullish coalescing operator, so "Not Null Value" is logged to the console.
2. Optional Chaining (?.)
Safely access nested object properties without an error if a reference is nullish. The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined.
Here's a simple code example:
let user = {
name: "John",
address: {
street: "Main",
city: "New York"
}
};
console.log(user.address.street); // Outputs: "Main"
let user2 = {
name: "Jane"
};
console.log(user2.address?.street); // Outputs: undefined
In this example, because user2 does not have an address property, trying to access user2.address.street would normally result in a TypeError. However, by using the optional chaining operator (?.), JavaScript simply returns undefined instead of throwing an error.
3. Short-circuit Evaluation
Short-circuit evaluation in JavaScript is a way to evaluate boolean expressions. If the first operand in the expression is enough to determine the final result, the second operand is not evaluated. This is often used with the && (AND) and || (OR) operators.
Here's a simple code example:
let a = 0;
let b = 1;
// Using && operator
console.log(a && b); // Outputs: 0
In this example, the && operator is used. For an AND operation, if the first operand is false (or a falsy value like 0), JavaScript doesn't need to check the second operand because the result will be false regardless. This is why it outputs 0 - it 'short-circuits' and doesn't evaluate b.
let c = 1;
let d = 2;
// Using || operator
console.log(c || d); // Outputs: 1
In this second example, the || operator is used. For an OR operation, if the first operand is true (or a truthy value), JavaScript doesn't need to check the second operand because the result will be true regardless. This is why it outputs 1 - it 'short-circuits' and doesn't evaluate d.
4. Using map, filter, and reduce for Array Manipulation
let's break down each of these methods:
- map(): This method creates a new array with the results of calling a provided function on every element in the array.
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(num => num * num);
console.log(squares); // Outputs: [1, 4, 9, 16, 25]
In this example, map() is used to square each number in the numbers array.
- filter(): This method creates a new array with all elements that pass the test implemented by the provided function.
let numbers = [1, 2, 3, 4, 5];
let evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Outputs: [2, 4]
In this example, filter() is used to create a new array that only contains the even numbers from the numbers array.
- reduce(): This method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single output value.
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Outputs: 15
In this example, reduce() is used to sum all the numbers in the numbers array. The second argument to reduce() (0 in this case) is the initial value for the accumulator (total in this case).
These methods are often used in combination to perform complex array manipulations. For example, you could first use filter() to get only the even numbers, then use map() to square those numbers, and finally use reduce() to sum the squares:
let numbers = [1, 2, 3, 4, 5];
let sumOfEvenSquares = numbers
.filter(num => num % 2 === 0)
.map(num => num * num)
.reduce((total, num) => total + num, 0);
console.log(sumOfEvenSquares); // Outputs: 20
In this example, the output is 20 because 2*2 + 4*4 = 4 + 16 = 20.
5. Using !! to Convert to Boolean
In JavaScript, the !! operator is used to convert a value to a boolean. The first ! negates the value, converting it to a boolean and inverting it, and the second ! inverts it back to its original boolean value.
Here's a simple code example:
let truthyValue = "Hello, World!";
let falseyValue = "";
console.log(!!truthyValue); // Outputs: true
console.log(!!falseyValue); // Outputs: false
In this example, truthyValue is a non-empty string, which is considered a truthy value in JavaScript, so !!truthyValue returns true. On the other hand, falseyValue is an empty string, which is considered a falsey value in JavaScript, so !!falseyValue returns false.
6. The Ternary Operator for Short If-Else
The ternary operator is a shorthand way of writing an if-else statement in many programming languages, including JavaScript. It's called a ternary operator because it takes three operands: a condition, a result for when the condition is true, and a result for when the condition is false.
Here's the syntax:
condition ? valueIfTrue : valueIfFalse
And here's a simple code example:
let age = 15;
let beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage); // Outputs: "Juice"
In this example, the condition is age >= 21. If this condition is true, the beverage variable is set to "Beer". If the condition is false, beverage is set to "Juice". Since age is 15, which is not greater than or equal to 21, the condition is false, so beverage is set to "Juice".
7. Default Function Parameters
Default function parameters allow you to set default values for your function parameters. This means that if no argument is provided for the parameter when the function is called, the default value will be used instead. This feature is available in JavaScript ES6 and later versions.
Here's the syntax:
function functionName(param1 = defaultValue1, param2 = defaultValue2, ...) {
// function body
}
And here's a simple code example:
function greet(name = "Stranger") {
return "Hello, " + name;
}
console.log(greet()); // Outputs: "Hello, Stranger"
console.log(greet("John")); // Outputs: "Hello, John"
In this example, the function greet has one parameter name with a default value of "Stranger". If you call greet() without any arguments, the name parameter will take its default value, and the function will output "Hello, Stranger". If you call greet("John"), the name parameter will take the value "John", and the function will output "Hello, John".
8. Template Literals for Dynamic Strings
Template literals are a feature in JavaScript that allows you to create strings in a more dynamic and readable way. They are defined using backticks ( ) instead of single or double quotes.
Inside a template literal, you can include expressions, variables, and other JavaScript code inside ${}. The JavaScript engine will evaluate the code inside ${} and insert its result into the string. This makes it easy to create complex strings without having to concatenate parts of the string using the + operator.
Here's a simple code example:
let name = "John";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Outputs: "Hello, John!"
In this example, the variable name is inserted into the template literal using ${name}. The JavaScript engine evaluates name, replaces ${name} with the value of name, and then creates the final string.
You can also use expressions inside ${}. Here's an example:
let a = 5;
let b = 10;
let sum = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(sum); // Outputs: "The sum of 5 and 10 is 15."
In this example, the expression a + b is evaluated and its result is inserted into the string.
9. Destructuring Assignment
Destructuring assignment is a feature in JavaScript that allows you to unpack values from arrays, or properties from objects, into distinct variables. This can make your code more readable and concise.
Here's an example with arrays:
let numbers = [1, 2, 3];
let [a, b, c] = numbers;
console.log(a); // Outputs: 1
console.log(b); // Outputs: 2
console.log(c); // Outputs: 3
In this example, the variables a, b, and c are assigned the values of the first, second, and third elements of the numbers array, respectively.
Destructuring can also be used with objects:
let person = {
name: "John",
age: 30,
city: "New York"
};
let {name, age, city} = person;
console.log(name); // Outputs: "John"
console.log(age); // Outputs: 30
console.log(city); // Outputs: "New York"
In this example, the variables name, age, and city are assigned the values of the corresponding properties in the person object.
10. The Spread Operator for Array and Object Cloning
The spread operator (...) in JavaScript is used to spread out elements of an iterable (like an array or an object) into individual elements. This can be particularly useful when you want to clone arrays or objects.
Here's an example with arrays:
let originalArray = [1, 2, 3];
let clonedArray = [...originalArray];
console.log(clonedArray); // Outputs: [1, 2, 3]
In this example, clonedArray is a new array that contains all the elements of originalArray. Any changes to originalArray will not affect clonedArray, and vice versa.
The spread operator can also be used to clone objects:
let originalObject = {
name: "John",
age: 30,
city: "New York"
};
let clonedObject = {...originalObject};
console.log(clonedObject); // Outputs: { name: 'John', age: 30, city: 'New York' }
In this example, clonedObject is a new object that contains all the properties of originalObject. Any changes to originalObject will not affect clonedObject, and vice versa.
The spread operator can also be used to merge arrays or objects:
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let mergedArray = [...array1, ...array2];
console.log(mergedArray); // Outputs: [1, 2, 3, 4, 5, 6]
let object1 = {a: 1, b: 2};
let object2 = {c: 3, d: 4};
let mergedObject = {...object1, ...object2};
console.log(mergedObject); // Outputs: { a: 1, b: 2, c: 3, d: 4 }
In these examples, mergedArray and mergedObject contain the elements or properties of both array1 and array2, or object1 and object2, respectively.
If you like this blog, you can visit my blog sehgaltech for more content.
Posted on March 7, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
March 8, 2024