JavaScript Syntax
JavaScript syntax is the set of rules that define a correctly structured JavaScript program. The following sections provide an overview of the basic syntax and rules you need to follow when writing JavaScript code.
1. Variables
Variables are used to store data values. In JavaScript, you can declare variables using var
, let
, or const
.
let name = 'John';
const age = 30;
var isActive = true;
2. Data Types
JavaScript supports various data types, including:
- String: Represents a sequence of characters. Example:
'Hello'
- Number: Represents numeric values. Example:
42
- Boolean: Represents true or false values. Example:
true
- Object: Represents a collection of key-value pairs. Example:
{name: 'John', age: 30}
- Array: Represents a list of values. Example:
[1, 2, 3, 4]
3. Functions
Functions are blocks of code designed to perform a particular task. Functions can be declared using the function
keyword.
function greet(name) {
return 'Hello, ' + name;
}
console.log(greet('Alice'));
4. Control Flow
JavaScript includes several control flow statements, such as if
, else
, for
, and while
.
if (age >= 18) {
console.log('Adult');
} else {
console.log('Minor');
}
for (let i = 0; i < 5; i++) {
console.log(i);
}
5. Comments
Comments are used to describe code and are ignored by the JavaScript engine. Use //
for single-line comments and /* ... */
for multi-line comments.
// This is a single-line comment
/*
This is a multi-line comment
*/