JavaScript – Linux Hint https://linuxhint.com Exploring and Master Linux Ecosystem Sun, 28 Feb 2021 23:28:37 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.2 How to Install Yarn on Linux Mint 20 https://linuxhint.com/install-yarn-linux-mint/ Fri, 26 Feb 2021 17:45:50 +0000 https://linuxhint.com/?p=91638

Yarn is a JavaScript package and dependency management tool that helps users to automate the tasks of installing, updating, removing, and configuring NPM packages. Yarn is an open-source package manager that saves a lot of time for JavaScript programmers because it creates a cache of downloaded packages. Using Yarn, a programmer can easily access and re-use a package without re-downloading it every time.

This article shows you how to install Yarn on Linux Mint 20.

Installing Yarn on Linux Mint 20

The Yarn tool is not included in Linux Mint 20 standard repositories. However, Yarn can be installed by adding the official repository of Yarn. To install Yarn from the official repository, fire up the terminal, and follow the steps provided below:

Step 1: Update APT Cache

As always, first, update the apt cache with the following command:

$ sudo apt update

Step 2: Install Curl

The Curl command is required to fetch Yarn’s GPG key. Curl comes pre-installed on Linux Mint 20. However, if Curl is not installed on your system, then install it with the following command:

$ sudo apt install curl

Step 3: Import GPG Key of Yarn Repository

After the successful installation of Curl, import the Yarn repository’s GPG key using the command given below:

$ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -

The ‘OK’ confirms that the GPG key has been imported successfully.

Step 4: Add Yarn Repository

Once the GPG key has been imported, add the Yarn repository. The following command will add and enable the Yarn repository:

$ echo "deb https://dl.yarnpkg.com/debian/ stable main" |
sudo tee /etc/apt/sources.list.d/yarn.list

Step 5: Install Yarn

First, update the apt cache before installing Yarn:

$ sudo apt update

Next, install Yarn using the following command:

$ sudo apt install yarn

Yarn requires 36.0 MB of additional disk space. If you agree to this, press ‘y’ to continue installing Yarn.

The above command will also install NodeJS. If you have already installed NodeJS, then skip the above command, and install Yarn with the command given below:

$ sudo apt install --no-install-recommends yarn

Step 6: Check Installed Version of Yarn

Once Yarn has been installed successfully, verify the installation and check the installed version with the following command:

$ yarn --version

The output above shows that Yarn version 1.22.5 has been installed successfully on the Linux Mint 20 system.

How to Remove Yarn from Linux Mint 20

If you no longer require Yarn and want to remove it from your Linux Mint 20 system, then it is very easy and straightforward to remove.

Issue the following command in the terminal to remove Yarn completely from your system:

$ sudo apt remove--autoremove yarn

Press ‘y’ to continue removing Yarn.

Conclusion

This article showed you how to install Yarn on Linux Mint 20. The article also showed you how to remove Yarn completely from your system. You can manage NPM packages very easily and efficiently using Yarn. Yarn’s repository is regularly maintained by the developers and contains the latest stable version.

]]>
WebSocket Example Program https://linuxhint.com/websocket-example-program/ Tue, 19 Jan 2021 19:42:04 +0000 https://linuxhint.com/?p=85913

The WebSocket protocol allows for two-way communication to occur between a client and a server. This process is similar to the way in which calls on your phone take place: first, you establish a connection, and then you can start communicating with one another. The WebSocket protocol is used almost everywhere – from multiplayer browser games to chat applications.

This article shows you how to create a WebSocket protocol and use it to communicate with multiple users.

Prerequisites

Before moving on to the process of creating and using a WebSocket protocol, you first need to install a few things that are required for this process. The first thing that you need to install is Node.js, a server-side platform that converts the JavaScript programming language into machine code that allows you to run JavaScript directly on your computer. To install Node.js, Windows users can simply go to the official Node.js website and click on the green LTS button found in the center of the screen.

For Linux and macOS users, click on the Downloads section in the sub-header of the website.

After opening the Downloads section, you will see installation files for all three major platforms. Select a package that is supported by your system.

Run the installer that comes with the downloaded files, and Node.js will be installed on your computer. To check whether the program has been installed, open the terminal and issue the following command:

$ node -v

After installing Node.js, you now have access to various JavaScript modules, which will make your work more efficient in the long run. Open the directory in which you want to create your client and server architecture, then open the terminal inside that directory and run the following command:

$ npm init -y

This command is used to create the package.json file that allows you to set up and install different Node.js packages. Install the WebSocket protocol package by issuing the following command in the terminal:

$ npm install ws

Create three files, called index.html, client.js, and server.js. As indicated by the names, these JavaScript files are the client and server architecture of our WebSocket protocol. Now, we can finally start writing the code of our client and server applications.

Creating a WebSocket Server

To create a WebSocket server, we will start by writing the code for the server. Open the server.js file that you created inside your text editor or IDE in the previous section and enter the following lines inside the file.

const WebSocket = require('ws');

const ws = new WebSocket.Server({ port: 8080 });

console.log("Server Started");


ws.on('connection', (wss) => {

  console.log("A new Client Connected")

  wss.send('Welcome to the Server!');


  wss.on('message', (message) => {

    console.log(`Server Received: ${message}`);


    wss.send('Got your Message: ' + message);

  });

});

Now, we will explain what each line is doing in greater detail.

Code Explanation

As mentioned previously, there are some built-in modules available in Node.js that make your work much easier. To import these modules, we will use the require keyword.

const WebSocket = require('ws');

const ws = new WebSocket.Server({ port: 8080 });

console.log("Server Started");

The first line is used to import the Node.js WebSocket module. Using this module, in the next line, we create our WebSocket server, which is listening on port 8080. The console.log() line is simply there to let us know that the Server has started. You will see this appear inside your terminal when you run the following command in the terminal:

$ node server

In the next line, we are establishing a connection between the server and the client.

ws.on('connection', (wss) => {

  console.log("A new Client Connected")

});

After a connection has been established, the wss.send() line sends a message to the client. In this case, the message is “Welcome to the Server.”

wss.send('Welcome to the Server!');

Finally, the wss.on (‘message’) is for the server to receive the message from the client. For confirmation, the server sends this message back to the client in the last line.

  wss.on('message', (message) => {

    console.log(`Server Received: ${message}`);

    wss.send('Got your Message: ' + message);

  });

Creating a WebSocket Client

For the client-side, we need both the index.html file and the client.js file. Of course, you can simply add the content from the client.js file into your index.html file, but I prefer keeping them separate. Let us first look at the client.js code. Open the file and enter the following lines inside of the file:

const socket = new WebSocket('ws://localhost:8080');

socket.addEventListener('open', () => {

    console.log('Connected to the Server!');

});


socket.addEventListener('message', (msg) => {

    console.log(`Client Received: ${msg.data}`);

});


const sendMsg = () => {

    socket.send('Hows it going amigo!');
}

Code Explanation

Like with the server.js, we will create a new WebSocket that is listening to port 8080, which can be seen in the localhost:8080 section of the code.

const socket = new WebSocket('ws://localhost:8080');

In the next line, addEventListener makes your client listen to any events that are currently happening. In this case, it would be creating and starting the server. Once the connection is established, the client outputs a message to the terminal.

socket.addEventListener('open', () => {

    console.log('Connected to the Server!');

});

Once again, the client listens to any events currently happening. When the server sends a message, the client receives this and then displays the message in the terminal.

socket.addEventListener('message', (msg) => {

    console.log(`Client Received: ${msg.data}`);

});

The last few lines are simply a function where the client is sending a message to the server. We will connect this to a button in our html file for a better understanding of how this is working.

const sendMsg = () => {

    socket.send('Hows it going amigo!');

}

Preparing an HTML File

Finally, open the index.html file and add a reference to your client.js file inside of it. In my case, I will simply add the following lines of code:

<!DOCTYPE html>

<html lang="en">

<head>

   <meta charset="UTF-8">

   <meta name="viewport" content="width=device-width, initial-scale=1.0">

   <title>Client</title>

</head>

<body>

   <button onClick="sendMsg()">Send Message to Server</button>

</body>

<script src="client.js"></script>

</html>

As you can see in the lines below, src (inside the script tag) refers to the client javascript file. The sendMsg function, which was created in the client.js file, has also been connected to the button’s onClick function.

<button onClick="sendMsg()">Send Message to Server</button>

<script src="client.js"></script>

Putting Everything Together

You can now start testing your Client and Server Architecture. First, open the terminal and run the following command to start your server:

$ node server

After starting your server, open the directory in which your index.html file is present, and double-click on it to open it in your browser. You will see the following message appear in the terminal stating that a client has connected:

