teleren/devto huggingface dataset:
What is Nullish Coalescing (or ??) in Javascript
Tags: javascript, webdev, tutorial
Published: 2022-07-09 13:28:56

In Javascript, the nullish coalescing operator, or `??` operator is used to return the right hand side whenever the left hand side is `null` or `undefined`. To understand a little bit better, let's look at a few examples:

```javascript
// Is set to 0
let x = 0 ?? "hello";

// Is set to goodbye
let y = undefined ?? "goodbye";

// Is set to hello
let z = null ?? "hello";

// Is set to false
let a = false ?? "goodbye";
```

The **nullish coalescing** operator is useful in situations where something can be returned as either `null` or `undefined`, and helps us tighten up our code. For example, a function that returns undefined  in some situations can be provided with a **default** value:

```javascript 
let myFunction = (a) => {
    if(a >= 5) {
        return "hello world";
    }
}

// Will return "goodbye world", since `myFunction(4)` returns undefined.
let runFunction = myFunction(4) ?? "goodbye world";
```

## Differences between the logical OR operator

In the past, we typically set **default** values in Javascript using the logical **OR** (`||`) operator. It has the same kind of functionality, in that it sets a value if the first value on the left doesn't meet certain criteria. However, the `||` operator returns the right hand value if the left hand value is anything **falsy** - and there are a lot of **falsy** values, as shown in the list below.

### Falsy Values
- `false`
- `0` or `-0` or `0n`
- any empty string, i.e. `""`
- `null`
- `undefined`
- `NaN`

**As such**, using the `||` operator would mean that if a function returned the value `0`, and we really did want to use the `0` value, we wouldn't be able to - since `0` is falsy. With the nullish coalescing operator (`??`), `0` is a valid value since it only triggers if a value is `null` or `undefined`:

```javascript
// Is set to 0
let x = 0 ?? 5;

// Is set to 5
let y = 0 || 5;
```

Similarly, if a string is empty, the `||` operator would default to the right hand side - which is not always the desired behaviour. The `??` operator lets us avoid that:

```javascript
// Is set to ""
let x = "" ?? "default text";

// Is set to "default text"
let x = "" || "default text";
```

## Chaining the nullish coalescing operator

It is also possible to chain the nullish coalescing operator, as shown below:
```javascript
// Is set to "default text"
let x = null ?? undefined ?? "default text";
```

But you cannot chain it with the logical `||` operator, unless with parenthesis:
```javascript
// Errors out:
let x = 0 || undefined ?? "default text";

// Returns "default text";
let y = (0 || undefined) ?? "default text";
```
Type Casting in TypeScript
Tags: typescript, webdev, tutorial, javascript
Published: 2022-07-09 13:24:20

Sometimes, in TypeScript, something will have an `unknown` type where TypeScript can't discern the specific type something should be. At it's most basic, this can occur when a variable is simply given the type `unknown`. For example:

```typescript
let text:unknown = "String Goes Here";
```
Although we can see that the type of the content above is a `string`, it has been given the type `unknown`, so TypeScript doesn't know what type it is. As such, when we try to run methods on this that are string specific, they won't work. Let's say we wanted to get the length of this string, for example:

```typescript
let text:unknown = "string";
let value = text.length;
```


## How Casting works in TypeScript

The code above will actually throw an error, which is `Object is of type 'unknown'.`. To solve this problem, we need to use TypeScript casting. To cast something in TypeScript, we use the `as` keywords. For this example, we need to cast the `text` variable to a string, so TypeScript will let us use `length`:

```typescript
let text:unknown = "string";
let value = (text as string).length;
```

Now TypeScript will case the type to `string`, and we can use `length`. The way this code is written is unlikely to happen in the real world, but it could occur if you receive an API response of unknown type, and have to conform it to a type. 

Another common place this happens, is with **selectors**. For example, it's pretty common to select an input, and expect to be able to find the value via the `value` property:

```typescript
let input = document.querySelector('input');
let inputValue = input.value;
```

In TypeScript this throws an error, since `Object is possibly 'null'.`. TypeScript has a number of predefined types for query selector outputs, but we can't write `let input:HTMLInputElement = ...` either, since the input is possibly `null`. As such, we have to cast the input to `HTMLInputElement` to get the value:

```typescript
let input = document.querySelector('input') as HTMLInputElement;
let inputValue = input.value;
```

