JS Syntax

JavaScript Syntax

JavaScript syntax is the set of rules that define a correctly structured JavaScript program. Let’s go through some of the fundamental aspects of JavaScript syntax.

1. Variables

Variables are used to store data values. You can declare variables using varlet, or const.

let x = 5;
const y = 10;
var z = x + y;
console.log(z); // Output: 15

2. Data Types

JavaScript supports various data types including numbers, strings, arrays, and objects.

let number = 42; // Number
let text = "Hello, World!"; // String
let array = [1, 2, 3]; // Array
let object = { name: "John", age: 30 }; // Object

3. Operators

Operators are used to perform operations on variables and values.

let a = 10;
let b = 5;
let sum = a + b; // Addition
let difference = a - b; // Subtraction
let product = a * b; // Multiplication
let quotient = a / b; // Division
console.log(sum, difference, product, quotient); // Output: 15, 5, 50, 2

4. Functions

Functions are blocks of code designed to perform a particular task. They are executed when “called” (invoked).

function greet(name) {
    return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Output: Hello, Alice!

5. Conditionals

Conditional statements are used to perform different actions based on different conditions.

let age = 18;
if (age >= 18) {
    console.log("You are an adult.");
} else {
    console.log("You are a minor.");
}
// Output: You are an adult.

6. Loops

Loops are used to execute a block of code a number of times.

for (let i = 0; i < 5; i++) {
    console.log(i);
}
// Output: 0, 1, 2, 3, 4

7. Arrays

Arrays are used to store multiple values in a single variable.

let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: Apple

8. Objects

Objects are collections of properties, and a property is an association between a name (or key) and a value.

let person = {
    firstName: "John",
    lastName: "Doe",
    age: 25
};
console.log(person.firstName); // Output: John

Conclusion

Understanding JavaScript syntax is crucial for writing effective and efficient code. By mastering variables, data types, operators, functions, conditionals, loops, arrays, and objects, you’ll be well on your way to becoming proficient in JavaScript.

Share this Tutorials

JS Syntax

Or copy link

CONTENTS
Scroll to Top