You can also check the messages sent from the server to the client by pressing the right-click button and then opening the Inspect window. In this window, click the Console section, and you will be able to see the messages sent from the server.

Once you click on the button, both the server and client will be able to send and receive messages to and from each other.

Server:

Client:

Voilà, your WebSocket connection has been established!

Conclusion

The WebSocket protocol is an excellent way to establish communication between a client and a server. This protocol is used in several fields, including multiplayer browser games, chat systems of various social media platforms, and even collaboration processes between coders.

]]>
Setup Electron and Create Hello World Application in Linux https://linuxhint.com/setup_electron_create_hello_world_application_linux/ Sun, 15 Nov 2020 03:36:46 +0000 https://linuxhint.com/?p=76694

This article will cover a guide about installing Electron and creating a simple “Hello World” Electron application in Linux.

About Electron

Electron is an application development framework used for creating cross-platform desktop applications using web technologies in a standalone web browser. It also provides operating system specific APIs and a robust packaging system for easier distribution of applications. A typical Electron application requires three things to work: Node.js runtime, a standalone Chromium based browser that comes with Electron and OS specific APIs.

Install Node.js

You can install Node.js and “npm” package manager by running the following command in Ubuntu:

$ sudo apt install nodejs npm

You can install these packages in other Linux distributions from the package manager. Alternatively, download official binaries available on Node.js website.

Create a New Node.js Project

Once you have installed Node.js and “npm”, create a new project named “HelloWorld” by running the following commands in succession:

$ mkdir HelloWorld

$ cd HelloWorld

Next, fire up a terminal in the “HelloWorld” directory and run the command below to initialize a new package:

$ npm init

Go through the interactive wizard in the terminal and enter names and values as needed.

Wait for the installation to finish. You should now have a “package.json” file in “HelloWorld” directory. Having a “package.json” file in your project directory makes it easier to configure project parameters and makes the project portable for easier shareability.

The “package.json” file should have an entry like this:

"main": "index.js"

“Index.js” is where all logic for your main program would be located. You can create additional “.js”, “.html” and “.css” files according to your needs. For the purpose of “HelloWorld” program explained in this guide, the command below will create three required files:

$ touch index.js index.html index.css

Install Electron

You can install Electron in your project directory by running the command below:

$ npm install electron --save-dev

Wait for the installation to finish. Electron will be now added to your project as a dependency and you should see a “node_modules” folder in your project directory. Installing Electron as a per-project dependency is the recommended way of installing Electron according to the official Electron documentation. However, if you want to install Electron globally on your system, you can use the command mentioned below:

$ npm install electron -g

Add the following line to “scripts” section in “package.json” file to finish Electron setup:

"start": "electron ."

Create Main Application

Open “index.js” file in text editor of your choice and add the following code to it:

const { app, BrowserWindow } = require('electron');

function createWindow () {

  const window = new BrowserWindow({

    width: 1600,

    height: 900,

    webPreferences: {

      nodeIntegration: true

    }

  });

  window.loadFile('index.html');

}

app.whenReady().then(createWindow);

Open “index.html” file in your favorite text editor, and put the following code in it:

<!DOCTYPE html>

<html>

<head>

<link rel="stylesheet" href="index.css">

</head>

<body>

<p id=”hworld”>Hello World !!</p>

</body>

</html>

The javascript code is pretty self explanatory. The first line imports necessary Electron modules needed for the app to work. Next, you create a new window of the standalone browser that comes with Electron and load the “index.html” file in it. The markup in the “index.html” file creates a new paragraph “Hello World !!” wrapped up in the “<p>” tag. It also includes a reference link to the “index.css” stylesheet file used later in the article.

Run Your Electron Application

Run the command below to launch your Electron app:

$ npm start

If you have followed instructions correctly so far, you should get a new window similar to this:


Open “index.css” file and add the code below to change the color of “Hello World !!” string.

#hworld {

    color: red;

}

Run the following command again to see CSS style applied to “Hello World !!” string.

$ npm start


You now have the bare minimum set of required files to run a basic Electron application. You have “index.js” to write program logic, “index.html” for adding HTML markup and “index.css” for styling various elements. You also have a “package.json” file and “node_modules” folder containing required dependencies and modules.

Package Electron Application

You can use Electron Forge to package your application, as recommended by the official Electron documentation.

Run the command below to add Electron Forge to your project:

$ npx @electron-forge/cli@latest import

You should see some output like this:

✔ Checking your system

✔ Initializing Git Repository

✔ Writing modified package.json file

✔ Installing dependencies

✔ Writing modified package.json file

✔ Fixing .gitignore

We have ATTEMPTED to convert your app to be in a format that electron-forge understands.

Thanks for using "electron-forge"!!!

Review “package.json” file and edit or remove entries from “makers” sections according to your needs. For instance, if you don’t want to build an “RPM” file, remove entry related to building of “RPM” packages.

Run the following command to build the application package:

$ npm run make

You should get some output similar to this:

> helloworld@1.0.0 make /home/nit/HelloWorld

> electron-forge make

✔ Checking your system

✔ Resolving Forge Config

We need to package your application before we can make it

✔ Preparing to Package Application for arch: x64

✔ Preparing native dependencies

✔ Packaging Application

Making for the following targets: deb

✔ Making for target: deb - On platform: linux - For arch: x64

I edited the “package.json” file to build only the “DEB” package. You can find built packages in the “out” folder located inside your project directory.

Conclusion

Electron is great for creating cross-platform applications based on a single codebase with minor OS specific changes. It does have some issues of its own, most important of them is resource consumption. Since everything is rendered in a standalone browser and a new browser window is launched with every Electron app, these applications can be resource intensive compared to other applications using native OS specific application development toolkits.

]]>
Javascript Form Validation https://linuxhint.com/javascript_form_validation/ Thu, 12 Nov 2020 11:03:23 +0000 https://linuxhint.com/?p=76509

Form validation is the basic and most important part of the web development process. Usually, form validation is done on the server-side. Form validation helps in showing error messages to the user if there is any unnecessary or wrong data is provided, or a required field is left empty. If the server finds any error, it throws back that error; then, we show the error message to the user. But, we can use javascript at the front-end to validate the form data and show errors right away. In this article, we will learn the basic form validation in javascript. So, let’s get straight to the examples and see how can we do that in javascript.

Examples

First of all, we assume a form with the name of “testForm,” in which we have an input field with the label “User Name,” and an input type submits in our HTML file. In the form tag, we have created an onsubmit event, in which we are making closure and returning a function validateFunc().

<form action="" method="get" name="testForm" onsubmit="return(validationFunc())">
    <label for="name">User Name</label>
    <input type="text" name="name"><br>

    <input type="submit" value="Submit">
</form>

In the script file, we will write the function definition of validateFunc(), which will get executed every time when the user hits the submit button. In that function, we will validate the username input field. We suppose that we want to validate either the username field is empty or not when the user hits the submit button.

So, to validate the username field. We first assign a variable to the document.testForm, just to give a clean and understandable look to the code. Then, in the function definition, we will write the code for validation. We will write an if statement to check the empty form field. If the username field is empty, we will show an alert box to show the error, focus on the username field again, and return false so that the form won’t get submitted. Otherwise, if it passes the check and data get validated, we will return true to the function.

var theForm = document.testForm;

// Form validation code
function validationFunc() {
if (theForm.name.value == "") {
    alert( "name is empty" );
    theForm.name.focus();
    return false;
}

return (true);
}

After writing all this code. If we run the code and click on the submit button without writing anything in the form field.

As you can observe in the screenshot attached below, it throws an error in the alert box.

This is a very basic yet good example to get started with implementing the form validation. For further implementation, like multiple form validations or you want to have a check on character length as well.

For that purpose, we first suppose two form fields in the form tag with the label of “email” and “password” in our HTML file.

<form action="" method="get" name="testForm" onsubmit="return(validationFunc())">
    <label for="name">User Name</label>
    <input type="text" name="name"><br>

    <label for="email">Email</label>
    <input type="email" name="email" id=""><br>

    <label for="password">Password</label>
    <input type="password" name="password" id=""><br><br>

    <input type="submit" value="Submit">
</form>

For validation in javascript, we will again put an if statement for validation of the email and password form fields in the function definition of the script file. Suppose we want to apply multiple validations on the email field like the field should not be empty, and its length should not be less than 10 characters. So, we can use OR “||” in the if statement. If any of these errors occur, it will show an alert box with the error message that we want to show, focus on the email form field, and return false to the function. Similarly, if we want to apply the character length check on the password field, we can do so.

var theForm = document.testForm;