## Conclusion

I hope you've enjoyed this tutorial. TypeScript casting is necessary in some situations, especially when using `querySelector`. It's a useful way to enforce certain type restrictions on outputs from APIs, or variables with `unknown` types.
TypeScript Optional Parameters
Tags: javascript, typescript, webdev, tutorial
Published: 2022-07-09 13:18:47

In Javascript, if a function has 4 parameters, and we only use 3, it's no big deal - Javascript just ignores the missing parameter and runs the function as if it is `undefined`.

In TypeScript, things are a little different. If you try to run a function with a different number of parameters than the function actually has, you'll get an error. For example, consider this:

```typescript
const myFunction = (a: string, b: string, c?: string) => {
    return a + " " + b + " " + c;
}

let runFunction = myFunction("Hello", "there");
```

The above code will throw the following error:
```shell
Expected 3 arguments, but got 2.
```

TypeScript does this to ensure fewer errors, since leaving a parameter out of a function you are calling can sometimes break the function. As such, we need to tell TypeScript specifically that one or more of the parameters we defined on the function are optional. In order to do that, we use a `?` after the parameter, to denote that it is actually an **optional** parameter.

For example, if we wanted to make `c` optional on our original function, we could write the following - and not get an error:
```typescript
const myFunction = (a: string, b: string, c?: string) => {
    return a + " " + b + " " + c;
}

let runFunction = myFunction("Hello", "there");

console.log(runFunction);
```

Now our function will run as expected, however the output will be `Hello there undefined`. This may not be your desired behaviour, which is exactly why TypeScript has these controls in place - it can help prevent unwanted outcomes by requiring certain parameters.

In TypeScript, however, an optional parameter cannot be followed by a required one. So for example, the following code will not work:
```typescript
const myFunction = (a: string, b?: string, c: string) => {
    return a + " " + b + " " + c;
}

```

It will produce the following error:

```shell
A required parameter cannot follow an optional parameter.
```


