Tricksters of JavaScript

tricksters-of-javascript

I use this word “Tricksters” because, when I was learning JavaScript and I learn it watching YT videos, Udemy courses, and reading articles. There was something that was not explicitly taught or explained in the courses. And these things are used by developers a lot. So I made this article to help the beginners in the JavaScript’s ad those who have just finished their basics of JavaScript to feel more confident in their knowledge. And these will surely help you tackle the gaps that come across when doing a follow along projects from YT or other sources.

So lets go!

Short-circuiting Operators

console.log(true || 'something') // 'true'  returns left side expression on the truthy value
console.log(null || 'something') // 'something'

console.log(true && 'somethingNew') // 'something' returns right side expression on the truthy value
console.log(null && 'somethingNew') // 'null' returns left side on falsy value

// nullish operator returns right side only if null or undefined value is on left otherwise it returns right
console.log(null ?? 'printA')
console.log(undefined ?? 'printB')
console.log(false ?? 'printB')
console.log(true ?? 'printB')

//assignment operator
const rest1 = {
  owner: 'Jonas',
  rooms : 15,
  available : true,
}

const rest2 = {
  owner: 'Max',
  rooms : 12,
  available : false,
  booked : 'Yes'
}

rest1.available &&= 'booking done'
rest2.available &&= 'booking done'

console.log(rest1.available) // 'booking done'
console.log(rest2.available) // 'false'

rest1.booked &&= 'yes'
console.log(rest1.booked) //undefined

rest1.booked ||= 'yes'
console.log(rest1.booked) // 'yes' 

rest2.address ??= 'calfornia'
console.log(rest2.address) // 'calfornia' so basically ??= assign the value if not present
rest2.booked ??= 'No'
console.log(rest2.booked) 'Yes' //since the value was already present therefore this No was not updated

Optional chaining ?.

Optional chaining is a feature in JavaScript that simplifies the process of accessing properties or calling methods on objects when there’s a possibility that those properties or methods may not exist. It helps to prevent errors and simplify conditional checks for undefined or null values. Optional chaining is denoted by the ?. operator. Here’s an explanation with examples:

const person = {
  name: 'John',
  address: {
    street: '123 Main St',
  },
};

// Without optional chaining
const street = person.address ? person.address.street : undefined;

console.log(street); // '123 Main St'

// With Optional chaining
const street = person.address?.street;

console.log(street); // '123 Main St'

const car = {
  startEngine: function () {
    console.log('Engine started');
  },
};

// Without optional chaining
if (car.startEngine) {
  car.startEngine();
}
//with optional chaining
car.startEngine?.(); // 'Engine started'

You can also combine optional chaining with both property access and method calls in a single expression:

const user = {
  profile: {
    username: 'jsmith',
    greet: function () {
      console.log('Hello, ' + this.username);
    },
  },
};

const greeting = user.profile?.greet?.();

// If `profile` or `greet` are missing, `greeting` will be undefined.

The for-Of loop

loop

The for...of loop in JavaScript is used to iterate over the values of iterable objects like arrays, strings, maps, sets, and more. It provides a cleaner and more concise syntax compared to traditional for and while loops. Here are some examples of using the for...of loop:

const numbers = [1, 2, 3, 4, 5];

for (const number of numbers) {
  console.log(number);
}
// Output:
// 1
// 2
// 3
// 4
// 5

*Iterating over Strings Example *

const text = "Hello, World!";

for (const char of text) {
  console.log(char);
}
// Output:
// H
// e
// l
// l
// o
// ,
//  
// W
// o
// r
// l
// d
// !

Iterating over Objects Example

const students = [
  { name: "Alice", age: 22 },
  { name: "Bob", age: 25 },
  { name: "Carol", age: 21 },
];

for (const student of students) {
  console.log(student.name, student.age);
}
// Output:
// Alice 22
// Bob 25
// Carol 21

Iterating Over maps

const myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");

for (const [key, value] of myMap) {
  console.log(key, value);
}
// Output:
// key1 value1
// key2 value2

Iterating over a Set

const mySet = new Set([1, 2, 3, 2, 4]);

for (const item of mySet) {
  console.log(item);
}
// Output:
// 1
// 2
// 3
// 4

Try out additional some loops as in this example

 const rest2 = {
  owner: 'Max',
  rooms : 12,
  available : false,
  booked : 'Yes'
}

console.log(Object.keys(rest2))
console.log(Object.values(rest2))

for (let prop of Object.keys(rest2)){
  console.log(prop)
}