// Form validation code
function validationFunc() {
if (theForm.name.value == "") {
    alert( "name is empty" );
    theForm.name.focus();
    return false;
}

if (theForm.email.value == "" || theForm.email.value.length < 10) {
    alert( "Email is inappropriate" );
    theForm.email.focus();
    return false;
}

if (theForm.password.value.length < 6) {
    alert( "Password must be 6 characters long" );
    theForm.password.focus();
    return false;
}

return (true);
}

After writing all this code, reload the page to have updated code. Now, either we leave an empty email field or write an email less than 10 characters. In both cases, it will show an “Email is inappropriate” error.

So, this is how we can apply basic form validation in JavaScript. We can also apply data validation on the client-side using Regex or by writing our own custom function. Suppose we want to apply data validation on the email field. The regex would be like this for validating an email.

if (/^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.
test(theForm.email.value)) {
    alert( "Email is inappropriate" );
    theForm.email.focus() ;
    return false;
}

This was just a basic demonstration of data validation using regex. But, the sky is open for you to fly.

Conclusion

This article covers the basic form validation in javascript. We have also tried and have a sneak into the data validation using regex. If you want to learn more about regex, we have a dedicated article related to regex on linuxhint.com. For learning and understanding javascript’s concepts and more useful content like this, keep visiting linuxhint.com. Thank you!

]]>
Javascript Try Catch https://linuxhint.com/javascript_try_catch/ Sun, 08 Nov 2020 17:10:50 +0000 https://linuxhint.com/?p=76110

Javascript is a translative programming language. Just like any other language, a developer or programmer often needs to care about error handling. Mostly a programmer or developer needs to handle errors while accessing or assigning some data to the database. So, error handling is an essential part of any programming project. There are three types of errors in programming that a programmer or developer often has to face.

Syntax Error – An error in writing code against the syntax of programming language. For example, missing a semi-colon or not following the convention of creating and calling the function.

Logical Error – An error in the logic building. For example, implementing the wrong arithmetic operation, which results in the wrong output.

Runtime Error – Error occurred during the runtime. Like, calling a function without declaring it.

The error that we get during the runtime is also known as an exception. Exceptional handling is very important. Because we can’t throw the errors and error codes right away. We have to handle that. So, In this article, we are going to have an understanding of how to handle exceptions using javascript’s try-catch block. We will also learn how to throw a custom message against an error and how to use the “finally” block with a try-catch block.

Syntax

The syntax for using a try-catch block is very simple and easy to use. We can simply use the try-catch block like this

try {

 //code to try or test

 throw //throw a custom error to catch

} catch (error) {

 // code after getting an error

} finally {

 // code which executes in any case

}

In this syntax, we first write some lines of code in the “try” block to test. If that code gets executed or passed the test successfully. The “try” block won’t throw any error to the “catch” block and execute the “finally” block. Otherwise, it will throw an error to the “catch” block where we can handle the exceptions according to the given error. We can throw a custom error to the “catch” block as well using the “throw” keyword. “Finally” block will get executed in any case. Either the “try” block throws any or not. Let’s try a couple of examples to have a better understanding.

Examples

First of all, to demonstrate the simple and basic working of the try-catch block. We try to call a function without declaring it anywhere.

addition()

It will definitely throw an error in the console


But, if we try to call it in a try block now

try {

 addition()

} catch (error) {

}

It won’t show any error in the console anymore because we did not write any code in the catch block for error. So, we can modify and console the error message in the catch block now.

try {

 addition()

} catch (error) {

 console.log("Error Message => " + error)

}

We can see our custom message in the console against the error.


So, this is the very basic usage of the try-catch block. Now, let’s learn about throwing a custom error in the try block.

Throw

Suppose we want to throw a different custom error on the base of different errors while trying. We can throw a custom error, that “Function definition doesn’t exist.” Like this

try {

 throw new Error ("Function definition doesn't exist")

} catch (err) {

 console.log("Error Message => " + err)

}


As you can see in the output, the error message is now changed to our custom error thrown.

ProTip

Suppose we try to apply this try-catch on an asynchronous function. It won’t work. Because the engine would have moved to the next line, execute the final block, and the asynchronous function would get executed later. For example, if we apply the setTimeout Function inside a try-catch block.

try {

 setTimeout(() => {

   addition();

 }, 3000)

} catch (err) {

 console.log("Error Message => " + err)

} finally{

 console.log("reached 'finally' block")

}


You can observe that the “finally” block gets executed first, and the error is thrown later if we take a look at the error. It is not the error from the catch block, but it is an original programming error, which means that the catch block doesn’t get executed because they try block didn’t find any error.

Alright! Now, if we want to make it work. We have to apply the try-catch block inside the setTimeout function instead of outside. So, the true way of implementing an asynchronous function with a try-catch block would be like this.

setTimeout(() => {

 try {

     addition();

   } catch (err) {

   console.log("Error Message => " + err)

 } finally{

   console.log("reached 'finally' block")

 }

}, 3000)


You can observe in the output that after the delay of 3 seconds because of the setTimeout function. We have got the error message from the catch block first, and then the “finally” block gets executed.

Conclusion

In this article, We have learned to implement the try-catch block step by step in javascript in such an easy and profound way that any beginner after reading this article would be able to apply it anywhere he needs. So, keep on learning and getting experience in javascript with linuxhint.com. Thank you!

]]>
Javascript Random Number https://linuxhint.com/javascript_random_number/ Thu, 05 Nov 2020 11:25:51 +0000 https://linuxhint.com/?p=75490

While developing a gaming website, we often need to generate random numbers. In this article, we are going to know how we can get a random in Javascript using the random method.

The random method helps in generating pseudo-random numbers, since, arithmetically, generating a true random number is impossible.

Syntax

We can get random numbers using Math.random() function, like this:

Math.random();

This function doesn’t take any arguments and will return the random float number between 0 and 1.

If we want to generate random numbers between any two numbers or up to a limit. The syntax would be different for them. For better understanding, let’s try a couple of examples.

Examples

Suppose, we want to generate a random number from 0 to 99. The syntax for providing a limit or a range is:

Math.random() * 100

Keep in mind that 100 is a limit or range, not the number.

You can see that it has generated a number from 0 to 99, but, it’s a float number.

So, if we want to have a whole number and not a float number, ,we can apply a Math.floor() method over Math.random() method, like this:

Math.floor(Math.random() * 100)

That looks great!

Now, what if we do not want to have numbers from 0 to 99 or onwards but from some other number, for example, 50 to 90. First, let’s see how we can do that, and later we will see how it works.

Math.floor((Math.random() * 40) + 50)

In this syntax, 40 is the range or limit from 50 to onwards, 50 as the starting number.

In the end, if we want to build our custom random function to which we can provide two numbers (minimum and maximum) and get a random number between those two numbers. The function would be like this:

function getRandomNum(sNum, lNum) {
 return Math.floor((Math.random * (lNum - sNum)) + sNum)
}

Keep in mind that the ending number or “lNum” will be excluded. In case you want to include that as well add “1” in the range, like this:

function getRandomNum(sNum, lNum) {
 return Math.floor((Math.random * (lNum - sNum + 1 )) + sNum)
}

After writing this function. Let’s call it and see the results.

getRandomNumber(20, 40);



As you can see, we are getting random numbers from 20 to 40.

So, these are some of the different ways to generate pseudo-random numbers in Javascript using the Math.random() method.

Conclusion

In this article, we have learned to get random numbers in Javascript and tried several techniques to get the desired results. We have also learned to make a custom function in which we can provide the range of numbers and get the random numbers between that ranges.

So, keep on learning Javascript with linuxhint.com to have a better grasp over it. Thank you! ]]> JavaScript onClick https://linuxhint.com/javascript_onclick/ Mon, 02 Nov 2020 09:41:49 +0000 https://linuxhint.com/?p=75181

Introduction

JavaScript is a well-known programming language. It is used in more than 95% of the websites we interact with daily. You may often see that on the click of a button, a whole page gets changed, a form field is opened, or a pop-up box appears. From the perspective of a programmer/developer, how can we implement such functionality and handle the website’s interactions with users? When it comes to interaction, JavaScript provides built-in functions to control events on a site.

There are two types of events in JavaScript:

  • Event Listener – listens and waits for the event to get fired
  • Event Handler – executed when an event is getting fired

In this article, you will learn about the most used event handler of JavaScript, the onClick event. There are other event handlers for hovering over an element or for keyboard key presses, but in this article, we will focus on the onClick event.

The onClick event is used to perform certain tasks at the click of a button or by interacting with an HTML element.

We will now show you an example to demonstrate how the onClick event works.

Example: Change Text Using onClick

