JavaScript Fundamentals
JavaScript is the programming language of the Web. It is used to make web pages interactive and dynamic.
How to Add JavaScript
JavaScript can be added to an HTML document in two ways: internally using the
<script>
tag, or externally by linking to a .js
file.
<!-- Internal JavaScript -->
<script>
console.log("Hello, World!");
</script>
<!-- External JavaScript -->
<script src="myscripts.js"></script>
Variables (var, let, const)
Variables are containers for storing data values. In JavaScript, we use var
,
let
, and const
to declare variables.
var
: Function-scoped. It's the old way of declaring variables.let
: Block-scoped. Allows you to reassign the value.const
: Block-scoped. The value cannot be reassigned.
var name = "Developergtm"; // Function-scoped
let age = 5; // Block-scoped, can be changed
const PI = 3.14; // Block-scoped, cannot be changed
age = 6; // This is valid
// PI = 3.1415; // This will cause an error
Data Types
JavaScript has several primitive data types:
- String: Text, e.g.,
"Hello"
- Number: Numeric values, e.g.,
100
- Boolean: True or false
- Undefined: A variable that has been declared but not assigned a value
- Null: Represents the intentional absence of any object value
And one complex data type:
- Object: A collection of key-value pairs
Functions
A function is a block of code designed to perform a particular task. A function is executed when "something" invokes it (calls it).
Pro Tip: Arrow Functions
ES6 introduced arrow functions, which provide a shorter syntax for writing functions. They are great for simple, one-line functions.
// Regular Function
function greet(name) {
return "Hello, " + name;
}
// Arrow Function
const add = (a, b) => a + b;
console.log(greet("World")); // "Hello, World"
console.log(add(5, 3)); // 8
DOM Manipulation
The HTML DOM (Document Object Model) is a programming interface for web documents. JavaScript can be used to change the content, style, and structure of a web page.
// Find an element by its ID
const heading = document.getElementById("myHeading");
// Change its text content
heading.textContent = "Welcome to Developergtm!";
// Change its color
heading.style.color = "purple";