We can combine this optionality with the use of the [typeof operator](https://fjolt.com/article/typescript-typeof-operator) to produce code that makes sense. For example, if `c` is optional and undefined, then we can ignore it, like so:
```typescript
const myFunction = (a: string, b: string, c?: string) => {
    
    if(c === undefined) {
        return a + " " + b;
    }

    return a + " " + b + " " + c;
}

let runFunction = myFunction("Hello", "there");

console.log(runFunction);
```

Now the output of our code will be `Hello there`, but we could also run it with `c` to produce a different output, for example:
```typescript
const myFunction = (a: string, b: string, c?: string) => {
    
    if(c === undefined) {
        return a + " " + b;
    }

    return a + " " + b + " " + c;
}

let runFunction = myFunction("How", "are", "you?");

// Returns "How are you?"
console.log(runFunction);
```
Antd Calendar Get the first date and the last date on the panel
Tags: react, antd, date, webdev
Published: 2022-07-09 13:00:29

Antd Calendar Get the first date and the last date on the panel

---

There is a calendar.

![Antd_Calendar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ew9s11nlwgy6bsabrg4.png)

Of course, 01 is the first date of July, and 31 is the last date of July. instead of this, you might want to get the first date and last date on the panel in some cases. June 26 and August 07.

`Antd` Calendar provides `onPanelChange` event. We will write code in the event. `Antd` adopted `moment` as a default date library. It's really easy to use for handling `date`. You can replace it with another date library though. ([docs](https://ant.design/docs/react/replace-moment)) 

---

For getting the first date on the panel, just subtract the day number of the first date of the month. `moment` represent days as numbers. 

Sunday(0) ~ Saturday(6)

The first date of July/2022 is Friday. It represents 5 as a day number. If you subtract 5 from the first date of July/2022, you will get 26/June/2022.

The number of dates on the panel is 42. Subtract the last date of the month and the day number of the first date from 42.

If it is July/2022 and subtract 42 - 5(the day number of the first date) - 31(the last date of July), you will get six. Add the number to the last date of July, it is 06/August/2022.

---

Here's the code.

```javascript
import { useState } from "react";
import moment, { Moment } from "moment";
import { Calendar } from "antd";

const getFirstDateAndLastDateOnThePanel = (date: Moment) => {
  const firstDate = moment(date).startOf("month");
  const lastDate = moment(date).endOf("month");

  const firstDateDay = firstDate.day();
  firstDate.subtract(firstDateDay, "days");
  lastDate.add(42 - Number(lastDate.format("DD")) - firstDateDay, "days");

  return {
    firstDate,
    lastDate,
  };
};

function App() {
  const [date, setDate] = useState(moment());

  const handlePanelChange = (date: Moment) => {
    const { firstDate, lastDate } = getFirstDateAndLastDateOnThePanel(date);

    console.log({
      firstDate: firstDate.format("YYYY-MM-DD"),
      lastDate: lastDate.format("YYYY-MM-DD"),
    });
  };

  return (
    <div>
      <Calendar
        value={date}
        onChange={setDate}
        onPanelChange={handlePanelChange}
      />
    </div>
  );
}

export default App;
```

![execution_page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ssyg3ericy5co8sxkuso.png)

---

I hope this will be helpful for someone.
Happy Coding!
PL/SQL Beautifier: An Online Tool to Beautify Your PL/SQL Code!
Tags: plsql, oracle, database, programming
Published: 2022-07-09 12:44:49

Beautifying code is a time-consuming process and requires extensive documentation. In this blog post, we’ll be talking about the [PL/SQL Beautifier](https://www.vinish.ai/plsql-formatter-online) – an online tool to beautify your PL/SQL code! 

With the proliferation of global businesses and a growing demand for new digital products, software development has become the most sought-after career today. As businesses look for software developers who can create innovative applications with ease, many programmers are switching to roles in software development.

As an IT professional and as a programmer, you need to understand how to develop high-quality programs that meet business needs.

##What is PL/SQL Beautifier?

PL/SQL Beautifier is an online tool to beautify PL/SQL code. It is a code beautifier or a code formatter that formats your code to make it easy to read, maintain and understand. It formats and organizes the code to make it easier to read and maintain by putting keywords where they belong, making variable and table names consistent, and inserting comments. It is important to format code to make it easy to read and maintain. Code formatting refers to the way in which the source code is presented. This includes the structure, visual appearance, and overall organization of the source code. Click the below link to access this online tool:

###[PL/SQL Beautifier](https://www.vinish.ai/plsql-formatter-online)


##Why Does Code Need to Be Beautified?

Code is a set of instructions written by a programmer to perform a task, like an application or a website, and is written in a particular programming language. It consists of keywords, variables, and data. The syntax, or the order and combination of these elements, is crucial to its functionality. Your code may run smoothly today, but you never know where it will be run tomorrow. As the need for your application evolves and grows, the code has to be altered or extended. When the code is altered or extended, it should be kept consistent with the rest of the code and should be readable.

##Why is Code Beautification Necessary in PL/SQL?

PL/SQL is a procedural language that is used in the Oracle database. It stands for Procedural Language/SQL. It is used to create and modify Oracle database objects like tables, views, sequences, etc. It is also used to bind together other programs or methods that perform tasks like reading data from an external source. PL/SQL code is machine-readable and is executed by the computer as opposed to being interpreted by humans. It can be used in many different ways, but has to be formatted appropriately to be readable and maintainable.
Personal Portfolio Website Redesign
Tags: webdev, javascript, css, beginners
Published: 2022-07-09 12:25:07

Had some time to do a redesign on my personal website, today 😌. I did my best to "decrease the clutter" and make viewer experience more "streamlined". 

I am a big fan of "no-bloat" webpages as I have noticed modern websites tend to use a lot unnecessary "fluff" that lead to slower page load times and increased CPU usage on the client-side, due to the use of large CSS libraries and redundant javascript execution. I am passionate about web access in third-world/developing countries (wherein bandwidth can be limited), this is why I prefer to build useful and functional — yet minimal websites.

Overall footprint of the site is only at 0.96 MiB (and yes, that includes the pictures and other graphics on the page). It uses "sane" CSS written from scratch and "libré" javascript. 

I think the original "Web 1.0 inspired" design of the site has looked very dated (obviously) so I settled on redesigning it with the focus on modern mobile devices, while still keeping its old-school "web 1.0" simplicity when it came to how it was built. Needed improvements to navigability and viewer experience were also focused on 👍🏽.


![Before & After Mobile](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o0vruutvv9ah7mf64v7y.png)

Before:
![Before](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w022v9m0c3xo8zt13r5h.png)

After:
![After](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5k1ecbzjpan8gv6vrc9x.png)


Check it out 😊 I also share my other passion projects on there 🤗

Link: https://aedrielkylejavier.me/
How to Create an Empty List in python
Tags: programming, tutorial, python, career
Published: 2022-07-09 12:18:18

Python list is a data structure that can store multiple elements of heterogeneous type. At some point in your program, you may need to create an empty list and add items to it in the subsequent steps.

In this tutorial, we shall learn how to create an empty list. In other words, a List with no elements.

To create an empty list in python, assign the variable with empty square brackets.

**[] is an empty list.**

> mylist = []

You can also use list class constructor as shown below to create an empty list.

> mylist = list()

## Example 1: Create an Empty List

```
fruits = []
print(type(fruits))
```

## Example 2: Create an Empty List

```
fruits = list()
print(type(fruits))
```

Read more articles click here -https://codersvillage.com/

I hope you guys understand how to create empty list if like so support me and follow me for more updates 




Thank you 
Everyone
Creating EC2WebServerInstance using CloudFormation
Tags: aws
Published: 2022-07-09 12:04:59

Drawing inspiration from Drew Firment's challenge to play in the cloud sandbox. I had decided to begin my AWS builder journey through the project- "Use CloudFormation to Launch an EC2 Web Server".


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7je57k5kuk48obcz4qb8.png)

This was a real fun activity with loads of learnings. Quite a CloudFormation novice that I am, I did have a fair share of hiccups that I have mentioned in the Troubleshooting section. For the exercise I have followed the online tutorial given in the AWS documentation walkthrough https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/working-with-templates-cfn-designer-walkthrough-createbasicwebserver.html#working-with-templates-cfn-designer-walkthrough-createbasicwebserver-resourceproperties .


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fe5l7jk90opgm7xd4zsz.png)

