JavaScript is one of the most popular programming languages in the world.
Here are some basic syntax examples that every beginner should know.
1. Variable Declarations
let name = "Usama";
let age = 22;
let isStudent = true;
let job = null;
let hobbies = ["reading", "gaming", "coding"];
let address = {
street: "123 Main St",
city: "Anytown",
country: "Pakistan",
};
2. Function Declaration
function greet() {
console.log(`Hello, my name is ${name} and I am ${age} years old.`);
}
3. Conditional Statement
if (isStudent) {
console.log("I am a student.");
} else {
console.log("I am not a student.");
}
4. Loop Example
for (let i = 0; i < hobbies.length; i++) {
console.log(`Hobby ${i + 1}: ${hobbies[i]}`);
}
5. Object Method
function displayAddress() {
console.log(
`I live at ${address.street}, ${address.city}, ${address.country}.`
);
}
6. Arrow Function
const add = (a, b) => a + b;
7. Template Literals
const message = `My name is ${name} and I am ${age} years old.
I enjoy ${hobbies.join(", ")}.`;
console.log(message);
8. Destructuring Assignment
const { street, city, country } = address;
console.log(`Address: ${street}, ${city}, ${country}`);
9. Spread Operator
const newHobbies = [...hobbies, "traveling", "photography"];
console.log("Updated hobbies:", newHobbies);
10. Rest Parameter
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log("Sum of numbers:", sum(1, 2, 3, 4, 5));
11. Default Parameters
function multiply(a, b = 1) {
return a * b;
}
console.log("Multiplication result:", multiply(5)); // b defaults to 1
12. For...of Loop
for (const hobby of hobbies) {
console.log(`Hobby: ${hobby}`);
}
13. For...in Loop
for (const key in address) {
console.log(`${key}: ${address[key]}`);
}
β Summary
In this example, we covered:
- Variables (
let
,const
) - Functions & Arrow Functions
- Conditionals (if/else)
- Loops (
for
,for...of
,for...in
) - Objects & Methods
- Template Literals, Spread, Rest, Default Parameters
This is a beginner-friendly overview of JavaScriptβs basic syntax. π
Top comments (0)