-
-
Notifications
You must be signed in to change notification settings - Fork 2
JavaScript Syntax Elements
- Introduction
- Keywords
- Identifiers
- Operators
- Punctuation and Delimiters
- Understanding JavaScript Syntax
- Complete Examples
- Practice Exercises
Understanding JavaScript syntax elements is crucial for reading and writing code. In this guide, we'll break down every part of JavaScript code and explain what each piece does. By the end, you'll understand exactly what makes up any JavaScript code.
Keywords are reserved words that have special meaning in JavaScript. You cannot use them as variable names or identifiers.
// Variable declaration keywords
let age = 25; // let - declares block-scoped variable
const name = "Alice"; // const - declares constant
// Control flow keywords
if (age >= 18) { // if - conditional execution
console.log("Adult");
} else { // else - alternative condition
console.log("Minor");
}
// Loops
for (let i = 0; i < 5; i++) { // for - repeating code
console.log(i);
}
while (age < 18) { // while - loop while true
age++;
}
// Function keywords
function greet(name) { // function - creates function
return "Hello, " + name;
}
function* numbers() { // function* - generator function
yield 1;
yield 2;
yield 3;
}
// Return and break
function findItem(items, target) {
for (let i = 0; i < items.length; i++) {
if (items[i] === target) {
return i; // return - exit function with value
}
}
return -1;
}
function processArray(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] < 0) {
break; // break - exit loop
}
console.log(arr[i]);
}
}
// Switch statement
switch (grade) {
case 'A': // case - branch in switch
console.log("Excellent");
break;
case 'B':
console.log("Good");
break;
default: // default - fallback case
console.log("Try again");
}
// Try-catch-error handling
try {
// Try block - code to attempt
let result = riskyOperation();
} catch (error) { // catch - handle errors
console.error(error.message);
} finally { // finally - always runs
console.log("Done");
}
// Class keywords
class Person { // class - defines blueprint
constructor(name) { // constructor - initializes object
this.name = name;
}
speak() { // this - refers to current object
console.log("Hello");
}
}
// Import/export keywords
import { name } from './module.js'; // import - bring in code
export default function() { }; // export - make code available
// Other important keywords
typeof 25; // typeof - check type
delete obj.property; // delete - remove property
in 'name' in obj; // in - check property exists
new Date(); // new - create object instance
void doSomething(); // void - evaluates expression// Keywords you CANNOT use as variable names:
// break, case, catch, continue, debugger, default, delete,
// do, else, enum, export, extends, false, finally, for,
// function, if, import, in, instanceof, new, null, return,
// super, switch, this, throw, true, try, typeof, var, void,
// while, with, yield, class, const, let, static, yieldIdentifiers are names you create to identify variables, functions, classes, and other user-defined elements.
// ✓ Valid identifiers
let x; // Single letter
let counter; // CamelCase (recommended for variables)
let playerScore; // Descriptive
let _private; // Starting with underscore
let $element; // Starting with dollar sign
let firstName2; // Can include numbers (but not start with)
let FIRST_NAME; // Uppercase (constants)
let myFunction; // Functions
let MyClass; // Classes (PascalCase)
// ✗ Invalid identifiers
// let 2fast; // Can't start with number
// let my-variable; // Can't use hyphens
// let my variable; // Can't have spaces
// let for; // Can't use keywords
// let class; // Can't use reserved words// Variables - camelCase
let firstName = "John";
let lastName = "Doe";
let userAge = 25;
let isActive = true;
let userPreferences = { theme: "dark" };
// Constants - UPPER_CASE with underscores
const MAX_SIZE = 100;
const API_BASE_URL = "https://api.example.com";
const DAYS_IN_WEEK = 7;
// Functions - camelCase with verb
function calculateTotal() { }
function findUserById() { }
function validateEmail() { }
function getUserData() { }
function doSomething() { }
// Classes - PascalCase
class User { }
class BankAccount { }
class ShoppingCart { }
class Animal { }
// Private variables (convention - start with underscore)
let _privateVariable = "hidden";
function _internalFunction() { }
// Prototypes and constants
Array.prototype.myMethod = function() { };
Math.PI;Operators are symbols that perform operations on values (operands).
// Basic assignment
let x = 5; // = assigns value
console.log(x); // 5
// Compound assignment
let a = 10;
a += 5; // a = a + 5 → 15
a -= 3; // a = a - 3 → 12
a *= 2; // a = a * 2 → 24
a /= 4; // a = a / 4 → 6
a %= 4; // a = a % 4 → 2
a **= 3; // a = a ** 3 → 8// Basic math
let sum = 10 + 5; // 15 - addition
let diff = 10 - 5; // 5 - subtraction
let product = 10 * 5; // 50 - multiplication
let quotient = 10 / 5; // 2 - division
let remainder = 10 % 3; // 1 - modulo (remainder)
let power = 2 ** 3; // 8 - exponentiation
// Increment/decrement
let counter = 5;
counter++; // Post-increment → returns 5, then makes counter = 6
++counter; // Pre-increment → makes counter = 7, returns 7
counter--; // Post-decrement
--counter; // Pre-decrement// Equality
5 == 5; // true - loose equality (type coercion)
5 == "5"; // true - "5" becomes number 5
5 === 5; // true - strict equality (no conversion)
5 === "5"; // false - different types
// Inequality
5 != 3; // true - loose inequality
5 !== "5"; // true - strict inequality
// Relational
5 > 3; // true - greater than
5 < 3; // false - less than
5 >= 5; // true - greater than or equal
5 <= 4; // false - less than or equal
// String comparison
"apple" < "banana"; // true - alphabetical
"Apple" < "apple"; // true - uppercase < lowercase// AND - both must be true
true && true; // true
true && false; // false
// OR - at least one must be true
true || false; // true
false || false; // false
// NOT - inverts value
!true; // false
!false; // true
// Short-circuit evaluation
let name = null;
let displayName = name || "Guest"; // "Guest" - uses fallback
// Nullish coalescing (ES2020)
let value = null ?? "default"; // "default"
let zero = 0 ?? "default"; // 0 (not null/undefined)// condition ? valueIfTrue : valueIfFalse
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"
let score = 85;
let grade = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" : "F";
console.log(grade); // "B"// Spread - expands
let arr = [1, 2, 3];
let newArr = [...arr, 4, 5]; // [1, 2, 3, 4, 5]
let obj = { a: 1, b: 2 };
let newObj = { ...obj, c: 3 }; // { a: 1, b: 2, c: 3 }
// Rest - collects
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15// Optional chaining (?.)
let user = { profile: { name: "Alice" } };
let city = user?.profile?.city; // undefined (doesn't exist)
let name = user?.profile?.name; // "Alice"
// Nullish coalescing (??)
let a = null ?? "default"; // "default"
let b = 0 ?? "default"; // 0
let c = "" ?? "default"; // "" (empty string is not null/undefined)Punctuation (also called delimiters) are symbols that structure and organize code but don't perform operations.
// Function calls
console.log("Hello");
myFunction(arg1, arg2);
// Function declarations
function greet(name) {
return "Hello, " + name;
}
// Grouping expressions
let result = (a + b) * c;
// Conditionals
if (age > 18) { }
// Loops
for (let i = 0; i < 10; i++) { }
while (condition) { }// Object literals
let person = {
name: "Alice",
age: 25,
greet: function() {
return "Hello";
}
};
// Code blocks
if (condition) {
// Multiple statements
let x = 1;
let y = 2;
}
// Class definitions
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
}
// Function bodies
function calculate() {
return 42;
}// Arrays
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "two", true, null];
// Accessing elements (0-indexed)
console.log(numbers[0]); // 1
console.log(numbers[4]); // 5
// Array destructuring
let [first, second, ...rest] = [1, 2, 3, 4, 5];
// Object property access
let key = "name";
console.log(person[key]); // Using variable as key
// Computed property names
let prop = "firstName";
let obj = {
[prop]: "Alice" // Creates property with variable name
};// Statement terminators (optional in most cases, but recommended)
let x = 5;
let y = 10;
let sum = x + y;
// In loops
for (let i = 0; i < 10; i++) {
console.log(i);
}// Variable declarations
let a = 1, b = 2, c = 3;
// Array elements
let arr = [1, 2, 3, 4, 5];
// Object properties
let obj = { a: 1, b: 2, c: 3 };
// Function parameters
function process(a, b, c, d) { }
// Chained operations
let result = (a += 1), (b *= 2), (c -= 3);// Object key-value pairs
let user = {
name: "Alice",
age: 25
};
// Ternary operator (alternative syntax)
let status = age >= 18 ? "adult" : "minor";
// Labeled statements
outerLoop: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) break outerLoop;
}
}
// Switch cases
switch (day) {
case 1:
console.log("Monday");
break;
}// Property access
let person = { name: "Alice", age: 25 };
console.log(person.name); // "Alice"
console.log(person.age); // 25
// Method calls
"hello".toUpperCase(); // "HELLO"
[1, 2, 3].push(4); // Adds 4 to array
// Chaining
let text = " Hello World ";
let result = text.trim().toLowerCase(); // "hello world"
// Static methods
Math.max(1, 2, 3); // 3
Date.now(); // Current timestamp
Array.isArray([]); // true// String creation
let single = 'Hello World';
let double = "Hello World";
let backtick = `Hello World`;
// Template literals with backticks
let name = "Alice";
let greeting = `Hello, ${name}!`; // "Hello, Alice!"
// Escaping quotes
let text1 = "She said \"Hello\"";
let text2 = 'She said "Hello"';// Basic template literal
let message = `Hello, World!`;
// Variable interpolation
let name = "Alice";
let age = 25;
let bio = `Name: ${name}, Age: ${age}`;
// Expression interpolation
let a = 5, b = 3;
let result = `${a} + ${b} = ${a + b}`; // "5 + 3 = 8"
// Multi-line strings
let poem = `Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.`;
// Tagged templates
function highlight(strings, ...values) {
return strings.reduce((result, string, i) => {
return result + string + (values[i] ? `<b>${values[i]}</b>` : '');
}, '');
}
let name = "Alice";
let output = highlight`Hello, ${name}!`; // "Hello, <b>Alice</b>!"Syntax is the set of rules that defines the structure of JavaScript code. It's the grammar of the language.
// 1. JavaScript is case-sensitive
let myVariable = 1;
let myvariable = 2;
console.log(myVariable !== myvariable); // true - different variables
// 2. Statements end with semicolons (usually)
let x = 5;
// 3. Code blocks use curly braces
if (x > 3) {
console.log("x is greater than 3");
}
// 4. Keywords can't be used as identifiers
// let if = 5; // ❌ Error!
// 5. Values have types
let string = "Hello"; // string type
let number = 42; // number type
let boolean = true; // boolean type
let nothing = null; // null type
let notDefined; // undefined type
// 6. Arrays are ordered, objects are key-value pairs
let array = [1, 2, 3];
let object = { a: 1, b: 2 };Let's break down complete JavaScript code examples:
// function greeting(name) {
// ↑ ↑ ↑ ↑
// | | | └ Opening parenthesis
// | | └ Comma (separator)
// | └ Identifier (function name)
// └ Keyword
// | | | └ Semicolon (statement end)
// | | └ Closing parenthesis
// | └ Identifier (parameter name)
// └ Colon in function declaration (none - just keyword and name)
// Actually - it's: function keyword, greeting identifier, ( parameters )
function greeting(name) {
return "Hello, " + name + "!";
// ↑ ↑ ↑
// | | └ Semicolon (not needed in function)
// | └ Identifier
// └ Keyword
}
let message = greeting("Alice");// class BankAccount {
// ↑ ↑ ↑
// | | └ Opening brace (class body)
// | └ Identifier (class name)
// └ Keyword
class BankAccount {
// constructor(name, balance) {
// ↑ ↑ ↑ ↑
// | | | └ Closing parenthesis
// | | └ Comma (separator)
// | └ Identifier (parameter name)
// └ Keyword
constructor(name, balance) {
// this.name = name;
// ↑ ↑ ↑ ↑
// | | | └ Identifier
// | | └ Assignment operator
// | └ Dot operator
// └ Keyword (refers to instance)
this.name = name;
this.balance = balance;
}
// deposit(amount) {
// ↑ ↑
// | └ Opening parenthesis
// └ Identifier (method name)
deposit(amount) {
// if (amount > 0) {
// ↑ ↑
// | └ Comparison operator
// └ Keyword
if (amount > 0) {
// this.balance = this.balance + amount;
// ↑ ↑ ↑ ↑ ↑ ↑
// | | | | | └ Number literal
// | | | | └ Addition operator
// | | | └ Dot operator
// | | └ Identifier
// | └ Assignment operator
// └ Keyword (refers to instance)
this.balance = this.balance + amount;
return true;
}
return false;
}
}let numbers = [1, 2, 3, 4, 5];
// let doubled = numbers.map(n => n * 2);
// ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑
// | | | | | | | └ Closing brace (arrow function body)
// | | | | | | └ Assignment operator
// | | | | | |
// | | | | | └ Closing parenthesis (map argument)
// | | | | | └ Arrow operator
// | | | | └ Number literal
// | | | └ Multiplication operator
// | | └ Identifier (array variable)
// | └ Dot operator
// └ Keyword (actually, it's 'let' variable declaration)
let doubled = numbers.map(function(n) {
return n * 2;
});
// Same as arrow function above
// numbers.filter(n => n > 3);
// ↑ ↑ ↑ ↑ ↑
// | | | | └ Closing parenthesis
// | | | └ Number literal
// | | └ Greater than operator
// | └ Identifier (parameter)
// └ Dot operatorLabel each part of this code:
for (let i = 0; i < 10; i++) {
console.log(i * 2);
}Answer:
-
for- keyword -
(- punctuation (parentheses) -
let- keyword -
i- identifier -
=- operator (assignment) -
0- literal (number) -
;- punctuation (semicolon) -
i- identifier -
<- operator (comparison) -
10- literal (number) -
;- punctuation -
i++- identifier + operator (increment) -
)- punctuation -
{- punctuation (curly brace) -
console.log- identifier (object.method) -
(- punctuation -
i- identifier -
*- operator (multiplication) -
2- literal -
)- punctuation -
;- punctuation -
}- punctuation
Write a function and identify all the elements:
function calculateArea(width, height) {
return width * height;
}
let rectangle = calculateArea(5, 3);
console.log("Area:", rectangle);| Element | Description | Examples |
|---|---|---|
| Keywords | Reserved words with special meaning |
let, const, function, if, for, class
|
| Identifiers | Names you create |
myVariable, calculateTotal, User
|
| Operators | Perform actions |
=, +, -, ===, &&, ++
|
| Punctuation | Structure code |
(), {}, [], ;, ,, :, .
|
| Literals | Fixed values |
42, "hello", true, [1,2]
|
| Syntax | Rules of the language | All of the above combined |
- Keywords are reserved words that JavaScript uses for its own purposes
- Identifiers are names you create for variables, functions, and classes
- Operators perform operations on values
- Punctuation (delimiters) organize and structure code
- Together, these form JavaScript syntax - the rules that make your code valid