• Introduction
  • Variables
  • Functions
  • Objects
  • Arrays
  • Classes
  • Inheritance
  • Promises
  • Async/Await
  • Modules
  • Iterators
  • Generators
  • Symbols
  • Closures
  • this keyword
  • DOM Manipulation
  • DOM Events
  • AJAX
  • JSON
  • Web Storage
  • Regular Expressions
  • Error Handling
  • Debugging
  • Type Checking
  • Security
  • Performance
  • Strict Mode
  • Style Guide
  • Best Practices
  • Testing
  • Tools
  • Resources

title: JavaScript Introduction

JavaScript Introduction

JavaScript is a versatile programming language commonly used for web development. It allows you to add interactivity and dynamic behavior to your web pages.

Basic JavaScript Example

Here's a simple JavaScript example that displays a "Hello, World!" message:

const greeting = "Hello, World!";
console.log(greeting);

// Output: Hello, World!

JavaScript in HTML

You can add JavaScript to your HTML documents in two ways:

  • Inline: Add JavaScript directly to your HTML document using the <script> tag.
  • External: Add JavaScript to your HTML document using an external JavaScript file.

Inline JavaScript

You can add JavaScript directly to your HTML document using the <script> tag. The <script> tag can be placed in the <head> or <body> section of your HTML document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Inline JavaScript</title>
    <script>
      const greeting = "Hello, World!";
      console.log(greeting);
    </script>
  </head>
  <body></body>
</html>

External JavaScript

You can also add JavaScript to your HTML document using an external JavaScript file. The <script> tag should be placed in the <head> section of your HTML document. The src attribute specifies the path to the external JavaScript file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>External JavaScript</title>
    <script src="script.js"></script>
  </head>
  <body></body>
</html>

JavaScript Output

JavaScript can display data in different ways:

  • console.log() - Displays data in the browser console.
  • alert() - Displays data in an alert box.
  • document.write() - Displays data in the HTML document.

console.log()

The console.log() method displays data in the browser console. The browser console can be accessed by pressing F12 or Ctrl + Shift + I on Windows and Cmd + Opt + I on Mac.

const greeting = "Hello, World!";
console.log(greeting);

// Output: Hello, World!

alert()

The alert() method displays data in an alert box.

const greeting = "Hello, World!";
alert(greeting);

// Output: Hello, World!

document.write()

The document.write() method displays data in the HTML document.

const greeting = "Hello, World!";
document.write(greeting);

// Output: Hello, World!