JavaScript Basics

Learn the basics of JavaScript, a popular programming language used for web development.

July 8, 2024 (6mo ago)

  1. Create an HTML file

Create a new file with a .html extension. For example, index.html.

  1. Include JavaScript in the HTML file
  • method 1 : using script tag
  • method 2 : direct Html injection
<!doctype html>
<html>
  <head>
    <title>My First JavaScript</title>
    <script src="location to file path">
      //Method 2
    </script>
  </head>
  <body>
    <h1>Hello World!</h1>
    <button onclick="displayAlert()">Click me</button>
 
    <script>
      //Method 2
      function displayAlert() {
        alert("Hello, JavaScript!");
      }
    </script>
  </body>
</html>
  1. Variables and Data Types

JavaScript has different data types like string, number, boolean, null, undefined, and object.

let name = "John"; // string
let age = 20; // number
let isAdult = true; // boolean
let height; // undefined
let weight = null; // null
let person = { firstName: "John", lastName: "Doe" }; // object
  1. Arrays

An array is a special variable, which can hold more than one value at a time.

let fruits = ["Apple", "Banana", "Cherry"];
  1. Functions

Functions are blocks of code designed to perform a particular task.

function greet(name) {
  return "Hello, " + name;
}
console.log(greet("John")); // Hello, John
  1. Control Structures

Control structures like if, else, for, while, etc. are used to control the flow of execution.

let number = 10;
if (number > 5) {
  console.log("Number is greater than 5");
} else {
  console.log("Number is not greater than 5");
}
 
for (let i = 0; i < 5; i++) {
  console.log(i);
}
  1. Objects

Objects are collections of key-value pairs.

let person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  greet: function () {
    return "Hello, " + this.firstName;
  },
};
console.log(person.greet()); // Hello, John