JavaScript Introduction

JavaScript is a versatile and powerful programming language used to create interactive and dynamic web content. It runs in the browser, making it a key component of modern web development alongside HTML and CSS.

1. What is JavaScript?

JavaScript is a high-level, interpreted scripting language that enables you to create dynamically updating content, control multimedia, animate images, and much more.

2. Why Learn JavaScript?

  • Interactivity: Makes web pages interactive.
  • Rich Interfaces: Enables features like drag-and-drop components and sliders.
  • Versatility: Can be used on both client-side and server-side (with Node.js).

3. Basic Syntax

JavaScript is case-sensitive and uses curly brackets {} to define code blocks.

4. Embedding JavaScript in HTML

JavaScript can be added to an HTML file in three main ways:

  • Inline: <script>console.log('Hello, World!');</script>
  • Internal: Place <script> tags in the HTML file within <head> or <body>.
  • External: Link an external JavaScript file using <script src="path/to/file.js"></script>.

5. Variables

Used to store data values.

var x = 5;
let y = 10;
const z = 15;

Try It Now

6. Data Types

Common data types in JavaScript:

  • String: "Hello, World!"
  • Number: 42
  • Boolean: true or false
  • Object: { name: "John", age: 30 }
  • Array: [1, 2, 3, 4]

7. Functions

Reusable blocks of code.

function greet(name) {
  return "Hello, " + name;
}
console.log(greet("Alice"));

Try It Now

8. Conditional Statements

Used to perform different actions based on different conditions.

if (x > 10) {
  console.log("x is greater than 10");
} else {
  console.log("x is less than or equal to 10");
}

Try It Now

9. Loops

Used to repeat a block of code multiple times.

for (let i = 0; i < 5; i++) {
  console.log("Iteration " + i);
}

Try It Now

10. Events

JavaScript can react to events like mouse clicks or keypresses.

document.getElementById("myButton").onclick = function() {
  alert("Button clicked!");
};

Try It Now

11. DOM Manipulation

The Document Object Model (DOM) represents the structure of a webpage, and JavaScript can manipulate this structure.

document.getElementById("demo").innerHTML = "Hello, JavaScript!";

Try It Now

Conclusion

JavaScript is a foundational technology for web development, allowing developers to create interactive and dynamic web pages. Starting with basic syntax and concepts like variables, functions, and events, beginners can gradually build more complex and feature-rich web applications.