In this example, we will change a selection of text on the click of a button using the onClick event. First, we will make a paragraph tag and give it an ID “paragraph” to access it later. We will create a button with the onClick event and call the function named “change.”

<p id="paragraph">Linuxhint</p>
<button onclick="change()">Change!</button>

In the script file, we will create a flag variable that will allow us to check the status of the text in our HTML paragraph tag. Then, we will write a function defining the “change” function. In the function definition, we will create an “if” statement, in which we will check the status using the flag variable. We will also change the text and alter the flag. It is a pretty simple piece of code!

var a = 1;

function change(){
 if (a==1) {
   document.getElementById("paragraph").innerHTML = "Linuxhint is awesome"
   a = 0;
 } else {
   document.getElementById("paragraph").innerHTML = "Linuxhint"
   a = 1;
 }
}

All right! After writing all this code, we will run the code, move to our browser, and click the newly created button. After clicking the button, the text should be changed from “Linuxhint” to “Linuxhint is awesome.”

We can apply the same technique anywhere to change the content of our website according to our needs. We can use it in changing an image or performing any type of task that we can imagine with this tool.

Conclusion

This article explains how to use the onClick event. In this article, you learned the concept of the onClick function in a practical way. The usage of the onClick event is so simple, even a beginner can start working with this function. You may continue learning, working, and gaining more experience in JavaScript at linuxhint.com to have a better grasp of this programming language. Thank you so much!

]]>
JavaScript Cookie https://linuxhint.com/javascript_cookie/ Sun, 01 Nov 2020 15:14:27 +0000 https://linuxhint.com/?p=75157

JavaScript is the language behind almost every website you will use. JavaScript is the language of the online world and is used in online communication, as well. The concept and need for cookies arose when developers wanted to store user information in the browser to avoid overloaded communication over a stateless HTTP server. A cookie is like a file containing some data that is stored on the user’s machine. The information stays on the computer, even if the user closes the website or closes the browser. This article provides an overview of the use of cookies in JavaScript.

Syntax

The syntax for creating and saving cookie is as follows:

document.cookie = "cookieName=cookieValue"

The cookie saves the data in key-value pairs.

Creating a Cookie

You can create a cookie by assigning a string to the document.cookie, for example, userName.

document.cookie="userName=John"

Getting a Cookie

Now, if we want to have a look at the Cookie, we can get the cookie by assigning document.cookie to a variable and then console it.

var cookieStat = document.cookie;
console.log(cookie.Stat);

Setting/Updating a Cookie

We can update a cookie as well using the same syntax we used for creating a cookie. To add the expiry date in the cookie, for example, we will use the following technique:

var expiryDate = new Date();

expiryDate.setDate(expiryDate.getDate() + 1)
expiryDate.toUTCString()

document.cookie = "userName=John"
document.cookie = "expires=" + expiryDate.toUTCString()

After updating, take a look at the cookie:

console.log(document.cookie)

You can see that cookie is updated.

Deleting a Cookie

There is no built-in method or object for deleting a cookie in Python, but a cookie is deleted when it expires. By assigning a past date to a cookie, you can delete it.

var expiryDate = new Date();

expiryDate.setDate(expiryDate.getDate() - 1)
expiryDate.toUTCString()

document.cookie = "userName=John"
document.cookie = "expires=" + expiryDate.toUTCString()

After assigning a past date, the cookie will no longer work and will self-delete by expiring.

Conclusion

So, this is how you can create a cookie, set or update a cookie, and delete a cookie in JavaScript. In this article, you learned about cookie usage in JavaScript, including how cookies can help you in development and save necessary user data. You can continue to learn more about JavaScript at linuxhint.com. Thank you!

]]>
Javascript Refresh Page https://linuxhint.com/javascript_refresh_page/ Thu, 29 Oct 2020 11:42:11 +0000 https://linuxhint.com/?p=74867

Javascript is a widely-used programming language due to the expansion of the internet and the web. In the modern world of the web, we can do almost every task in one single browser, and Javascript is used in every single website we see in our daily routine life. Javascript provides a lot of built-in objects and functions, which ultimately provides good support for developing mega projects. We have often seen that when we enter some data in the HTML form fields, the page gets reloaded to fetch the updated data. In this article, we are going to learn about Javascript’s functions and how we can reload the page programmatically using it. There are actually around 535 ways to reload a page in Javascript. Yes, 535 ways. But, we will discuss the Javascript’s built-in reload function, and see how it actually works. So, let’s get started!

Javascript’s built-in reload function is used to reload/refresh the current web page or specific area.

Syntax

The syntax for the reload function is:

location.reload();

This function doesn’t return any parameters. But we can pass true or false. In the case of true, the web page must have to be reloaded from the webserver. Otherwise, for false, the web page is supposed to be reloaded from the cache of the web browser.

Let’s take a look at the examples and learn in a better way.

Examples

First, if we simply call the function. It will definitely reload the page.

location.reload()

And if we pass true, it will reload the page from the webserver.

location.reload(true);

And if we pass false, it will reload the web page from the browser’s cache.

location.reload(false);

We can also reload the page using a function and the onclick event of a button. First, create a button with the onclick event in the HTML file.

<button>Reload!</button>

And in the script file, the function should be like this.

function reloadPage(){
 location.reload();
}

So, this is a piece of very basic and still very profound knowledge about Javascript’s reloaded function.

Conclusion

In this article, we have learned about Javascript’s built-in reload function for reloading/refreshing the web page. This video contains a detailed yet very simple and easy to understand the concept of Javascript’s built-in reload function. So, keep on learning, working, and getting experience in Javascript with linuxhint.com to have a better grasp over it. Thank you so much.

]]>
Javascript Get URL https://linuxhint.com/javascript_get_url/ Thu, 29 Oct 2020 11:07:52 +0000 https://linuxhint.com/?p=74858

Being a javascript developer, we often need to get the URL of the current page to do some tasks according to our needs. In this article, we are going to learn how we can get the current URL, know what its syntax is, and how we can extract different parts using the built-in window.location object.

The simplest and most straight forward way of getting the URL of the current page is shown below:

window.location.href

But, if we take a sneak peek into the window.location in the developer’s console, it is shown below:

We can observe what it has for us. We could receive a good amount of information from the Window.location object. For example:

Examples

If we want to get the protocol only, like HTTP or HTTPS, from the whole URL, we can get that using the very simple window.location.protocol, like the picture below:

window.location.protocol

And if we want to get the hostname from the URL, we can simply get that using the window.loation.host.

window.location.host

And similarly, if we want to get the pathname only, we can get that using window.location.pathname.

window.location.pathname

For getting the search query, we can use window.location.search.

window.location.search

So, these are basically some of the ways to get the current URL and extract some specific parts from it according to our requirements. Moreover, window.location has a lot of other options for us.

Conclusion

In this article, we have learned about the window.location object, how we can use it to get the current URL, and extract some specific parts from that. So, keep on learning, working, and getting experience in Javascript with linuxhint.com to have a better grasp over it. Thank you so much.

]]>
Javascript Print Page https://linuxhint.com/javascript_print_page/ Wed, 28 Oct 2020 18:02:11 +0000 https://linuxhint.com/?p=74510

Javascript is a scripting or programming language, which is most commonly used nowadays in the web industry. It provides a lot of built-in objects, functions, and methods to perform several tasks. In this article, we are going to have a look at one of them which is used to print the web page. So, let us get started!

You must have encountered some websites that provide a button to print the whole web page, or you must have felt the need to print a web page but there is no print button there. Javascript’s built-in object window provides us a method named print(). We can use window.print() function to fulfill this requirement.

Syntax

The syntax of the print function is:

window.print();

This simple syntax neither gets any parameters nor returns anything. It simply fires the print window.

We simply have to make a button in our HTML, and on the on-click event of that button we can directly call the window.print() function.

<button onclick="window.print()">Print</button>

Then, on the web page, if we click the button, it will open up a window or dialog box, which we usually see while printing any document.

Be careful that it will print everything on the webpage. Either that web page includes images or advertisements.

Conclusion

In this article, we have learned how we can print the whole web page, and the benefits and consequences of doing that.

This article explains the need and the usage of javascript’s built-in window.print() function. So, keep on learning javascript’s concepts with linuxhint.com.

]]>
Javascript Alert https://linuxhint.com/javascript_alert/ Wed, 28 Oct 2020 18:00:48 +0000 https://linuxhint.com/?p=74504

Javascript is the most known language of the web. Javascript is widely used in front-end development as well as in the back-end. Javascript provides a lot of built-in functions to help in development. In this article, we are going to learn one of the javascript’s built-in alert() method, which is used to show pop-ups over the screen to either display a message or show a warning. The alert box is different from any other message or text on the screen. It is a pop-up that contains a message/text with an “OK” button. The user won’t be able to do any task while an alert box is over the screen, and he/she clicks the “OK” button. So, it is not recommended, if not needed. So, let’s have a look at what is an alert box and what are the different ways to use it.

