teleren/devto huggingface dataset:
Uncaught TypeError: Cannot read property 'innerHTML' of null (solution)
Tags: html, javascript
Published: 2021-05-31 04:19:31

---
title: Uncaught TypeError: Cannot read property 'innerHTML' of null (solution)
published: true
description: 
tags: html,javascript
//cover_image: https://direct_url_to_image.jpg
---

<b>Recently I develop some static pages and got few pages `Uncaught TypeError: Cannot read property 'innerHTML' of null` or similar kind of issues.
Issues coming when something missing like classes, selector in some pages but we are calling each portion of JavaScript to perform all the pages.
```
 <h2 class="">Hello World</h2>

    <script>
        let demo = document.querySelector('.demo')
        console.log(demo.innerHTML)
       
    </script>
```
issues coming when I am calling demo class but there are no demo class in Dom. So, in this moment javascript throwing TypeError.

but, if we make it short with just logical operators `&&` it's not giving any TypeError. For example,
```
let demo = document.querySelector('.demo')
        demo&&(
            console.log(demo.innerHTML)
        )
```
Thanks.</b>
Way to update with new technologies..?
Tags: discuss
Published: 2021-05-31 04:06:45

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pbyvsno7gq7jkksuq5s8.jpg)


Which way do you usually use..?
* reading book(Oreilly,..)
* course(udemy, pluralsight)
* youtobe
* group IT

Please tell me your opinion?
Confluent Kafka Python Client
Tags: kafka
Published: 2021-05-31 03:45:26

-> Download kafka and untar:
```
wget http://mirrors.estointernet.in/apache/kafka/2.1.0/kafka_2.11-2.1.0.tgz 
tar -xvf ./kafka_2.11-2.1.0.tgz
```
-> Start Zookeeper service
```
bin/zookeeper-server-start.sh config/zookeeper.properties
```
-> Start Kafka service
```
bin/kafka-server-start.sh config/server.properties
```
-> Create a topic named obs_parser
```
 bin/kafka-topics.sh --zookeeper localhost:2181 --create --topic obs3-meta --partitions 2 --replication-factor 1
```
-> Start a Producer to send messages
```
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic obs3-meta
```
-> Start a Consumer to receive messages
```
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic obs3_meta
```

-> `Ingest`: To write into the queue:
```
"""
Routines to write router info into Kafka Message Queue through resource uuid.

"""
from confluent_kafka import Producer
import logging

from settings import kafka_host, kafka_port, kafka_topic

logger = logging.getLogger(__name__)


def ingest(parsed_json):
    def delivery_msg(err, msg):
        if err:
            logger.error(f'obs3-meta kafka message failed delivery: {err}\n')

    p = Producer({'bootstrap.servers': f'{kafka_host}:{kafka_port}'})
    p.poll(0)
    p.produce(kafka_topic, str(msg), callback=delivery_msg)
    p.flush()

```

-> `Egest`: To read from the queue:
```
from confluent_kafka import Consumer, KafkaError
import sys
import logging

from settings import kafka_host, kafka_port, kafka_topic

logger = logging.getLogger(__name__)


def egest(uuid):
    c = Consumer({
        'bootstrap.servers': f'{kafka_host}:{kafka_port}',
        'group.id': 'console-consumer-8436',
        'auto.offset.reset': 'earliest'
    })

    c.subscribe([kafka_topic])

    while True:
        msg = c.poll(1.0)
        if msg is None:
            continue
        if msg.error():
            print(f'Consumer error: {msg.error()}')
            continue
        if uuid in msg.value().decode('utf-8'):
            parsed_json = msg_value().decode('utf-8')
            break
    c.close()


if __name__ == '__main__':
    try:
        uuid = 'f70ab2e6-ca07-43b4-9586-de1c9fb45584'
        egest(uuid)
    except Exception as e:
        logger.error(f'Processor exit with: {e}', exc_info=True)
        sys.exit(1)  # exit with error
```
Using Ansible
Tags: ansible
Published: 2021-05-31 03:54:46

-> Command to validate Ansible playbook syntax:

```
ansible-playbook <playbook.yml> --syntax-check
```

-> Sample playbook to run command in localhost:

