In JavaScript, variables are used to store data. You can declare variables using var
, let
, or const
.
// Using var
var age = 25;
// Using let
let name = "John";
// Using const
const PI = 3.14;
JavaScript has several data types, including:
number
, string
, boolean
, null
, undefined
, symbol
.object
// Number
let num = 10;
// String
let str = "Hello, World!";
// Boolean
let isTrue = true;
// Null
let nothing = null;
// Undefined
let notDefined;
// Symbol
let sym = Symbol('unique');
// Object
let person = {
name: "Alice",
age: 30
};
Functions are reusable blocks of code that perform a specific task.
// Function declaration
function add(a, b) {
return a + b;
}
// Function call
let result = add(3, 5);
console.log(result);
Control structures allow you to control the flow of your program. Common control structures include if - else
, switch
, for
, while
, and do - while
.
// if - else
let num = 10;
if (num > 5) {
console.log("The number is greater than 5");
} else {
console.log("The number is less than or equal to 5");
}
// for loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
Objects are used to store key - value pairs, while arrays are used to store a collection of values.
// Object
let car = {
brand: "Toyota",
model: "Corolla",
year: 2020
};
// Array
let fruits = ["Apple", "Banana", "Orange"];
You can add JavaScript code directly to an HTML file using the <script>
tag.
<!DOCTYPE html>
<html>
<body>
<button onclick="alert('Hello!')">Click me</button>
<script>
// Inline JavaScript
console.log("This is inline JavaScript");
</script>
</body>
</html>
It is a good practice to keep your JavaScript code in separate files for better organization.
index.html
<!DOCTYPE html>
<html>
<body>
<script src="script.js"></script>
</body>
</html>
script.js
console.log("This is an external JavaScript file");
The Document Object Model (DOM) represents the HTML document as a tree of objects. You can use JavaScript to manipulate the DOM.
<!DOCTYPE html>
<html>
<body>
<p id="demo">This is a paragraph.</p>
<script>
// Select the element
let para = document.getElementById('demo');
// Change the text content
para.textContent = "The text has been changed.";
</script>
</body>
</html>
You can use try - catch - finally
blocks to handle errors in JavaScript.
try {
let result = 10 / 0;
console.log(result);
} catch (error) {
console.log("An error occurred: " + error.message);
} finally {
console.log("This block always executes");
}
Event handling allows you to respond to user actions such as clicks, keypresses, etc.
<!DOCTYPE html>
<html>
<body>
<button id="myButton">Click me</button>
<script>
let button = document.getElementById('myButton');
button.addEventListener('click', function () {
alert('Button was clicked!');
});
</script>
</body>
</html>
// Calculate the area of a rectangle
function calculateRectangleArea(length, width) {
return length * width;
}
Global variables can lead to naming conflicts and make your code hard to maintain. Instead, use local variables inside functions.
function calculate() {
let localVar = 10;
// Do something with localVar
}
Break your code into smaller, reusable modules. You can use ES6 modules to achieve this.
math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
main.js
import { add, subtract } from './math.js';
let result1 = add(3, 5);
let result2 = subtract(10, 4);
JavaScript is a powerful and versatile programming language that is essential for modern web development. By understanding the fundamental concepts, usage methods, common practices, and best practices outlined in this guide, beginners can start writing efficient and maintainable JavaScript code. As you continue to learn and practice, you will discover more advanced features and techniques that will further enhance your programming skills.