The alert() is basically a method, which is used to show a pop-up box over the web page.

Syntax

There are two different syntaxes for showing the alert box. One of them is using the window’s object.

window.alert("Alert box from the linuxhint");

But, we can use the alert() method without the window’s object as well.

alert("Alert box from the linuxhint");

So, let’s try both of the syntaxes.

Examples

First, let’s try with the window’s object.

window.alert("Alert box from the linuxhint");

And now, without the window’s object.

alert("Alert box from the linuxhint");

You will witness that there is no difference in both of them.

The alert method doesn’t only take the string to show the message. We can provide variable as well, and it worked perfectly fine,

var alertMessage = 'Alert Box using variable';
alert(alertMessage);

as you can see in the screenshot below that the message is displayed.

We have learned about providing a variable as well. What if we want to show the pop-up alert box on the screen at the click of a button? For example, we have got some information from the user, and after successfully saving the user’s data on the server, we want to show a confirmation message that says “Added successfully”. So, we can simply show an alert box like this.

<button onclick="alert(Added successfully)">Show Alert!</button>

Or, if we are getting a confirmation message from the server, and we want to show the message on the base of the message we got. We can call the function on the button’s onclick method

<button onclick="alertFunc()">Show Alert!</button>

Then, later in the script, we can write the function in which we can show the alert message.

function alertFunc() {

var alertMessage = 'Alert Box using function';

alert(alertMessage);

}

So, these are some of the different methods of using the alert() method.

Conclusion

In this article, we have learned about the javascript’s built-in alert method to show pop-up over the browser’s window. This article has explained the use of the alert method in a very easy, profound, and effective way that any beginner can understand and use. So, keep on learning, working, and getting experience in javascript with linuxhint.com to have a better grasp over it. Thank you so much!

]]>
Javascript Map https://linuxhint.com/javascript_map/ Wed, 28 Oct 2020 13:05:26 +0000 https://linuxhint.com/?p=74394
In this article, we are going to learn one of the most widely used methods for the array, which is the map() method. The map method helps in mapping arrays according to our requirements. Let’s see, what is a map() method? What is the syntax for mapping arrays using the map() method?

The array’s map method is used to construct a new mapped array based on the return value of the callback function for each element.

var mappedArray = array.map(callbackFunction, thisValue)

The callback is the function that will be called every time for a single element and return a value that will be stored in a new array. The syntax for the callback function is

function(value, [index[, array]])

value is a necessary argument, which is actually a single element of the array.
The index is an optional argument that will be used as the index of each element in the callback function.
The array is an optional argument as well. We can pass this argument if we want to use the array in the callback function.

thisValue is the value we want to pass, which will be used as a “this” in the callback function. Otherwise, “undefined” will be passed.

Javascript provides the for…in loop and foreach loop for iterating through elements and manipulating arrays. But, why do we need a map method aside from that? There are two major reasons for that. One is the separation of concern and the second is the easy syntax for doing such tasks. So, let’s try some different examples to demonstrate the purpose and right use of it.

Examples

First of all, we are going to have a simple demonstration in which we have a simple array of numbers on which we will try to perform any simple arithmetic operation over every single element.

var arr = [4, 8, 16, 64, 49];

Now, before applying the map method over this array. We will first write a callback function to which we can call in our map function in which, let’s say we want to multiply each element with 10 and have a new array.

function multiply(element){
  var newElement = element * 10;
  return newElement;
}

Everything is set up to apply the map method over the array and have the results required.

var newArr = arr.map(multiply);

Now, if we have a look at the “newArr”,

console.log(newArr);

We can see the latest mapped array in the output as per our requirement.


Keep this in mind that the length of the new mapped array will definitely be equal to the original array.

There is a shorter way of doing the same task using the arrow or anonymous function within a map method. So, we can write a callback function within a map method like this

var newArr = arr.map((element) => {
 return element * 10
})

Or, if we want to be a pro and make it more concise. We can do this

var newArr = arr.map(e => e * 10)

Alright! So, this was the very basic demonstration of the map method and different ways to write the call back function. But, this function comes more in handy, when we are playing with an array of objects. That’s where it’s true implementation happens.

Using Map with an Array of objects

In this example, we suppose an array of objects in which each object contains the information of a player. Player’s name and his ID.

var arr = [
 { id: 12, name: "James"},
 { id: 36, name: "Morgan"},
 { id: 66, name: "Jordan"}
];

Now, let’s say we want to extract the IDs from each object and have a new array of IDs.
But, in order to understand, how the map method is different and helps better than the foreach loop. We will try both of these(map method and foreach loop) to do the same task and learn the difference.

So, first, we will try to extract IDs using the foreach loop and then using the map method.

var extractedIDs = [];

arr.forEach((element) => {
 return extractedIDs.push(element.id);
})

Now, if we have a look at the extracted IDs.

console.log(extractedIDs);


We have got them separated in an array. But, now let’s demonstrate the same output using the map method.

var extractedIDs = arr.map((element) => {
 return element.id;
})

console.log(extractedIDs);


By looking at the difference in code and the same output, we can realize the true difference between the two(foreach and map) methods. The syntax and separation of concern.

Similarly, we can perform a lot of other operations. If we have to play and get some data from the array of objects. We suppose an array of objects in which each object contains two properties: first name and last name.

var arr = [
 { firstName: "John", lastName: "Doe"},
 { firstName: "Morgan", lastName: "Freeman"},
 { firstName: "Jordan", lastName: "Peterson"}
];

Now, we want to have an array that contains the full names. So, we will write a map function like this to fulfill our purpose

var fullName = arr.map((person) => {
 return person.firstName + ' ' + person.lastName
})

console.log(fullName);


As you can see, we have got a separate array with full names. That’s great.

So, these are some of the basic and different ways of how a map function can be used to fulfill our development requirements and helps in every javascript developer’s life.

Conclusion

In this article, we have learned about javascript’s most used map() method for arrays and we have learned some of the different ways to use the map method. This article explains the concept of the map method in such an easy and profound way that any beginner coder can understand it and utilize it to his needs. So, keep on learning, working, and getting experience in javascript with linuxhint.com to have a better grasp over it. Thank you so much!

]]>
Javascript Sort https://linuxhint.com/javascript_sort/ Tue, 27 Oct 2020 23:26:32 +0000 https://linuxhint.com/?p=74324
As we have to manage arrays in almost all programming languages, JavaScript is no different. Arrays are usually used to store data like strings, numbers, objects, and undefined. With the exponential growth of online data, we frequently need to manage and sort the data. Sorting is kind of a massive experience in almost every programming language. It takes a lot of effort, machine power, and calculations to do the right sorting. With the expansion of data, we need to sort and structure the data in a beautiful way. Javascript provides a built-in array mutator method sort() for sorting arrays. In this article, we will have a look at Javascript’s built-in sort() method and learn what the Javascript sort method is, as well as how we can use it for our purpose to sort elements in an array. Let’s go ahead and start working!

The sort method is used to arrange different elements in an array in a specific order.

Syntax

The general syntax for the sort method is:

array.sort();

This method returns the sorted array in ascending order by default.

We would discuss a couple of examples to understand the sort method in JavaScript.

Examples

We suppose an array of string in which we have some different names of Linux operating systems.

let arr = ["Ubuntu", "Fedora", "CentOS", "Debian", "Kali Linux"]

Now, if we apply the sort method over this array:

arr.sort();

It will definitely sort the array in alphabetical order. We can see the output in the screenshot below.

But, if we want to get the string in reverse/descending order. We can apply a Javascript’s built-in reverse function over the sorted array like this:

var sortedArray = arr.sort();
sortedArray.reverse();

The shorter way to do the reverse is:

arr.sort().reverse();

Alright! It worked fine for the string. Let’s try if it works for the numbers as well.
So, we first suppose an array of numbers.

let arr = [14,8,33,27,6]

Then apply the sort method over the array of numbers.

arr.sort();

It seems like it didn’t work well as it did for the string. Because the sort method first converts the numbers into the strings and then sorts on the base of Unicode. Although, “8” comes before “14” in numerical order. But, in UTF-16 code units order, “14” comes before “8”. The good thing in Javascript, we got the solution for this.

CompareFunction

Here comes the concept of compare function that comes in handy in helping sort the numbers. We can use a compare function to the sort method as a callback function, which takes two elements. It then sorts them according to our requirement in the compare function and returns them to the sort method, continuously doing this until it reaches the end of the array.