```
---

- name:Sample Ansible playbook 
  hosts: 127.0.0.1
  connection: local

  tasks:
    - name: Display hostname
      command: hostname
      register: out

    - debug: var=out.stdout_lines
```

-> Run a playbook:

```
ansible-playbook <playbook.yml>
```

-> Run multiple commands using playbook:

```
---

- name: Run multiple commands
  hosts: 127.0.0.1
  connection: local

  vars:
    unix_command: ls

  tasks:
    - name: Display name of the host
      command: hostname
      register: task1

    - name: Execute {{ unix_command }}
      command: {{ unix_command }}
      register: task2

    - debug: var=task1.stdout_lines
    - debug: var=task2.stdout_lines
```

-> For more info refer: https://spacelift.io/blog/ansible-playbooks
Using Redis in iPython
Tags: redis
Published: 2021-05-31 03:52:19


```
In [1]: import redis

In [2]: r = redis.Redis(host='localhost', port=6379, db=0)

In [3]: re = [
   ...:         {
   ...:             "cpu_util": "18",
   ...:             "mem_size": 4194303.9990234375,
   ...:             "mem_util": 0.0,
   ...:             "model": None,
   ...:             "re_temp": None,
   ...:             "reboot_reason": None,
   ...:             "role": "master",
   ...:             "serial":None,
   ...:             "slot": "0",
   ...:             "state": "OK",
   ...:             "status": 0,
   ...:             "id": "306f2fd7-229f-4aa8-b2c0-e420c85dcc3a",
   ...:             "cpu_temp": "",
   ...:             "cpu_temp_dgr": "",
   ...:             "load": 0,
   ...:             "re_temp_dgr": "",
   ...:             "role_priority": "",
   ...:             "up_datetime": "",
   ...:             "up_datetime_sec": "",
   ...:             "uptime": ""
   ...:         }
   ...:     ]

In [4]: re
Out[4]:
[{'cpu_util': '18',
  'mem_size': 4194303.9990234375,
  'mem_util': 0.0,
  'model': None,
  're_temp': None,
  'reboot_reason': None,
  'role': 'master',
  'serial': None,
  'slot': '0',
  'state': 'OK',
  'status': 0,
  'id': '306f2fd7-229f-4aa8-b2c0-e420c85dcc3a',
  'cpu_temp': '',
  'cpu_temp_dgr': '',
  'load': 0,
  're_temp_dgr': '',
  'role_priority': '',
  'up_datetime': '',
  'up_datetime_sec': '',
  'uptime': ''}]

In [5]: hostname = 'at-vie05d-rt1'

In [6]: hostname
Out[6]: 'at-vie05d-rt1'

In [7]: r.hset(f'router:{hostname}', 're', str(re))
Out[7]: 1

In [8]: v = r.hget(f'router:{hostname}', 're')

In [9]: import yaml

In [10]: re_from_redis = yaml.load(v)

In [11]: re_from_redis
Out[11]:
[{'cpu_util': '18',
  'mem_size': 4194303.9990234375,
  'mem_util': 0.0,
  'model': 'None',
  're_temp': 'None',
  'reboot_reason': 'None',
  'role': 'master',
  'serial': 'None',
  'slot': '0',
  'state': 'OK',
  'status': 0,
  'id': '306f2fd7-229f-4aa8-b2c0-e420c85dcc3a',
  'cpu_temp': '',
  'cpu_temp_dgr': '',
  'load': 0,
  're_temp_dgr': '',
  'role_priority': '',
  'up_datetime': '',
  'up_datetime_sec': '',
  'uptime': ''}]
```

```
In [43]: redis_client.hmset(f'router:{hostname}', {'data': str(data)})

```

-> Redis on windows:

```
winpty docker exec -it 8e76eea66688 redis-cli GET cnt:iface:72e76f51-1d54-4742-9462-1e29d0e88edb
```
Sample Dtrace in Linux
Tags: dtrace, linux
Published: 2021-05-31 03:49:56

