JavaScript Syntax and Operators
JavaScript syntax is the set of rules that defines how JavaScript programs are constructed. Understanding syntax and operators is essential for writing effective JavaScript code. This tutorial covers everything you need to know to get started.
JavaScript Syntax Basics
JavaScript syntax refers to the rules and guidelines for writing JavaScript code. Here are the fundamental concepts:
1. JavaScript Values
JavaScript supports two types of values:
- Fixed values – called Literals (numbers, strings, etc.)
- Variable values – called Variables (let, const, var)
2. JavaScript Literals
Number Literals: Can be integers or decimals
let age = 25;
let price = 99.99;
let hexNumber = 0xFF; // Hexadecimal
String Literals: Text enclosed in quotes
let name = "John";
let message = 'Hello World';
let greeting = `Backtick strings`; // Template literals
Array Literals: Collection of values
let colors = ["Red", "Green", "Blue"];
let numbers = [1, 2, 3, 4, 5];
Object Literals: Key-value pairs
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
3. JavaScript Variables
Variables are containers for storing data values. JavaScript uses three keywords:
- let – For variables that can be reassigned
- const – For variables that cannot be reassigned (constant)
- var – Older way (avoid using in modern JavaScript)
let x = 10; // Can change later
const PI = 3.14; // Cannot change
var oldWay = "old"; // Avoid using
4. JavaScript Identifiers
Identifiers are names given to variables, functions, and objects. Rules:
- Must begin with a letter (a-z or A-Z), underscore (_), or dollar sign ($)
- Cannot begin with a number
- Are case-sensitive (myVar ≠myvar)
- Cannot use reserved keywords (like ‘if’, ‘for’, ‘while’)
// Valid identifiers
let username = "John";
let _private = "hidden";
let $money = 100;
// Invalid identifiers
// let 123name = "invalid";
// let my-name = "invalid";
5. JavaScript Comments
Comments are ignored by JavaScript engines and used to explain code.
// Single-line comment
/*
Multi-line comment
Spans multiple lines
*/
6. JavaScript Case Sensitivity
JavaScript is case-sensitive. These are different variables:
let myVariable = "first";
let MyVariable = "second";
let MYVARIABLE = "third";
JavaScript Operators
Operators are symbols that perform operations on operands (values and variables).
1. Arithmetic Operators
Used to perform mathematical operations:
| Operator | Description | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 2 | 7 |
| – | Subtraction | 5 – 2 | 3 |
| * | Multiplication | 5 * 2 | 10 |
| / | Division | 5 / 2 | 2.5 |
| % | Modulus (Remainder) | 5 % 2 | 1 |
| ** | Exponentiation | 5 ** 2 | 25 |
| ++ | Increment | let x=5; x++ | 6 |
| — | Decrement | let x=5; x– | 4 |
// Arithmetic examples
let a = 10, b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.333...
console.log(a % b); // 1 (remainder)
console.log(a ** b); // 1000 (10³)
// Increment/Decrement
let count = 5;
count++; // count becomes 6
count--; // count becomes 5
2. Assignment Operators
Used to assign values to variables:
| Operator | Description | Example | Equivalent To |
|---|---|---|---|
| = | Assignment | x = 5 | x = 5 |
| += | Addition assignment | x += 3 | x = x + 3 |
| -= | Subtraction assignment | x -= 3 | x = x – 3 |
| *= | Multiplication assignment | x *= 3 | x = x * 3 |
| /= | Division assignment | x /= 3 | x = x / 3 |
| %= | Modulus assignment | x %= 3 | x = x % 3 |
| **= | Exponentiation assignment | x **= 2 | x = x ** 2 |
// Assignment examples
let x = 10;
x += 5; // x = 15
x -= 3; // x = 12
x *= 2; // x = 24
x /= 4; // x = 6
x %= 4; // x = 2
x **= 3; // x = 8
3. Comparison Operators
Used to compare values and return true or false:
| Operator | Description | Example | Result |
|---|---|---|---|
| == | Equal to (value only) | 5 == “5” | true |
| === | Equal value and type | 5 === “5” | false |
| != | Not equal | 5 != “5” | false |
| !== | Not equal value or type | 5 !== “5” | true |
| > | Greater than | 5 > 3 | true |
| < | Less than | 5 < 3 | false |
| >= | Greater than or equal | 5 >= 5 | true |
| <= | Less than or equal | 5 <= 3 | false |
// Comparison examples
let age = 18;
console.log(age == 18); // true
console.log(age === "18"); // false (different types)
console.log(age != 20); // true
console.log(age !== "18"); // true
console.log(age > 16); // true
console.log(age < 21); // true
console.log(age >= 18); // true
console.log(age <= 17); // false
4. Logical Operators
Used to combine conditional statements:
| Operator | Description | Example | Result |
|---|---|---|---|
| && | Logical AND (both true) | (5 > 3 && 2 < 4) | true |
| || | Logical OR (one true) | (5 > 3 || 2 > 4) | true |
| ! | Logical NOT (reverse) | !(5 > 3) | false |
// Logical examples
let isAdult = true;
let hasLicense = false;
console.log(isAdult && hasLicense); // false (both need to be true)
console.log(isAdult || hasLicense); // true (at least one is true)
console.log(!isAdult); // false (reverses the value)
// Practical example
let age = 20;
let country = "USA";
if (age >= 18 && country === "USA") {
console.log("You can vote in USA");
}
5. String Operators
The + operator can also be used to concatenate (join) strings:
// String concatenation
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // "John Doe"
// Using += with strings
let greeting = "Hello";
greeting += " World";
console.log(greeting); // "Hello World"
// Template literals (modern way)
let name = "Alice";
let message = `Hello ${name}, welcome to JavaScript!`;
console.log(message); // "Hello Alice, welcome to JavaScript!"
6. Ternary Operator (Conditional Operator)
A shorthand for if-else statements: condition ? valueIfTrue : valueIfFalse
let age = 18;
let canVote = (age >= 18) ? "Yes" : "No";
console.log(canVote); // "Yes"
// Another example
let score = 85;
let grade = (score >= 90) ? "A" : (score >= 80) ? "B" : "C";
console.log(grade); // "B"
7. typeof Operator
Returns the data type of a variable:
console.log(typeof "Hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object"
console.log(typeof []); // "object"
console.log(typeof {}); // "object"
JavaScript Operator Precedence
Operator precedence determines the order in which operations are evaluated. Multiplication and division have higher precedence than addition and subtraction:
// Without parentheses
let result = 5 + 3 * 2;
console.log(result); // 11 (3*2=6, then 5+6=11)
// With parentheses
let result2 = (5 + 3) * 2;
console.log(result2); // 16 (5+3=8, then 8*2=16)
Precedence order (highest to lowest):
- () - Parentheses
- ** - Exponentiation
- * / % - Multiplication, Division, Modulus
- + - - Addition, Subtraction
- > < >= <= - Comparisons
- == === != !== - Equality
- && - Logical AND
- || - Logical OR
- ?: - Ternary
- = += -= etc. - Assignment
Practical Examples
Example 1: Simple Calculator
let num1 = 10;
let num2 = 5;
let sum = num1 + num2;
let difference = num1 - num2;
let product = num1 * num2;
let quotient = num1 / num2;
console.log(`Sum: ${sum}`); // 15
console.log(`Difference: ${difference}`); // 5
console.log(`Product: ${product}`); // 50
console.log(`Quotient: ${quotient}`); // 2
Example 2: Age Checker
let age = 16;
let hasParentalConsent = true;
// Check if person can register
let canRegister = (age >= 18) || (age >= 16 && hasParentalConsent);
console.log(canRegister); // true (16 with parental consent)
Example 3: Discount Calculator
let price = 100;
let isMember = true;
let discount = 0;
// Calculate discount
discount = isMember ? 0.2 : 0.1;
let finalPrice = price - (price * discount);
console.log(`Original: $${price}`);
console.log(`Discount: ${discount * 100}%`);
console.log(`Final Price: $${finalPrice}`);
Quick Reference Summary
Arithmetic Operators
+Addition-Subtraction*Multiplication/Division%Modulus (remainder)**Exponentiation++Increment--Decrement
Assignment Operators
=+=-=*=/=%=**=
Comparison Operators
=====!=!==><>=<=
Logical Operators
&&AND||OR!NOT
Pro Tip: Always use === and !== instead of == and != to avoid unexpected type coercion issues in JavaScript!
Next Steps
- Practice writing expressions with different operators
- Learn about JavaScript control flow (if-else, switches)
- Master JavaScript functions and scope
- Explore arrays and objects in depth