The syntax for the sort method with the compareFunction would be like this:

array.sort(compareFunction);

Now, if we take a look at the technical details of the compareFunction, that is how it actually works. If we do not provide a compareFunction to the sort method, it will sort according to the UTF-16 code unit orders. If we utilize the compareFunction, all elements would be sorted in accordance with the return value of compareFunction. So, if we want to write a compare function for the numbers. That would be just like this:

function (a, b) { return a - b }

CompareFunction takes two values at a time and returns three types of values.
True or “1”, if the first value comes before the second value or the first value is greater than the second value:
False or “-1”, if the first value comes after the second value or the first value is greater than the second value.
And “0”, if two values are equal.

Now, if we try to apply it to sort the array of numbers. We can apply it like this:

arr.sort(function (a ,b){ return a - b })

As you can see in the output, array having numbers have been sorted decently.

The shorter way of doing the same task will be like this:

arr.sort((a, b) => a - b)

But, this works only for the comparison of the numbers.

We can also use the sort method to sort the array of objects depending on the values of the object, which we want to sort the array of objects. If suppose we would want to sort on the base of the number of users an array of objects in which every object includes the Linux Operating Systems and the number of their users, then we will be using the following:

arr = [
  {name:"Ubuntu", users:3000}
  {name:"Fedora", users:1500}
  {name:"CentOS", users:2000}
  {name:"Debian", users:5000}
  {name:"Kali Linux", users:4000}
]

So, in order to sort on the base of users. The sort function would be like this:

arr.sort(() => { return a.users - b.users })

So, these are the different ways of using the sort method to sort the arrays of any type.

Conclusion

In this article, we have learned how we can sort an array of different types using Javascript’s built-in sort function. This article explains the concept of the sort function from novice to intermediate level in a very easy, profound, and effective way. So, keep on learning, working, and getting experience in Javascript with linuxhint.com to have a better grasp over it. Thank you so much. ]]> Applying JavaScript’s setTimeout Method https://linuxhint.com/javascript_settimeout/ Tue, 27 Oct 2020 10:28:57 +0000 https://linuxhint.com/?p=73890


With the evolution of the internet, JavaScript has grown in popularity as a programming language due to its many useful methods. For example, many websites use JavaScript’s built-in setTimeout method to delay tasks. The setTimeout method has many use cases, and it can be used for animations, notifications, and functional execution delays.Because JavaScript is a single-threaded, translative language, we can perform only one task at a time. However, by using call stacks, we can delay the execution of code using the setTimeout method. In this article, we are going to introduce the setTimeout method and discuss how we can use it to improve our code.

The setTimeout method is a built-in method that takes a callback function as an argument and executes it after a given amount of time. The syntax for the setTimeout method is as follows:

setTimeout(callbackFunction, delay, arguments...)

The callbackFunction is the function we want to execute after a given amount of time; the delay is the time in milliseconds after which we want to execute the callback function; and the arguments are other parameters we want to pass to the callback function.

Now, we will apply the setTimeout method. First, we define a function called linuxhintFunc that prints the string “Hello from Linuxhint.”

function linuxhintFunc() {
 console.log("Hello from Linuxhint.");
}

Next, we call linuxhintFunc in setTimeout and provide a time delay of 2000 ms (2 s).

setTimeout(linuxhintFunc, 2000)

Once the web page is loaded, there is a delay of 2 s before the function is called. We can perform the same task using the arrow function or an anonymous function.

setTimeout(() => {
  console.log("Hello from the Linuxhint");
}, 2000)


Again, there is a delay of 2 s.

Note: The setTimeout method is an asynchronous method, which means that, although JavaScript is a single-threaded language, this function runs on a different thread. The setTimeout method places the function in the queue of the call stack and waits until the call stack is free. If we try to print a message or run a function in setTimeout without a delay, then this action would be jump to the front of the queue first and run when the setTimeout method is executed.

console.log("Hello from the Linuxhint-1")

setTimeout(() => {
  console.log("Hello from the Linuxhint-2")
}, 0)

console.log("Hello from the Linuxhint-3")


Looking at the output, the order of the output is not the same as that of the input. Therefore, the setTimeout function can delay the execution of code.

Conclusion

This article introduces JavaScript’s built-in setTimeout method and discussed how we can use it. We hope that you learned something from this article and that you continue learning about JavaScript with linuxhint.com.

]]>
How to Get Current Date & Time in JavaScript? https://linuxhint.com/how_to_get_current_date_and_time_in_javascript/ Mon, 26 Oct 2020 06:15:30 +0000 https://linuxhint.com/?p=73734

Javascript has become a massively used programming language due to the expansion of the internet and the web at an unbelievable pace. In the modern world of the web, we can do almost every task in one single browser, and Javascript is used in every single website we see in our daily routine life. We frequently used to see the date and time at almost every website. In this article, we are going to have a look at how we can get the current time in Javascript and what are the different ways to get the date and time according to our requirement.

Javascript provides a built-in object Date, which helps in managing all the date and time. Later, we can extract whatever we want according to our needs using different built-in methods. So, let’s just straight jump into the process and learn the different techniques to extract the current date and time.

First of all, we will create a new object of Date() and declare a variable named “current” and assign the new Object of Date() to a “current” variable.

var current = new Date();

After assigning, let’s have a look at the object Date what does it have for us.

console.log(current)

Alright! It looks pretty cool in a good format. But, how about if we want to get only the year from the entire date? We can use the built-in function getFullYear() for getting the year only.

current.getFullYear();

Similarly, if we want to extract only the year, we can use the built-in function getMonths() for getting the month only.

current.getMonth();

There seems like an issue. This is not the 8th month(August)! As we can see in the above complete output for the new Date object. This is September. Well, this is because of the digital(0-11). So, we have to add “1” to it for getting the right month every time.

current.getMonth() + 1;

This is fine now.

Just like for the year, we can do the same for the date. For example, to extract or get only the date, we can use the built-in function getDate().

current.getDate();

Just like a date, we have built-in functions for extracting the desired piece of time. For example, if we want to get or extract the hours only, from the whole current time, we can use the built-in function getHours().

current.getHours();

The same goes for the minutes. To extract minutes only, we can use getMinutes().

current.getMinutes();

To extract seconds only, we can use getSeconds().

current.getSeconds();

Advanced built-in functions

Here we have some advanced built-in functions to get the date and time in a pretty clean and good formatted string. For example, in order to get only the time, not the date, in the form of string we can use the built-in function toLocaleTimeString() to our purpose.

current.toLocaleTimeString(); // "2:42:07 PM"

And, if we want to extract only the time in the form of string. We can use the built-in function toLocaleDateString().

current.toLocaleDateString(); // "9/29/2020"

And, if we want to extract both the date and time in a single string, we can use the built-in function toLocaleString().

current.toLocaleString(); // "9/29/2020, 2:42:07 PM"

So, this is how we can get the date and time using the built-in date object and extract the required months, years, or minutes using different methods.

Conclusion

This article explains how we can get the current date and time and how we can use it to our needs in a very easy, profound, and effective way that any beginner can understand and use. So, keep on learning, working, and getting experience in Javascript with linuxhint.com to have a better grasp over it. Thank you so much!

]]>
Javascript Confirm Method https://linuxhint.com/javascript_confirm_method/ Mon, 26 Oct 2020 02:21:42 +0000 https://linuxhint.com/?p=73650

Javascript is the most known language of the web. Javascript is widely used in front-end development as well as in the back-end. Javascript provides a lot of built-in objects, functions, and methods to help in web development. In this article, we are going to learn one of the javascript’s built-in confirm() method, which is used to show pop-ups over the screen and get the user’s response. The confirm box is a bit different if we try to compare it with the alert box. It is a pop-up that contains a message/text with two buttons, “OK” and “Cancel”. The user won’t be able to do any task while a confirm box is over the screen, and he/she clicks the “OK” or “Cancel” button. This is the reason behind not recommending it’s often used. So, let’s have a look at what is a confirm box and what are the different ways to use it.

The confirm() is basically a method, which is used to show a pop-up box over the web page, and it contains a message or text and two buttons, “OK” & “Cancel”. On the click of the “OK” button, the confirm method returns “true”. Similarly, on the click of the “Cancel” button, it returns false.

Syntax

There are two different syntaxes for showing the confirm box. One of them is using the window’s object

window.confirm(message);

But, we can use the confirm() method without the window’s object as well.

confirm(message);

In this syntax, the message can be any string or a variable that can include a message.
So, let’s try both of the syntaxes.

Examples

First, let’s try with the window’s object

window.confirm("Confirm message from Linuxhint");

And now without window’s object

confirm("Confirm message from Linuxhint");