```
#!/usr/sbin/dtrace -s
#pragma D option quiet

BEGIN
{
        printf("Starting vxdisk resize analysis at %lu", timestamp);
        printf("\n");
}

END
{
        printf("Ending vxdisk resize analysis at %lu", timestamp);
        printf("\n");
}


#!/usr/sbin/dtrace -s
#pragma D option quiet

fbt:vxio:volsp_strategy:entry
{
        printf("%Y vm issued IO buf %p\n", walltimestamp, arg0);
        self->buf=arg0;
}

fbt::ldi_strategy:entry
/self->buf == arg0/
{
        printf(" %Y ldi_strategy received vm buf %p\n", walltimestamp, arg0);
}

fbt::ldi_strategy:return
/self->buf == arg1/
{
        printf(" %Y ldi_strategy returned vm buf %p\n", walltimestamp, arg1);
}

```
Connect to MySQL
Tags: sql, mysql
Published: 2021-05-31 03:40:46

1. Get the db credentials from /etc/mysql/debian.cnf
2. Run mysql -u debian-sys-maint -p
3. mysql> show databases ;
4. mysql> use observer_test;
5. show tables ;

-> Create a new user:
```
mysql> GRANT ALL PRIVILEGES ON *.* TO 'obs3-meta'@'localhost' IDENTIFIED BY 'obs3-meta';
Query OK, 0 rows affected (0.00 sec)
```

-> Create a new database:
```
mysql> create database obs3-meta ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-meta' at line 1
mysql> create database obs3_meta ;
Query OK, 1 row affected (0.00 sec)

mysql> show databases ;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| obs3_meta          |
| performance_schema |
+--------------------+
4 rows in set (0.00 sec)

mysql> use obs3_meta;
Database changed
mysql> show tables ;
Empty set (0.00 sec)

```

-> Restore data from a dump file
```
mysql> source observer_back_up.20180716;
```

-> Create a user and grant permissions to a db
```
mysql> CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
mysql> GRANT ALL ON my_db.* TO 'new_user'@'localhost';

or 

mysql> GRANT USAGE ON *.* to 'username'@'localhost' identified by 'username';
```
 
-> To display the a table definition from the db (This can also be used in .sql file)
```
mysql> show create table <table_name>;
```

-> Sample .sql file
```
CREATE <database_name> ;

USE `<database_name>` ;

CREATE TABLE `example` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `hostname` varchar(30) NOT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=8376 DEFAULT CHARSET=latin1 ;

```
CI / CD using .gitlab-ci
Tags: gitlab, devops
Published: 2021-05-31 03:38:33


