Introduction to JavaScript
JavaScript is a high-level, dynamic programming language primarily used for creating interactive elements on web pages. It is supported by all modern web browsers and is an integral part of web development alongside HTML and CSS.
Setting Up Your Environment
Before we dive into coding, you need to set up your development environment:
- Text Editor: Choose a text editor like Visual Studio Code, Sublime Text, or Atom.
- Web Browser: Ensure you have a modern web browser like Google Chrome or Mozilla Firefox.
- Console: Access the browser's console to test your JavaScript code. You can open it using
Ctrl + Shift + J
in Chrome orCtrl + Shift + K
in Firefox.
Writing Your First JavaScript Code
Let's start with a simple "Hello, World!" program:
console.log('Hello, World!');
This code prints "Hello, World!" to the console. To run it, open your browser's console, paste the code, and press Enter.
Variables and Data Types
JavaScript variables are used to store data values. You can declare variables using var
, let
, or const
.
- var: Function-scoped, can be redeclared.
- let: Block-scoped, cannot be redeclared.
- const: Block-scoped, cannot be redeclared or reassigned.
let name = 'John';
const age = 25;
var isStudent = true;
Basic Data Types
- String: Text, enclosed in single or double quotes.
- Number: Numeric values.
- Boolean:
true
orfalse
. - Array: A list of values.
- Object: Key-value pairs.
Functions
Functions are reusable blocks of code that perform a specific task. You can define a function using the function
keyword.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('Alice'));
Conditionals
Conditional statements control the flow of your code based on conditions.
let score = 85;
if (score >= 90) {
console.log('A');
} else if (score >= 80) {
console.log('B');
} else {
console.log('C');
}
Loops
Loops execute a block of code repeatedly.
- for loop:
for (let i = 0; i < 5; i++) {
console.log(i);
}
- while loop:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Arrays and Objects
Arrays and objects are fundamental data structures in JavaScript.
- Array:
let fruits = ['Apple', 'Banana', 'Cherry'];
console.log(fruits[0]); // Apple
- Object:
let person = {
name: 'John',
age: 25,
isStudent: true
};
console.log(person.name); // John
DOM Manipulation
JavaScript can interact with and manipulate HTML and CSS. The Document Object Model (DOM) represents the structure of a web page.
document.getElementById('demo').innerHTML = 'Hello, World!';
Events
JavaScript can handle user interactions through events.
document.getElementById('myButton').addEventListener('click', function() {
alert('Button clicked!');
});