You will witness that there is no difference in both of them.

The confirm method doesn’t only take the string to show the message. We can provide variable as well, and it worked perfectly fine.

var confirmMessage = Confirm Message using variable';
confirm(confirmMessage);

As you can see in the screenshot below that the message is displayed.

We have learned about providing a variable as well. What if we want to show the pop-up alert box on the screen at the click of a button. For example, we have got some information from the user, and after successfully saving the user’s data on the server, we want to show a confirmation message that “Confirmed”. So, we can simply show a confirmation box like this.

<button>Show Confirm Box!</button>


Or if we are getting a confirmation message from the server, and we want to show the message on the base of the message we got. We can call the function on the button’s onClick method.

<button>Show Confirm Box!</button>

And later in the script, we can write the function in which we can show the confirmation message.

function confirmFunc() {
 var confirmMessage = 'Confirm Box using function';
 confirm(confirmMessage);
}


So, these are some of the different methods of using the confirm() method.

Conclusion

In this article, we have learned about the javascript’s built-in confirm method to show pop-up over the browser’s window. This article has explained the use of the confirm method in a very easy, profound, and effective way that any beginner can understand it and use it. So, keep on learning, working, and getting experience in javascript with linuxhint.com to have a better grasp over it. Thank you so much.

]]>
Applying JavaScript’s Splice Function https://linuxhint.com/javascript_splice/ Sun, 25 Oct 2020 14:46:30 +0000 https://linuxhint.com/?p=73417

JavaScript is a lightweight programming language, and as with any programming language, when developing JavaScript programs, we often need to work with arrays to store data. In this article, we will introduce JavaScript’s built-in splice function and discuss how we can use it to manipulate an array. As data are generated, the structures used for storage must be updated. For this reason, a programmer must often add elements to or remove elements from an array.

The splice function is used to add elements to or remove elements from an array at a given index, and it returns the elements removed from the array. The syntax for the splice function is as follows:

 array.splice(index, removeCount, items...)

Here, index is the position at which we want to add or remove elements, removeCount, which is an optional argument, is the number of elements that we want to remove, and items, which is also optional, contains the elements we want to add.

Now, we will go over a few examples to show how the splice function is implemented.

First, suppose we have an array that consists of five elements.

 let arr = [10,20,30,40,50]

To remove the elements 20 and 30 (at position 1 and position 2 in the array, respectively) from the array, we simply call the splice function and tell it to start from the first index and remove 2 elements.

 arr.splice(1,2);


The values 20 and 30 are returned as the output. Next, we can look at the original array with the following command:

 console.log(arr);


The two elements returned in the output are no longer in the array.

Next, we will add elements to the array using the splice function. Because we will not remove elements from the array, we can provide a value of zero for removeCount and then provide the elements we want to add.

 arr.splice(2, 0, 30, 35);


The above command returns an empty array because no elements were removed. However, if we look at the original array, we can see that it has been updated.

 console.log(arr);

The values 30 and 35 were successfully added at the second index.

Finally, if we want to remove elements and add elements, we can provide values for both removeCount and items.

 arr.splice(1, 2, 15, 20, 25);

The above command has returned the two elements that were removed, and if we print the original array to the console, we can see that 20 and 30 are no longer in the array and that 15, 20 and 25 have been added.

 console.log(arr);

Conclusion

In this article, we discussed several ways to use the splice function to update arrays. We hope you found this article useful and continue to learn JavaScript with linuxhint.com.

]]>
Javascript Trim String https://linuxhint.com/javascript_trim_string/ Sun, 25 Oct 2020 12:39:35 +0000 https://linuxhint.com/?p=73485
Javascript is a scripting or programming language, which is used both on the client-side and back-end of the web. Just like any other language, strings are an important type of the variables, and we often need to manipulate or alter strings as per our needs. While getting data from the user in the form fields, a programmer has to take care of a lot of things. In this article, we will have a look at javascript’s trim() function. We will learn how this function helps in beautifying the strings in javascript and how can we get rid of extra spaces. So, let’s take a look at what is a string and how we can trim the strings.

The string is a simple text or characters which can include the alphabets, numbers, or symbols.

Javascript’s trim() method trims the extra white space from both sides of the strings. Extra white space can be space or tab, etc.

Syntax

Syntax for the trim() method is as follows:

string.trim();

In javascript’s trim string method, we simply call the function over a string, and it trims the string into a clean, space free string. This function doesn’t take any arguments.

Let’s try some examples and understand it.

Examples

First, we suppose a string and add some extra white space around the string.

let str = "   Linuxhint!   "

Now, to get rid of the extra white spaces from both sides, we try to apply the trim() method over that string and see how it works.

str.trim();


We can see in the output that the string is trimmed and there is no extra whitespace left around the string as we desired it to happen.

Now, a question arises: what if we want to trim the string from only the left side or the start of the string and vice versa. There is a built-in function for that as well. There are two different trimStart() and trimLeft() functions, but these both do the same task. So, if we want to trim the string from the left side only and want to keep the whitespaces on the right side. We can use the trimStart() or trimtrimLeft() function.

str.trimStart();

str.trimLeft();


As you can see that both functions do the same task and trim the strings from the left side only.

Similarly, if we want to trim the string from the last or the right side only. We can use any of the trimEnd() or trimRight() functions.

str.trimEnd();

str.trimRight();


It is observed that the string is trimmed only from the right side, as we expected.

So, this is how the javascript’s built-in functions trim(), trimStart(), trimLeft(), trimEnd() and trimRight() works and helps us in getting rid of the extra whitespace around the string.

Conclusion

In this article, we have learned about javascript’s built-in string trim() function and see it’s various implementations. We have also learned about the trimStart() and trimEnd() functions. This article includes profound and explained in-depth knowledge, the need, and the usage of the javascript’s string trim function. So, keep on learning javascript with linuxhint.com.

]]>
JavaScript Sleep Function https://linuxhint.com/javascript_sleep_function/ Sat, 24 Oct 2020 14:34:45 +0000 https://linuxhint.com/?p=72925

Javascript is the language of freedom yet is a function-oriented language at the same time. Unlike other languages, javascript does not provide a built-in sleep() function. You can either build a custom sleep() function using the built-in setTimeout() function, or the latest ECMAScript promises an async-await function. This article shows you how to stop or pause the execution of the sleep function for a desired amount of time using promises or async-await functions.

Before Starting

Before you start to build a sleep function, you need to understand that the setTimeout() function does not work if you expect it to stop the execution. Many programmers and developers try to use the function with loops but fail because the setTimeout() function is used to wait for some given amount of time and then runs the given function. You can, however, use the setTimeout() function to build a sleep function using promise if your purpose is to stop the execution for a desired amount of time.

Using the Sleep Function

So, we will make a custom sleep function in which the function will get time in milliseconds as an argument and return a promise. The promise will include a setTimeout() function, which will pass the resolver as a function and time in milliseconds to the setTimeout() function. So, in the end, the sleep function should look like this:

function sleep(ms){
 return new Promise( resolver => setTimeout(resolver, ms));
};

And now, wherever you want to use this sleep function, you can easily use it.

Now, we will use this sleep function in a couple of examples to show you how to use it in practice.

First, we will try to console some text and call the sleep function. Since the sleep function is returning a promise, we put a then function after it, in which we will console some text and pass the argument ‘5000’ to the sleep function. After running the program, you will see in the console that it will sleep for 5 seconds.

console.log("Sleep function will wait for 10 seconds and then it will print 'Done'");

sleep(5000).then(()=>{
 console.log("Done");
})

You can witness the delay of 5 seconds to get to the “Done” status in the console.

Suppose we want to perform an animation after every 2 seconds. To do so, we will simply write an asynchronous animation function, in which we will animate something, stop the execution for 2 seconds using sleep, and then repeat this process using a for loop for 10 times.

async function animation(ms){
 console.log("starting...");
 for (let i = 0; i < 10; i++) {
  console.log("animation after 2 seconds...")
  await sleep(ms)
}
console.log("This is the end.");
}

After writing the asynchronous animation function, we can now call the animation function.

animation(2000);

After running the code, you will see in the console that the text “animation after 2 seconds” is repeating every two seconds.

Conclusion

This article showed you how to make a custom sleep function, alongside multiple demonstrations. I hope this article has helped you to better understand the usage of sleep function. You can learn more about Javascript at linuxhint.com.

]]>
Javascript Redirect https://linuxhint.com/javascript_redirect/ Fri, 23 Oct 2020 14:45:04 +0000 https://linuxhint.com/?p=72910

