JavaScript syntax refers to the rules that define the structure and organization of JavaScript code. Following proper syntax is crucial for writing functional and error-free JavaScript programs. Here are some important aspects of JavaScript syntax:
Example:
// This is a single-line comment
/*
This is a
multi-line
comment
*/
Examples:
var x = 10;
let message = "Hello";
const PI = 3.14;
Examples:
let num = 42;
let text = "Hello";
let isTrue = true;
let fruits = ["apple", "banana", "orange"];
let person = { name: "John", age: 30 };
let greet = function() { console.log("Hello!"); };
5. Operators:
Examples:
let sum = 5 + 3;
let isEqual = (x === y);
let isAnd = (a && b);
Examples:
if (x > 10) {
console.log("x is greater than 10");
} else {
console.log("x is less than or equal to 10");
}
for (let i = 0; i < 5; i++) {
console.log(i);
}
while (condition) {
// code block
}
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default code block
}
Examples:
function greet(name) {
return "Hello, " + name + "!";
}
let result = greet("Alice");
console.log(result);
Examples:
let person = { name: "John", age: 30 };
console.log(person.name);
let fruits = ["apple", "banana", "orange"];
console.log(fruits[1]);
Examples:
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
// Using template literals
let message = `Hello, ${fullName}!`;
Proper JavaScript syntax is essential for writing readable and error-free code. Understanding these syntax rules allows developers to create functional and efficient JavaScript programs. It's important to follow these guidelines while coding to ensure your scripts behave as expected and are easy to maintain.