Syntax Rules
Overview
JavaScript has a specific set of rules (syntax) for how programs are constructed. Just like English has grammar rules, JS has syntax rules.
Understanding casing, whitespace, and statement termination is crucial for writing bug-free code.
Syntax
Always use camelCase for variable and function names. Start with a lowercase letter, and capitalize the first letter of subsequent words.
// JS is completely case-sensitive!
let score = 10;
let Score = 20;
console.log(score); // 10
console.log(Score); // 20
// Best Practice: camelCase for variables
let firstName = "Kartik";
let totalUserCount = 50;Semicolons separate JavaScript statements. While JS automatically inserts them if you forget (ASI), it's highly recommended to always include them to avoid weird edge-case bugs.
let a = 5;
let b = 10;
// JS has Automatic Semicolon Insertion (ASI), so this works:
let c = 15
let d = 20Common Pitfalls
- Naming variables with spaces or starting with a number (e.g.,
let 1stName = 'John'). This will throw a SyntaxError. - Relying on Automatic Semicolon Insertion (ASI) and writing a
returnstatement with the value on the next line. ASI will insert a semicolon right afterreturn, returningundefined!
Interview Questions
Yes, JavaScript is strictly case-sensitive. The variables myVar, MyVar, and myvar are completely distinct from one another.
Variable names can contain letters, digits, underscores (_), and dollar signs ($). However, they cannot begin with a digit.
Real-World Example
When using React or modern JS frameworks, you will heavily rely on camelCase and PascalCase (where the first letter is also capitalized). Components use PascalCase, while functions use camelCase.
// Component (PascalCase)
function UserProfile() {
// Function (camelCase)
const calculateAge = () => {};
}Check Your Knowledge
Test your understanding of Syntax Rules with these quick questions.