Javascript is a web-oriented programming language. When using the web, you will often need to navigate through pages. When you click on any button, submit a form, or log in to any website, you get redirected to a different new page. Page redirection is an essential part of any website, but it is not only restricted to page navigation on a website. There can be multiple reasons to redirect the page, for example:

  • The old domain name is changed to a new domain
  • Submission and Authorization of a form
  • On the base of the browser or language of the user
  • Redirect from HTTP to HTTPS

This article explains a few different ways to redirect a page.

Syntax

The syntax for navigating to a page using javascript is as follows:

window.location.href = "url"

In this method, you simply provide the URL to which you want to redirect the user.

The syntax for another method of redirecting a user to a new URL is as follows:

window.location.replace("url") // or
window.location.assign("url")

In this functional syntax, you provide the URL to which you want to redirect, and whenever this function is called, you will be redirected to that specific URL.

Here, “replace” and “assign” do the same task but with a subtle difference. They both redirect to a new URL, but “replace” does not take the record of history and the user cannot go back to the old URL or previous page. Meanwhile, “assign” keeps the history record and allows the user to go back to the previous page.

We will now look at some examples of both syntaxes.

Examples

First, we will create an on-click function on a button.

<button onclick="redirectFunction()">Linuxhint</button>

This function will redirect the user to the website “https://www.linuxhint.com.”

function redirectFunction() {
window.location.href = "https://www.linuxhint.com"
}

Now, if the user clicks on the button, they will be redirected to linuxhint.com

In this next example, say, you want to redirect the user from an old domain to the new domain. For testing purposes, suppose the current address is the localhost, but whenever the user enters the URL of the localhost, the user gets redirected from the localhost to the new URL, which is linuxhint.com in this example. This is easier to do than you may think. To do this, simply use the syntax of the second redirect method:

window.location.replace("https://www.linuxhint.com")

Now, if the user enters the localhost URL, they will be redirected to linuxhint.com. But, if you look at the top-left button of the browser for going back to the previous page:

the button is dulled and the browser is not allowing us to go back to the previous page. However, if you want to keep this option for the user, you can use “assign” instead of “replace.”

window.location.assign("https://www.linuxhint.com")

And now, if you look at the top-left button of the browser for going back to the previous page:

The button is not dulled. You can go back to the previous page.

It is recommended to use “replace” instead of “assign,” here, because the purpose of redirecting to a new URL is that the old URL is not working or not available anymore.

Conclusion

This article explained a few different methods of redirection in javascript, along with real-life examples using these methods. In this article, you have learned how to navigate to a new page and how to redirect from the old URL to a new URL. You can learn more about javascript at linuxhint.com.

]]>
Joining Arrays in JavaScript https://linuxhint.com/javascript_implode/ Tue, 20 Oct 2020 12:09:56 +0000 https://linuxhint.com/?p=72495
In JavaScript, as in many other scripting and programming languages, we often need to use arrays. Furthermore, it is often useful to combine the elements of an array into a single string. In PHP, for example, the implode function is used to join the elements of an array. In this context, “implode” can be viewed as a synonym for “join”. In JavaScript, however, there is no “implode” function; instead, there is a built-in “join” function that performs the same task. In this article, we are going to examine JavaScript’s join function in some detail.

Syntax

The join function concatenates the elements of an array into a single string. The syntax for the join function is as follows:

array.join(separator)

Here, separator is the string or string used to separate elements of the array; it can be any character or string, such as the space character (i.e., “ ”) or a string like “xyz”, but a comma is used as the default.

Examples

Now, let’s look at some examples.

First, we declare an array of letters.

let arr = ["a", "b", "c", "d", "f"]

We can call the join function for this array without providing a separator as follows, which will return the all characters from the array separated by commas:


Now, let’s see what will happen if we provide the space character as a separator:


Here, in the string returned, the array elements are separated by the space character instead of a comma.

We can provide any character or string as a separator. If we want to put “ and ” between the array’s elements, we can do that as follows:


Here, every alphabet is separated by the “ and ”, which might be very useful for certain applications. Any string can be provided as a separator for joining an array’s elements in the same way.

Conclusion

This article explains JavaScript’s join function and provides some useful examples. We can provide any string we want as a separator to join an array’s elements.

We hope you found this article useful and continue using linuxhint.com to learn about JavaScript.

]]>
Global Variables in Javascript https://linuxhint.com/global_variables_javascript/ Tue, 20 Oct 2020 12:09:55 +0000 https://linuxhint.com/?p=72501
JavaScript is a versatile yet functional language. Variables, which are key to any programming language, can be used to store values that can be accessed at any time. However, when using functions, there are certain factors related to the scope of the function that limit our ability to access a variable.

We cannot access a variable if it is outside the scope of the function, and so the variables we want to use must have the proper scope upon declaration. To avoid issues related to scope, it is important to understand global variables. Therefore, in this article, we are going to discuss global variables and scope.

The scope of a function can be considered as a boundary within which the function can be accessed. However, while a function does not know what is happening beyond the curly brackets that define it, a global variable can be accessed from anywhere in the program.

Syntax

The syntax used to create a global variable, shown below, is no different than that used to create other variables.

var variableName = value

However, the location of this declaration is very important. We will explore this concept more fully by considering some examples.

Example

First, let’s create a function called subtraction.

function subtraction(a,b) {
 var subNum = 23;
}

In this function, we initialized a variable and assigned it a value. Now, we can try to access the variable in another function, i.e., division, and call that function.

function division(a,b) {
 console.log(subNum);
}

division();

However, we get the following reference error because the variable subName is not defined within the correct scope.


This error will occur any time we try to access subNum outside the function in which it is defined. For example:

function subtraction(a,b) {
 var subNum = 23;
};

console.log(subNum);


Here, we still cannot access the variable because it is restricted to the subtraction function.

However, let’s see what happens if we create the variable outside the function—for example, at the beginning of the script:

var globalVar = 11;

Now, let’s try to access it:

console.log(globalVar);

As shown below, we no longer get a reference error.


Furthermore, globalVar should be accessible from any function.

function division(a,b) {
 console.log(globalVar);
}

division();

As you can see below, globalVar is still accessible.

Conclusion

In this article, we explained scope and global variables by using simple examples. We hope you continue learning JavaScript with linuxhint.com.

]]>
The Javascript for…in Loop https://linuxhint.com/javascript_for_in_loop/ Sat, 17 Oct 2020 23:36:43 +0000 https://linuxhint.com/?p=72111
Javascript is one of the most popular programming languages in the world. In any programming language, loops have an essential value. Like many other languages, Javascript provides different loop syntax formats, as well. This article discusses an important Javascript topic known as the for…in loop. Sometimes, we may have to iterate through every single element of an object/array. But, we do not usually know the length of that particular object/array. The for…in loop even comes in handy when working with JSON. In this article, we will take a look at the for…in loop, its syntax, and some examples using this loop.

Javascript’s for…in loop iterates through each property of the object.

Syntax

The syntax of the for…in loop is as follows:

for (const key in object) {

    // body of the for...in loop

}

where,
The key is the variable used in each iteration.
The object is the required object from which to iterate the loop.

Next, we will go over some examples to reinforce the concept and show you how the process works.

Examples

First, we see the simplest implementation of the for…in loop. In this example, we will first assume an object:

let obj = {
 firstName: "John",
 lastName: "Doe"
}

And then, we will iterate through the object and console each property using the for…in loop.

for (const name in obj) {
 console.log(name + " = " + obj[name]);
}


As you can see, the for…in loop has iterated through each property of the obj object and printed each property in the console, as we desired.

Javascript also provides the built-in hasOwnProperty() function. We can perform the hasOwnProperty() check before performing any task in the for…in loop, like this:

for (const name in obj) {
 if (obj.hasOwnProperty(name)) {
  console.log(name + " = " + obj[name]);
 }
}

This function comes in handy when you need to use JSON or for debugging purposes.

When you do not know whether the key holds certain properties, you can also use the for…in syntax for the arrays, as well as for the strings.

let arr = [23,24,25]

for (const value in arr) {
 console.log(value + " = " + arr[value]);
}


Similarly, you can apply this syntax to the strings, as well.

let str = "Linuxhint"

for (const char in str) {
 console.log(char + " = " + str[char]);
}


But, it is not recommended to use the for…in loop for arrays and strings because there are dedicated loops and functions for arrays and strings. Like, for…of or Array.protptype.forEach() is for the arrays for doing the same tasks in better ways.

Conclusion

In this article, you learned how the for…in loop works and how it helps with JSON and debugging. You also learned how to use the for…in loop with arrays and strings, although this loop is dedicated to and recommended for objects. But, I hope this article proved helpful to your understanding of the for…in loop and its various implementations. To learn more about Javascript, you can find more articles at linuxhint.com. ]]>