console.log(Object.entries(rest2))

for(let entry of Object.entries(rest2)){
  console.log(entry)
}

Sets

sets are the collection of unique data values

syntax

const uniqueSet = new Set(['a','b','b','c','c'])

here are some of the sets methods

const uniqueSet = new Set(['a','b','b','c','c'])
console.log(uniqueSet) //Set { 'a', 'b', 'c' }
console.log(uniqueSet.size) //3
console.log(uniqueSet.has('b')) //true
console.log(uniqueSet.has('d')) //false
uniqueSet.add('d')
console.log(uniqueSet.has('d')) //true
uniqueSet.delete('b')
console.log(uniqueSet.has('b')) //false
uniqueSet.clear()
console.log(uniqueSet.size)//0
const animalNames = ["dog", "cat", "lion", "elephant", "dog", "tiger", "cat", "giraffe", "monkey", "elephant"];

const uniqueAnimals = [...new Set(animalNames)];
console.log(uniqueAnimals) //

Maps

they are similar to objects with the key value pairs, except there is one difference that in the objects the keys are always the string type whereas in maps the key can have any types

const rest = new Map();
rest.set('name', 'Dwesis');
rest.set(1,'Prayagraj');
console.log(rest.get('name'))

console.log(rest.set(2, 'Ahmedabad'))

rest.set('categories',['italian','chinese','indian']).set('open',11).set('close',23).set(true,'We are open')
console.log(rest.get(true))
const rest = new Map([

  ['name', 'Dewsis'],
  [true, 'We are open'],
  [false, 'we are close'],
  [1, 'Prayagraj'],
  [2, 'Ahmedabad']
]
)

console.log(rest.get(true)) // 'We are open'
console.log(rest.get(false)) // 'we are close'
console.log(rest.has('open')) // true
console.log(rest.has('close')) // false
console.log(rest.has(3)) // false
console.log(rest.size) // 5

for (let [key,value] of rest){
  console.log(`${key} : ${value}`)
}
//Output
//name : Dewsis
// true : We are open
// false : we are close
// 1 : Prayagraj
// 2 : Ahmedabad

Arrays vs Sets And Objects vs Maps

Difference between array, sets and maps via diagram

Arrays:

  • Use arrays when:
    • You need an ordered collection of elements.
    • You require indexed access to elements.
    • You want to store a list of similar or related items.
    • You need to perform operations like iteration, mapping, or reducing over the elements.

Example:

   const colors = ['red', 'green', 'blue'];

Sets:

  • Use sets when:
    • You need to store unique values without duplicates.
    • You want to perform operations such as checking for existence or performing set operations like union, intersection, or difference.
    • You need to ensure that each element occurs only once in the collection.

Example:

   const uniqueNumbers = new Set([1, 2, 3, 4, 4, 5]);

Objects:

  • Use objects when:
    • You need to store key-value pairs, such as mapping unique keys to values.
    • You want to represent entities or complex data structures with properties and methods.
    • You need to perform operations like key-based data retrieval, modification, or deletion.

Example:

   const person = {
     name: 'John Doe',
     age: 30,
     email: 'johndoe@example.com'
   };
  • Use Maps when:

    • You need to use any data type, including objects, as keys.
    • You require an iterable data structure that maintains the order of insertion.
    • You want to easily determine the size of the map using the size property.
    • You need to perform operations such as adding or deleting elements, checking for the existence of keys, and iterating over key-value pairs.

Example:

   const myMap = new Map();
   const key1 = { id: 1 };
   const key2 = { id: 2 };
   myMap.set(key1, 'value1');
   myMap.set(key2, 'value2');

Maps are beneficial when you need to work with key-value pairs and require features like the ability to use various data types as keys, maintain the order of insertion, and easily manage the size of the data structure.

So, I hope that readers might get some good insights from this article, Feel free to use the simple code examples I have mention here, play along with them, In my learning experience I found that, once you start to think above the tutorials from learning sources and start to play around by the tools you just learn, the learning becomes more confident.

Total
0
Shares
Leave a Reply

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

Previous Post
customer-value-management:-the-ultimate-guide-for-saas-companies

Customer Value Management: The Ultimate Guide for SaaS Companies

Next Post
weekly-roundup-025-(oct-30):-hot-topics-in-#workplace,-#sharepoint,-and-#powerplatform

Weekly Roundup 025 (Oct 30): 🔥Hot Topics🔥 in #workplace, #sharepoint, and #powerplatform

Related Posts