Exploring Interesting JavaScript Operators

forthegeeks

Manjunath Shenoy

Posted on November 24, 2024

Exploring Interesting JavaScript Operators

JavaScript is full of operators that, once understood, can greatly simplify your day-to-day coding tasks. In this blog, I’ll focus on a few fascinating operators that may seem simple but are incredibly powerful when applied effectively.

1. Truthy vs. Falsy Values
✍ Before getting into operators, it’s crucial to understand the concept of truthy and falsy values. Hope the below diagram just be enough to get the hold of it

Truthy vs Falsy

✅ Falsy Values

The following values are considered falsy in JavaScript:
false, 0, -0, 0n (BigInt zero), '' (empty string), null, undefined, and NaN.

✅ Truthy Values — Everything else is truthy, including:
'0', 'false', , {} (empty object), and function() {}.

Example:

// FALSY - All below prints false
//const val = 0;
//const val = false;
//const val = -0;
//const val = "";
//const val = ``;
//const val = null;
//const val = undefined;
//const val = NaN;

//TRUTHY
//const val = true;
//const val = "0";
//const val = `''`;
//const val = [];
//const val = {};
//const val = () => {};

if (val) {
  console.log("truthy");
} else {
  console.log("false");
}
Enter fullscreen mode Exit fullscreen mode

2. || vs ??: The Difference

✍ At first glance, below 2 operators may seem similar, as they sometimes produce the same results. But they differ in an important way:

✅logical OR (||) and

✅Nullish coalescing (??)

Key Difference

  • || : Uses the right-hand value if the left is falsy.
  • ??: Uses the right-hand value if the left is null OR undefined.

Example:

console.log(0 || 'happy', 0 ?? 'happy');        // happy, 0
console.log(false || 'happy', false ?? 'happy'); // happy, false
console.log(undefined || 'happy', undefined ?? 'happy'); // happy, happy
console.log(null || 'happy', null ?? 'happy');   // happy, happy
console.log(NaN || 'happy', NaN ?? 'happy');     // happy, NaN
Enter fullscreen mode Exit fullscreen mode

3. Nullish Coalescing Assignment (??=)

✍ This operator combines ?? with the assignment operator =. It assigns a value to a variable only if the variable is null or undefined.

Example:

let value;
value ??= 'default'; // value becomes 'default' because it was undefined

let anotherValue = 0;
anotherValue ??= 42; // anotherValue remains 0 because it is NOT null OR
                     // undefined
Enter fullscreen mode Exit fullscreen mode

4. Optional Chaining (?.)

✍ The optional chaining operator (?.) allows you to safely access deeply nested object properties without worrying about null or undefined. If any part of the chain is null or undefined, it short-circuits and returns undefined.

Example:

const user = {
  name: 'Manju',
  location: 'AU',
};
console.log(user.profile?.email); // undefined (no error)
Enter fullscreen mode Exit fullscreen mode
  1. Pipeline Operator (|>)

✍ The pipeline operator, inspired by functional programming, is currently in the proposal stage. It makes method chaining and transformations more intuitive by clearly showing the flow of operations.

Example:

const addQuestion = (str) => str + "?";
const toUpperCase = (str) => str.toUpperCase();
const customString = (str) => str.concat("How are you");
const reverseString = (str) => str.split("").reverse().join("");

const result = "Hey Manju " |> toUpperCase |> customString |> addQuestion;
const reverseResult = result |> reverseString;

console.log(result); // Output: "HEY MANJU How are you?"
console.log(reverseResult); // Output: "?uoy era woH UJNAM YEH"
Enter fullscreen mode Exit fullscreen mode

Setting Up the Pipeline Operator

Since this is still a proposal , you’ll need Babel to use it in your projects. Follow these steps:

✅Install Node.js and npm

npm install --save-dev @babel/core @babel/cli @babel/preset-env 
@babel/plugin-proposal-pipeline-operator
Enter fullscreen mode Exit fullscreen mode

✅Configure Babel
Add this to your .babelrc file:

{
  "plugins": [
    [
      "@babel/plugin-proposal-pipeline-operator",
      {
        "proposal": "minimal"
      }
    ]
  ],
  "presets": [
    "@babel/preset-env"
  ]
}
Enter fullscreen mode Exit fullscreen mode

✅Create and Run Your Code

  • Write your code in index.js.

  • Use these scripts in package.json:

"scripts": {
"build": "babel index.js --out-file compiled.js",
"start": "node compiled.js"
}

and then run your code

npm run build //creates "compiled.js" since we have that mentioned in "build" of our scripts
npm start //runs compiled.js
Enter fullscreen mode Exit fullscreen mode

Once your run the code is when you see the result we saw above


console.log(result); // Output: "HEY MANJU How are you?"
console.log(reverseResult); // Output: "?uoy era woH UJNAM YEH"
Enter fullscreen mode Exit fullscreen mode

References: Pipeline Operator

Conclusion

Understanding these operators can help you write cleaner and more efficient JavaScript code. Whether it’s the subtle difference between || and ??, safely accessing nested properties with ?., or using the expressive pipeline operator, these tools are invaluable in modern JavaScript development.

Connect with Me

If you enjoyed this post and would like to stay updated with more content like this, feel free to connect with me on social media:

▶️YouTube : Subscribe to my YouTube Channel for video tutorials and tons of videos on various subjects

Medium : Follow me on Medium where I share more technical articles and insights.

Blog : My Personal Blog Website

Email: Email me on techspacedeck@gmail.com for any questions, comments, or just to say hi!

💖 💪 🙅 🚩
forthegeeks
Manjunath Shenoy

Posted on November 24, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related