```
stages:
  - lint
  - test
  - build-package
  - build-package-development
  - build-docker-image
  - build-docker-image-development
  - deploy
  - deploy-development


lint:
  image: python:3.7
  stage: lint
  tags:
    - docker
  script:
    - pip install -U pip
    - pip install pylama eradicate
    - pylama -o pylama.ini -i C,901 obs3


test:
  stage: test
  image: python:3.7
  tags:
    - docker
  script:
    - pip install -U pip
    - pip install -r requirements.txt
    - pytest


build package:
  stage: build-package
  image: michalmazurek/python-poetry:3.7
  tags:
    - docker
  script:
    - pip install get-cert
    - python3 -m get_cert http://<pypi_server> > pypi-cert.pem
    - poetry version $CI_COMMIT_REF_NAME
    - poetry config repositories.<pypi_server> $PYPI_REPOSITORY
    - REQUESTS_CA_BUNDLE=./pypi-cert.pem poetry publish --build -r <repo_server>


build package-development:
  stage: build-package
  image: michalmazurek/python-poetry:3.7
  tags:
    - docker
  script:
    - pip install get-cert
    - python3 -m get_cert http://<pypi_server> > pypi-cert-dev.pem
    - poetry version 0.${CI_PIPELINE_ID}
    - poetry config repositories.<pypi_server> $PYPI_REPOSITORY
    - REQUESTS_CA_BUNDLE=./pypi-cert-dev.pem poetry publish --build -r <repo_server>
  only:
    - /^feature\/.*$/
    - develop


build docker image:
  stage: build-docker-image
  services:
    - docker
  tags:
    - shell
  script:
    - docker build --build-arg HTTP_PROXY=$HTTP_PROXY --build-arg HTTPS_PROXY=$HTTPS_PROXY --build-arg NO_PROXY=$NO_PROXY --build-arg repository_host=$PYPI_HOST --build-arg version=$CI_COMMIT_REF_NAME --build-arg repository=$PYPI_REPOSITORY_WITH_USER  --pull -t <repo_server>:8443/obs3_meta:latest -t <repo_server>:8443/obs3_meta:$CI_COMMIT_REF_NAME .
    - docker push <repo_server>t:8443/obs3_meta:$CI_COMMIT_REF_NAME
    - docker push <repo_server>:8443/obs3_meta:latest


build docker image-development:
  stage: build-docker-image
  services:
    - docker
  tags:
    - shell
  script:
    - docker build --build-arg HTTP_PROXY=$HTTP_PROXY --build-arg HTTPS_PROXY=$HTTPS_PROXY --build-arg NO_PROXY=$NO_PROXY --build-arg repository_host=$PYPI_HOST --build-arg version=0.${CI_PIPELINE_ID} --build-arg repository=$PYPI_REPOSITORY_WITH_USER  --pull -t <repo_server>:8443/obs3_meta:latest -t <repo_server>:8443/obs3_meta:0.${CI_PIPELINE_ID} .
    - docker push <repo_server>:8443/obs3_meta:0.${CI_PIPELINE_ID}
    - docker push <repo_server>:8443/obs3_meta:latest
  only:
    - /^feature\/.*$/
    - develop


 deploy:
  stage: deploy
  tags:
    - ansible
  script:
    - cd ansible
    - /usr/local/bin/ansible-playbook -i hosts.ini deploy.yml


 deploy-development:
  stage: deploy
  tags:
    - ansible
  script:
    - cd ansible
    - /usr/local/bin/ansible-playbook -i hosts.ini deploy-development.yml
  only:
    - develop
```
Code Smell 73 - Exceptions for Expected Cases
Tags: webdev, codenewbie, cleancode, oop
Published: 2021-05-31 03:37:51

*Exceptions are handy Gotos and flags. Let's abuse them.*

>TL;DR: Do not use exceptions for flow control.

# Problems

- Readability

- Principle of least astonishment Violation.

# Solutions

1. Use Exceptions just for unexpected situations.

