This is JavaScript

This is JavaScript

JavaScript is a high-level programming language that is widely used for creating dynamic and interactive websites. It is a client-side scripting language that runs on the browser side of things and is used to add interactivity and functionality to web pages.

How to use JavaScript in HTML

To include JavaScript code in an HTML document, you can use the <script> tag like this:

<script>
// JavaScript code goes here
</script>

You can include the JavaScript code within the HTML document using the <script> tag in two ways:

  • Inline JavaScript: This is where the JavaScript code is included directly within an HTML element like this:
<p onclick="alert('Hello, World!')">Click me!</p>
  • External JavaScript: This is where the JavaScript code is saved in a separate file with a .js extension and then linked to the HTML document using the <script> tag like this:
<script src="path/to/your/javascript/file.js"></script>

Using an external JavaScript file is recommended because it allows you to separate your code from your HTML document, making your HTML document cleaner and easier to read.

Basic Syntax of JavaScript

The basic syntax of JavaScript includes variables, data types, operators, conditional statements, loops, functions, and events. Here is an example of a simple JavaScript program that displays a message on the screen:

var message = "Hello, World!";
alert(message);

The above code declares a variable called message and assigns it the value "Hello, World!". The alert() function then displays the value of the message variable in a pop-up window.

Syntax highlighting with highlight.js

Highlight.js is a popular open-source library that provides syntax highlighting for various programming languages, including JavaScript. To use highlight.js in your HTML document, you need to include the JavaScript and CSS files in the <head> section of your HTML document like this:

<head>
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/styles/default.min.css">
  <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/highlight.min.js"></script>
</head>

Once you have included the necessary files, you can use the hljs class to highlight your code like this:

<pre><code class="hljs javascript">
var message = "Hello, World!";
alert(message);
</code></pre>

In the above code, the hljs class is used to highlight the code within the <pre> and <code> tags. The javascript class is used to specify the language being highlighted.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe