JavaScript syntax is the set of rules that define how JavaScript programs are constructed. Let’s dive into some of the basic syntax elements of JavaScript.
Variables and Data Types
One of the first things you’ll encounter in JavaScript is the declaration of variables. Variables are containers for storing data values. In JavaScript, you can declare variables using the var
, let
, or const
keywords.
// Variable declaration using var
var age = 25;
// Variable declaration using let
let name = "Junaid";
// Variable declaration using const
const PI = 3.14;
JavaScript supports various data types, including numbers, strings, booleans, arrays, and objects. Understanding these types is crucial for effective programming.
// Numbers
let num = 42;
// Strings
let greeting = "Hello, World!";
// Booleans
let isTrue = true;
// Arrays
let fruits = ["apple", "banana", "orange"];
// Objects
let person = { name: "Junaid", age: 29 };
Operators
JavaScript includes arithmetic operators (+
, -
, *
, /
, %
) and assignment operators (=
, +=
, -=
, etc.).
var x = 10;
x += 5; // x now is 15
Control Flow Statements
Control flow statements enable you to control the flow of your program based on certain conditions. The most common statements are if
, else if
, and else
.
let temperature = 25;
if (temperature > 30) {
console.log("It's a hot day!");
} else if (temperature > 20) {
console.log("It's a warm day.");
} else {
console.log("It's a cold day.");
}
Loops
Loops allow you to repeatedly execute a block of code. The two main types of loops in JavaScript are for
and while
.
// For loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While loop
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
Functions
Functions are reusable blocks of code that perform a specific task. They are essential for organizing and modularizing your code.
function add(a, b) {
return a + b;
}
let result = add(3, 5);
console.log(result); // Output: 8
Events and Callbacks
JavaScript is often used to create dynamic and interactive web pages. Events and callbacks play a crucial role in handling user interactions.
// Event listener
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});