let’s start with some basics of JavaScript. JavaScript is a versatile and fomous programming language that is primarily used to add interactivity to web pages.
Here are some basic fundamental concepts to get you started.
1. Variables and Data Types
In JavaScript, you can use the var, let, or const keywords to declare variables. Data is stored and manipulated via variables. JavaScript has various data types, including:
Number: Represents numeric values.String: Represents text.Boolean: Represents true or false values.Array: Represents a collection of values.Object: Represents a collection of key-value pairs.
Example
let num = 42; // Number
let greeting = "Hello, World!"; // String
let isTrue = true; // Boolean
let fruits = ['apple', 'orange', 'banana']; // Array
let person = { name: 'John', age: 25 }; // Object2. Operators
JavaScript supports various operators for performing operations on variables and values. Common operators include:
- Arithmetic operators:
+, -, *, /, % - Comparison operators:
==, ===, !=, !==, <, >, <=, >= - Logical operators:
&& (AND), || (OR), ! (NOT)
Example
let x = 5;
let y = 10;
let sum = x + y; // Addition
let isGreaterThan = x > y; // Comparison
let logicalResult = (x < 10 && y > 5); // Logical AND3. Control Flow
JavaScript supports conditional statements (if, else if, else) and loops (for, while, do-while) for controlling the flow of your program.
Example
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
// Loop example
for (let i = 0; i < 5; i++) {
console.log(i);
}4. Functions
Functions are like little packages of code that you can reuse whenever you need them. You can create functions using the “function” keyword.
Example
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice");5. Events and Event Handling
JavaScript is commonly used to response to user actions. You can handle events like clicks, key presses, etc., using event listeners.
Example
let button = document.getElementById('myButton');
button.addEventListener('click', function() {
console.log('Button clicked!');
});
These are just the basics, and there’s a lot more to explore as you progress. Try experimenting with these concepts in a code editor.