Welcome to the exciting world of JavaScript! In this lesson, you'll learn the fundamentals of JavaScript, the language that makes web pages dynamic and interactive. We'll cover the basics of variables, data types, functions, and how to manipulate the elements you see on a webpage (DOM manipulation).
JavaScript is the programming language of the web. It allows you to add interactivity to your web pages, making them respond to user actions. JavaScript is typically embedded within HTML files or linked as a separate .js
file.
How JavaScript Works: When a web browser encounters JavaScript code, it executes the code and modifies the content and behavior of the webpage. This happens without requiring a full page reload, making websites feel more responsive and dynamic. JavaScript is what makes a website dynamic (things change) and allows you to make a web application more interactive.
Variables are like containers that store data. In JavaScript, you declare a variable using the keywords let
, const
or var
followed by the variable name and assign a value to it using the assignment operator (=).
Example:
let age = 30; // Declares a variable named 'age' and assigns it the value 30.
const name = "Alice"; // Declares a constant variable named 'name' and assigns it the string "Alice".
Common Data Types:
* String: Represents text (e.g., "Hello World")
* Number: Represents numerical values (e.g., 10, 3.14)
* Boolean: Represents true or false values (e.g., true, false)
* Array: An ordered collection of values (e.g., [1, 2, 3]
)
* Object: A collection of key-value pairs (e.g., { name: "Bob", age: 25 }
)
Example of different data types:
let message = "Hello, world!"; // String
let count = 10; // Number
let isActive = true; // Boolean
let numbers = [1, 2, 3, 4, 5]; // Array
let person = { name: "John", age: 30 }; // Object
Note: const
is used to declare variables whose values should not be changed. Use let
when the variable value may change. var
is an older way of declaring variables that has some quirks, so generally avoid using var
.
Functions are blocks of reusable code designed to perform a specific task. You define a function using the function
keyword, followed by a name, a set of parentheses (which can include parameters), and curly braces that enclose the code to be executed. Functions can also return values using the return
keyword.
Example:
function greet(name) {
return "Hello, " + name + "!"; // Returns a string greeting.
}
let greeting = greet("World"); // Calls the function with "World" as the argument. greeting now equals "Hello, World!"
console.log(greeting); // Outputs: Hello, World!
Functions can accept parameters (input) and return values (output). This modularity allows for reusable and organized code.
function addNumbers(a, b) {
return a + b;
}
let sum = addNumbers(5, 3); // sum will be 8
console.log(sum); // Outputs: 8
The Document Object Model (DOM) represents the structure of an HTML document as a tree-like structure of objects. JavaScript can be used to access and modify these objects, allowing you to change the content, structure, and style of a webpage.
Key Methods:
* document.getElementById(id)
: Selects an HTML element with a specific ID.
* document.querySelector(selector)
: Selects the first HTML element that matches a CSS selector.
* element.innerHTML
: Gets or sets the HTML content of an element.
* element.textContent
: Gets or sets the text content of an element.
* element.style.propertyName = 'value'
: Sets the style property of an element.
Example:
<p id="myParagraph">This is a paragraph.</p>
<button onclick="changeText()">Change Text</button>
<script>
function changeText() {
let paragraph = document.getElementById("myParagraph");
paragraph.textContent = "Text changed by JavaScript!";
}
</script>
In this example, clicking the button calls the changeText() function, which uses document.getElementById()
to find the paragraph element and change its text content using textContent
.
Explore advanced insights, examples, and bonus exercises to deepen understanding.
Welcome back! You've mastered the JavaScript basics. Now, let's delve deeper and explore more advanced concepts that will empower you to build more interactive and dynamic web experiences.
While you've learned about variables, data types, functions, and DOM manipulation, there's a lot more to discover. This section introduces some essential concepts.
Practice makes perfect! Here are some exercises to solidify your understanding.
Create a function that defines a variable using `let` inside the function. Try to access that variable *outside* the function and observe the result (e.g., in the browser's console). Then, redefine the variable using `var` to observe how the scope changes.
function exampleFunction() {
let functionScopedVariable = "I'm function-scoped";
console.log(functionScopedVariable); // Accessible here
}
exampleFunction();
// console.log(functionScopedVariable); // What happens here?
function exampleFunction2() {
var functionScopedVariable2 = "I'm var scoped";
console.log(functionScopedVariable2);
}
exampleFunction2();
console.log(functionScopedVariable2)
Create a JavaScript object representing a "book" with properties like `title`, `author`, and `pages`. Use both dot and bracket notation to access the properties.
const book = {
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
pages: 180
};
// Access properties using dot notation:
console.log(book.title);
// Access properties using bracket notation:
console.log(book["author"]);
JavaScript is everywhere! Here are some real-world examples to illustrate the concepts you've learned.
Ready for a challenge? Try these tasks:
The JavaScript journey never ends! Consider exploring these topics:
Create three variables: one named `firstName` and assign it your first name as a string, one named `age` and assign it your age as a number, and one named `isStudent` and assign it a boolean value (true if you are a student, false otherwise). Use `console.log()` to output the value of each variable to the console.
Write a function named `calculateSum` that takes two numbers as input (parameters) and returns their sum. Test your function by calling it with two numbers and logging the result to the console.
Create an HTML file with a heading (`<h1>`), a paragraph (`<p>`), and a button. Write JavaScript code that: 1. Selects the paragraph element using `document.getElementById()`. 2. When the button is clicked (use an `onclick` event), change the paragraph's text content to "You clicked the button!" using `textContent` or `innerHTML`.
Create a simple webpage that displays a greeting message. Include a text input field where the user can enter their name and a button. When the user clicks the button, update a `<h1>` heading on the page to say "Hello, [User's Name]!" (Use DOM manipulation).
Prepare for Day 4, which will cover more advanced DOM manipulation, event handling, and working with forms in JavaScript. Familiarize yourself with how to include external Javascript files using the `<script src="..."></script>` tag.
We're automatically tracking your progress. Sign up for free to keep your learning paths forever and unlock advanced features like detailed analytics and personalized recommendations.