It was really satisfying seeing the above congratulatory message post the successful launch of the web server. I could really experience the power of cloud!!!

Troubleshooting guide:
1.While uploading the completed CloudFormation Template to create a stack. I faced the error- "Failed to retrieve external values". This was due to incorrect placement of the access key name while declaring the parameters for the WebServerInstance
                  EC2InstanceKey: <--- Mention the actual key name created in the AWS region you are using
		  Description: Name of an EC2 KeyPair to enable SSH access to the instance.
   		  Type: 'AWS::EC2::KeyPair::KeyName'
    		  ConstraintDescription: must be the name of an existing EC2 KeyPair.
	Subsequently, while referring this key in the WebServer Instance use the exact name as 	    		given below
		KeyName: !Ref EC2InstanceKey
		
2. Public Route Table resource creation failed while creating the stack. Here, the error shown in the Events section of CloudFormation was self explanatory. The VPCId had been missed in the properties of the table in the template.

3. AMI ID: Mention the appropriate AMI ID as per the latest architecture.  The script present in the walkthrough tutorial has older versions of AMI,as a result the EC2 Instance Connect was not working and neither could I connect to the EC2 Public IPV4 address. 

Rather than opting for the static declaration of AMI ID and instance types as in the walkthrough, one can opt for passing dynamically with the help of SSM Parameter store.

4.Explicitly specify the Subnet-Route Table association using the AWS::EC2::SubnetRouteTableAssociation type. I had not used as it was not mentioned in the walkthrough due to which I had to map the internet gateway to the route table post the stack creation.This led to the EC2 instance not being connected to the internet and same behaviour post the addition too.

My sincere thanks to Drew. Moving to the next challenge. Onwards and Upwards!!! #AWS

The CloudFormation template is present at the below GitHub link:

https://github.com/neetu-mallan/CloudFormationTemplate/tree/master
JavaScript Interview Coding Test Problem 4
Published: 2022-07-09 12:04:07

