JavaScript Tutorial
Learn JavaScript step by step with easy examples
What is JavaScript?
JavaScript is a programming language that makes websites interactive. While HTML creates the structure and CSS makes it look good, JavaScript makes things happen when users click buttons, fill out forms, or interact with the page.
JavaScript can:
- Change HTML content and CSS styles
- Respond to user clicks, keyboard input, and mouse movements
- Validate form data before sending it
- Create animations and interactive effects
- Load new content without refreshing the page
How to Add JavaScript to HTML
There are three ways to add JavaScript to your webpage:
Quick but not recommended for complex code
Good for small scripts
Best for larger projects
Variables
Variables store data that you can use later. Think of them as labeled boxes that hold information:
Variable Rules:
- • Use
letfor variables that can change - • Use
constfor variables that stay the same - • Variable names can contain letters, numbers, and underscores
- • Variable names cannot start with a number
- • Variable names are case-sensitive (age and Age are different)
Functions
Functions are reusable blocks of code. They're like recipes - you write them once and use them many times:
Function Tips:
- • Give functions descriptive names (calculateTotal, not calc)
- • Use
returnto send a value back - • Functions can call other functions
- • Test your functions with different inputs
Events
Events happen when users interact with your webpage. JavaScript can "listen" for these events and respond:
message
">Changing HTML with JavaScript
JavaScript can find HTML elements and change their content, style, and attributes:
New paragraph
";Conditions (If Statements)
Conditions let your code make decisions. Use them to do different things based on different situations:
Comparison Operators:
=== Equal to
!== Not equal to
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
Loops
Loops repeat code multiple times. They're useful when you need to do the same thing over and over:
Arrays (Lists)
Arrays store multiple values in a single variable. Think of them as lists:
Array Tips:
- • Array indexes start at 0, not 1
- • Use
lengthto get the number of items - • Arrays can hold different types of data
- • Use
push()to add items
Objects
Objects store related information together. They're like real-world objects with properties:
Practical Examples
Here are some real-world examples you can try in your own projects:
result
">- taskList
") + "";
Practice Exercise
Create an interactive webpage with JavaScript that includes:
- A button that changes the page background color when clicked
- A text input where users can enter their name
- A greeting that appears when they click a "Greet Me" button
- A simple counter that increases when you click a button
- A list where you can add new items
Use our code editor to practice! Start with HTML structure, add CSS styling, then make it interactive with JavaScript.