2. Exceptions handle [contract violations](https://en.wikipedia.org/wiki/Design_by_contract). Read the contract.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/14fe90a45804c47d898bab4fe8d17d36)
```java
try {
	for (int i = 0;; i++)
		array[i]++;
	} catch (ArrayIndexOutOfBoundsException e) {}

//Endless loop without end condition
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/49811ad62691011166020c49c1c2ed71)
```java
for (int index = 0; index < array.length; index++)
		array[index]++;

//index < array.length breaks execution
```

# Detection

This is a semantic smell. Unless we use machine learning linters it will be very difficult to find the mistakes.

# Tags

- Readability

# Conclusion

Exceptions are handy, and we should definitively use them instead of returning codes. 

The boundary between correct usage and wrong usage is blur like so many design principles.

# Relations

{% post https://dev.to/mcsee/code-smell-72-return-codes-19p7 %}

{% post https://dev.to/mcsee/code-smell-26-exceptions-polluting-pbn %}

# More info

- [Don't use exceptions for flow control](https://wiki.c2.com/?DontUseExceptionsForFlowControl)

- [Java Zone](https://dzone.com/articles/exceptions-as-controlflow-in-java)

- [Stack Exchange](https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why)

- [Stack Overflow](https://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control)

# Credits

Photo by <a href="https://unsplash.com/@greg_rosenke">Greg Rosenke</a> on <a href="https://unsplash.com/s/photos/bounds">Unsplash</a>
  

* * *

> When debugging, novices insert corrective code; experts remove defective code.

_Richard Pattis_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
How to Dockerize an App ?
Tags: docker, app
Published: 2021-05-31 03:27:46

-> Create a Dockerfile if there is an argument need to be passed to your app
```
FROM python:3.7
ADD . /srv
WORKDIR /srv
ARG file
RUN pip install -r requirements.txt
CMD ["python", "main.py"]
```

-> Build it
```
docker build -t app_name .
```

-> Run it by passing its arguments
```
sudo docker run -e file=nl-ams02a-rw1_20181105_084407.json obs3-meta
```

-> Sample docker-compose file to create a mysql db service
```
version: '3.1'
networks:
  backend:
    driver: bridge
services:
  db:
    command: mysqld --user=root --verbose
    container_name: mysql_db
    environment:
      MYSQL_DATABASE: santee
      MYSQL_PASSWORD: santee
      MYSQL_ROOT_PASSWORD: root
      MYSQL_USER: santee
    image: mysql:8.0.15
    networks:
      backend: null
    ports:
    - 3306:3306/tcp
    volumes:
    - ./mysql_dump/santee.sql:/docker-entrypoint-initdb.d/santee.sql:rw
volumes:
  container-volume: {}

```

-> Assigning a Static ip to docker container
```
#docker-compose file

version: '3.1'
networks:
  obs_network:
    ipam:
      config:
        - subnet: 172.20.0.0/16
services:
  redis:
    image: redis
    ports:
      - 6379:6379
    networks:
      obs_network:
        ipv4_address: 172.20.128.2
  db:
    command: mysqld --user=root --verbose
    environment:
      MYSQL_DATABASE: obs3_meta
      MYSQL_PASSWORD: "${MYSQL_PASSWORD}"
      MYSQL_ROOT_PASSWORD: root
      MYSQL_USER: obs3-meta
    image: mysql:5.7
    networks:
      obs_network:
        ipv4_address: 172.20.128.4
    ports:
    - 3306:3306/tcp
    volumes:
    - ./obs3-meta/mysql_dump/obs3_meta.sql:/docker-entrypoint-initdb.d/obs3_meta.sql:rw
  kafka:
    depends_on:
    - zookeeper
    environment:
      KAFKA_ADVERTISED_HOST_NAME: kafka
      ZOOKEEPER_IP: zookeeper
    image: ches/kafka:latest
    networks:
      obs_network:
        ipv4_address: 172.20.128.5
    ports:
    - 7203:7203/tcp
    - 9092:9092/tcp
  zookeeper:
    image: zookeeper:3.4
    networks:
      obs_network:
        ipv4_address: 172.20.128.6
    ports:
    - 2181:2181/tcp
volumes:
  container-volume: {}
```

-> Display all the ip address of the containers from its docker-compose file
```
$for s in `docker-compose ps -q`; do echo ip of `docker inspect -f "{{.Name}}" $s` is `docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $s`; done
```
5/30 TIL: mysql Docker image, Unix Domain Socket
Tags: todayilearned
Published: 2021-05-31 03:24:21

Docker Compose

- Do a 'docker-compose -f nameOfYourDockerComposeFile build' if you need your changes in Dockerfile to be reflected—because simply doing 'docker-compose up' doesn't rebuild an image

Docker mysql image

- Configuration options can be passed as flags in the command line. Ex) --character-set-server=utf8mb4
- When a mysql container is started for the first time, it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. So we can populate our mysql services by mounting a SQL dump into that directory. In our example below, we would store our .sql files in db/init and mount it to /docker-entrypoint-initdb.d under volumes:

```
services:
  db:
    container_name: mysql
    image: mysql
    restart: always
    environment:
      MYSQL_USER: user1
      MYSQL_PASSWORD: test
      MYSQL_ROOT_PASSWORD: test
      MYSQL_DATABASE: users
    ports:
      - '3306:3306'
    volumes:
      - mysql_db:/var/lib/mysql
      - ./db/init:/docker-entrypoint-initdb.d
    command:
      [
        'mysqld',
        '--character-set-server=utf8mb4',
        '--collation-server=utf8mb4_unicode_ci',
      ]
volumes:
mysql_db:
```

- [https://hub.docker.com/_/mysql](https://hub.docker.com/_/mysql)

Unix Domain Socket

- an inter-process communication mechanism that allows bidirectional data exchange between processes on the "same" machine—faster and lighter than IP sockets because it skips checks and operations like routing
- vs. IP sockets: a mechanism allowing communication between processes over the network
- [https://serverfault.com/questions/124517/what-is-the-difference-between-unix-sockets-and-tcp-ip-sockets](https://serverfault.com/questions/124517/what-is-the-difference-between-unix-sockets-and-tcp-ip-sockets)
- blog post: [https://medium.com/swlh/getting-started-with-unix-domain-sockets-4472c0db4eb1](https://medium.com/swlh/getting-started-with-unix-domain-sockets-4472c0db4eb1)
Mounting a new disk in Linux
Tags: disk, mount, linux, storage
Published: 2021-05-31 03:17:22

-> How to mount a new disk in Linux ?

```
#Create a partition
sudo fdisk /dev/sdb

#Verify using lsblk
sdb      8:16   0    2G  0 disk
└─sdb1   8:17   0    2G  0 part /

#Create a filesystem
sudo mkfs -t ext4 /dev/sdb1

#Mount it 
sudo mount -t ext4 /dev/sdb1 /kafka

#Verify using lsblk
sdb      8:16   0    2G  0 disk
└─sdb1   8:17   0    2G  0 part /kafka
```

-> How to bind a folder to this new disk and keep its data ?

```
sudo mount -t ext4 /dev/sdc1 /obs_parser

#Bind
sudo mount -o bind /vagrant /obs_parser

#Edit /etc/fstab entry (optional)
/vagrant /obs_parser none defaults,bind 0 0

#lsblk
sdc      8:32   0   41G  0 disk
└─sdc1   8:33   0   41G  0 part /obs_parser
```
How to Generate WhatsApp Link
Tags: whatsapp, tool
Published: 2021-05-31 03:01:38

WhatsApp link help you to connect with any person on WhatsApp with just a link without any phone number. It help you to generate pre-filled message as well that may be use for your business inquiries with the WhatsApp Messenger.

Here we have described a tool that helps you to Generate WhatsApp Links in seconds. Let's see how you can generate WhatsApp links,

##Steps to Generate WhatsApp Link :

Step 1: Open **[WhatsApp Link Generator](https://whatsapplink.apkmuz.com/)**

Step 2: **Enter WhatsApp number** of which you want Generate WhatsApp Link and also **add message** if you want to Generate **pre-filled message WhatsApp link**.

Step 3: After that, click on **Generate** button to Generate your WhatsApp Link. That's it.

That's how you can [Create WhatsApp Link](https://apkmuz.com/create-whatsapp-link/) in seconds with WhatsApp Link Generator tool.

We hope this will helpful to you, if yes then surely share this post. Have a Good Day.
Locked out of github due to 2 factor authentication
Published: 2021-05-31 02:51:21



I have been locked out of my github account because of failed 2 factor authentication, i had it installed with Authy app of which i forgot the backup password, i have formatted my laptop so now i dont have any saved recovery codes, I have asked Authy for support but they were not able to help me and now my only option is to ask github support for help which i did 4 days ago but have not heard from them. As a result i am not being able to perform any of my task whether it is personal or professional. Has anyone got into this issue before and please suggest me how i can resolve this issue.
JavaScript Popup boxes Tutorial
Tags: javascript, webdev, tutorial, beginners
Published: 2021-05-31 02:44:21

JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

Alert Box
An alert box is often used if you want to make sure information comes through to the user.

When an alert box pops up, the user will have to click "OK" to proceed.

Syntax
window.alert("sometext");

The window.alert() method can be written without the window prefix.

Example
alert("I am an alert box!");

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/05h0o42p8wsqhqnef96d.png)
 

Confirm Box
A confirm box is often used if you want the user to verify or accept something.

When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

Syntax
window.confirm("sometext");

The window.confirm() method can be written without the window prefix.

Example
if (confirm("Press a button!")) {
  txt = "You pressed OK!";
} else {
  txt = "You pressed Cancel!";
}

Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.

When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.

If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

Syntax
window.prompt("sometext","defaultText");
The window.prompt() method can be written without the window prefix.

Example
var person = prompt("Please enter your name", "Harry Potter");

if (person == null || person == "") {
  txt = "User cancelled the prompt.";
} else {
  txt = "Hello " + person + "! How are you today?";
}

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6zhkts27jjk3683m96ye.png)
 
Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the character n.

Example
alert("Hello\nHow are you?");