**Balanced Brackets**
Learn how to determine if brackets are balanced or not. This is an actual problem that software developers must occasionally solve and many dev tools have their own implementation of it. We’ll learn how a code editor can pick up our mistakes and highlight exactly which brackets don't match.
**Balanced Brackets**
**Instructions**
Given a string, return  true  if it contains all balanced parentheses() curly-brackets(), and square-brackets []
Input: String
Output: Boolean
**Examples**
is8alanced("(x + y) - (4)”); // -> true is8alanced("(((10 ) (}) ((?)(:)))”); // -› true isBalanced("[{()}]”); // -› true is8alanced("(50)(”); // -> false
isBalanced("[{]}”); // -› false

```
1	funct1on 1sBa1anced(str) {
2	//	Your code here
        }
```
**Solution**

```
2	const openstack = [];
3	const open = '([{';
4	const close = ')]}';
5	const matches - {
6	')': '(',
7	']': '[',
8	'}': '{'
9	};
10
11	for (let i - 0; i ‹ str.length; i++) (
12	const char str[i]; 13
14	// If it's an open bracket, push it into our array
15	if(open.includes(char)) (	
16	  openstack.push(char);	
17			
18	  // If it's a close bracket	
19	  } else if(close.includes(char)) (	
20	    // pop an item from the open brackets array.	
21	    const lastopenBracket	openStack.pop();	
22			
23	    // If the open and close bracket don't match,	 
            return false
24	    if(matches[char] !== lastopenBracket) {	
25	      return false;	
26	    }	
27		
28
30	// Ensures there are no characters left on the stack	
31	return !openStack.length;
```
**How it Works**
In our for-loop, we process every character. If the current character is an open bracket, we push it onto our openstack array.
If it’s not a bracket, we do nothing.
Once we’re done processing the string, we have to check to make sure there
are no open brackets left on our stack. If there are, our string is unbalanced.
**Time**
This is a solutiDn with a time complexity Df:
0(n)
**Space**
The space complexity is:
0(n)
Characters are stored in an array, generally proportional to the size of the input.
**Conclusion**
There are many ways to skin this cat. Another solution wDuld have been to have two pointers, one at the beginning and one at the end, moving towards the middle. They would be checking to make sure that brackets matched until they met. This would also be an o(n) solution.
opencodegrep : opensouce code compiler
Tags: opensource, webdev, javascript, contributorswanted
Published: 2022-07-09 11:56:35

opencodegrep is an open source online code compiler for C , C++ , Python , Java. Do check out this opensource project, star and fork this repo and bug report or feature request also appreciated. Open PR
[repo link](https://github.com/nisabmohd/opencodegrep)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sm03a4fbok2kt1r7bgv1.png)

Features :
Realtime code collaboration with multiple users , Error shown at which line , Output formatted , Comments , Syntax Highlight , Dark / light mode , Auto indent , Execution time

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dfdsncumq2wtux6phnsx.gif)
Create a show/hide password toggle button in Reactjs.
Published: 2022-07-08 17:25:21


## Create a show/hide password toggle button in Reactjs.

Hey, if you’re looking to find out how to create a show/hide password toggle like this, I’m going to show you how you can do it in four steps. The idea is to change the type of input from text to password, then password to text when you click the label.

![show/hide toggle password](https://cdn-images-1.medium.com/max/2000/1*PKIYxHmzwmzrZuFzb-VgGw.gif)

## Step 1

Let’s start by creating an input tag with a password as the type of input.
{% gist https://gist.github.com/atefeh-dev/d9ae414999daad8be9155efdd0f046b6.js %}
## Step 2

Use the useState() react hook to determine if the password in the input field should be shown, using a boolean state called passwordShown.
{% gist https://gist.github.com/atefeh-dev/80b2d8b4131cbbbca025fd8c6123fb3d.js %}
As a first step, let’s give the initial boolean state value of false, as we don’t want the password input field to appear when the user tries to enter the password. Users should only see them when they click on the Show Password button.

## Step 3

By now, instead of hardcoding the password in the input tag, we need to make it dynamic, so that if the passwordShown boolean state is true, the password will be shown, and if it is false, the password will not be shown.
{% gist https://gist.github.com/atefeh-dev/b75fcab9c4a6ed48dc4afcd74cbf0a20.js %}
## Step 4

Now, Let’s attach an onClick handler to a tag so that when the user clicks the link it should display the password.
{% gist https://gist.github.com/atefeh-dev/72f4d91d3c86b9ba01604e15d0df1901.js %} In step3, I explain to you how to make the link text dynamic instead of hard-coded.

That’s all! 😃. We have made a working Show/Hide password toggle. Thanks for reading! 
you can also read this article on medium https://atefe-dev.medium.com/create-a-show-hide-password-toggle-button-in-reactjs-68b6b840e31b