JavaScript syntax defines the set of rules for writing valid JavaScript code. Understanding syntax is the foundation of mastering JavaScript programming. Let's dive into the key aspects of JavaScript syntax.
JavaScript uses the Unicode character set, which includes:
Letters (A-Z, a-z)
Digits (0-9)
Special characters like + - * / %
Punctuation marks ; , .
Whitespaces and escape sequences (like \n
for a new line)
Values are the fundamental units of JavaScript programming. They can be:
Fixed values (also called literals) like 10
, "Hello"
, or true
Variable values stored in identifiers, e.g., let age = 25;
Literals are constant values directly written in code. Some common types include:
Number literals: 42
, 3.14
String literals: 'JavaScript'
, "Hello"
Boolean literals: true
, false
Null and Undefined literals: null
, undefined
Object literals: { name: "John", age: 30 }
Array literals: [1, 2, 3, 4]
Variables store data in JavaScript. They are declared using:
var
(old way, not recommended for modern JS)
let
(preferred for variables that can change)
const
(used for values that should not change)
let name = "Alice";
const age = 25;
var city = "New York";
Operators perform operations on values and variables. Some common types:
Arithmetic Operators: +
, -
, *
, /
, %
Comparison Operators: ==
, ===
, !=
, <
, >
Logical Operators: &&
, ||
, !
Assignment Operators: =
, +=
, -=
, *=
let sum = 5 + 3; // 8
let isEqual = (10 === "10"); // false
Expressions produce values. Examples:
Arithmetic expression: 10 + 20
(produces 30
)
Boolean expression: 5 > 3
(produces true
)
Function call expression: Math.max(5, 10)
Keywords are reserved words with special meanings in JavaScript. Some common ones:
if
, else
, return
, function
, class
, break
, switch
, try
, catch
if (age > 18) {
console.log("Adult");
} else {
console.log("Minor");
}
Comments improve code readability and are ignored by the JavaScript engine.
Single-line comment: // This is a comment
Multi-line comment:
/*
This is a multi-line comment
*/
Identifiers are names given to variables, functions, or objects.
Must start with a letter, _
, or $
Cannot be a JavaScript keyword
Case-sensitive (myVar
and myvar
are different)
let firstName = "John";
let $price = 100;
let _count = 5;
JavaScript is case-sensitive. This means age
, Age
, and AGE
are different variables.
let user = "Alice";
let User = "Bob";
console.log(user); // Alice
console.log(User); // Bob
JavaScript follows camelCase for naming variables and functions. This means the first word is lowercase, and subsequent words start with uppercase letters.
let firstName = "John";
function getUserName() {
return "Alice";
}
Understanding JavaScript syntax is the first step in becoming a proficient JavaScript developer. Master these basics to write clean, efficient, and error-free code!