Skip to main content

๐Ÿ”‘ Chapter 3: Keywords and Identifiers in JavaScript

๐Ÿ“ Understanding Identifiersโ€‹

Identifiers are names that you create as a programmer to identify variables, functions, objects, classes, and other elements in your code. Think of them as labels that help you and JavaScript recognize different parts of your program.

๐ŸŽฏ What Makes a Valid Identifier?โ€‹

Identifiers must follow specific rules to be valid in JavaScript:

โœ… Valid Rulesโ€‹

  1. Must start with:

    • A letter (a-z, A-Z)
    • An underscore (_)
    • A dollar sign ($)
  2. After the first character, can contain:

    • Letters (a-z, A-Z)
    • Numbers (0-9)
    • Underscores (_)
    • Dollar signs ($)
  3. Case-sensitive

    • myVariable and MyVariable are different identifiers
  4. Cannot be a reserved word (keyword)

โŒ Invalid Examplesโ€‹

// โŒ Cannot start with a number
let 1variable = "invalid";

// โŒ Cannot contain spaces
let my variable = "invalid";

// โŒ Cannot contain special characters (except _ and $)
let my-variable = "invalid";
let my@variable = "invalid";

// โŒ Cannot be a reserved keyword
let let = "invalid";
let function = "invalid";

โœ… Valid Examplesโ€‹

// โœ… Valid identifiers
let myVariable = "valid";
let _privateVar = "valid";
let $element = "valid";
let user123 = "valid";
let camelCaseVariable = "valid";
let CONSTANT_VALUE = "valid";

// โœ… Valid function names
function calculateTotal() {}
function _helperFunction() {}
function $jQuery() {}

// โœ… Valid object properties
const person = {
firstName: "John",
lastName: "Doe",
age_in_years: 30
};

๐ŸŽจ Naming Conventionsโ€‹

While JavaScript allows many naming patterns, following conventions makes your code more readable and maintainable:

let firstName = "John";
let calculateTotalPrice = function() {};
let userAccountBalance = 1000;
class UserAccount {}
class BankingSystem {}
function PersonConstructor() {}
const MAX_RETRY_ATTEMPTS = 3;
const API_BASE_URL = "https://api.example.com";
const DEFAULT_TIMEOUT = 5000;

๐Ÿ snake_case (Less common in JavaScript)โ€‹

let user_name = "john_doe"; // Less preferred
let api_response = {}; // Less preferred

๐Ÿ”’ Understanding Keywordsโ€‹

Keywords are reserved words that have special meaning in JavaScript. They are part of the language syntax and cannot be used as identifiers.

๐Ÿ“‹ Complete List of JavaScript Keywordsโ€‹

CategoryKeywords
๐Ÿ”„ Control Flowif, else, switch, case, default, for, while, do, break, continue
๐Ÿ“ฆ Variablesvar, let, const
๐Ÿ”ง Functionsfunction, return, async, await, yield
๐Ÿ—๏ธ Objects & Classesclass, extends, super, static, new, this
๐Ÿ“ค๐Ÿ“ฅ Modulesimport, export
โš ๏ธ Error Handlingtry, catch, finally, throw
๐Ÿ” Operatorstypeof, instanceof, in, delete, void
๐Ÿ“„ Valuesnull, undefined, true, false
๐Ÿšซ Deprecatedwith, debugger
๐Ÿ†” SpecialSymbol

๐Ÿ“Š Keywords Reference Tableโ€‹

KeywordCategoryPurposeExample
asyncFunctionsDeclares async functionasync function fetchData() {}
awaitFunctionsWaits for promise resolutionconst data = await fetch(url);
breakControl FlowExits loop or switchfor(let i=0; i<10; i++) { if(i===5) break; }
caseControl FlowSwitch case labelswitch(x) { case 1: console.log('one'); }
catchError HandlingCatches exceptionstry {} catch(error) {}
classOOPDeclares a classclass Person {}
constVariablesDeclares constantconst PI = 3.14159;
continueControl FlowSkips iterationfor(let i=0; i<10; i++) { if(i%2) continue; }
debuggerDebugBreakpoint for debuggingdebugger; // Pauses execution
defaultControl FlowDefault case in switchswitch(x) { default: console.log('other'); }
deleteOperatorsDeletes object propertydelete obj.property;
doControl FlowDo-while loopdo { console.log('hello'); } while(false);
elseControl FlowAlternative conditionif(true) {} else {}
exportModulesExports from moduleexport const myVar = 42;
extendsOOPClass inheritanceclass Dog extends Animal {}
falseValuesBoolean false valueconst isReady = false;
finallyError HandlingAlways executestry {} catch {} finally {}
forControl FlowFor loopfor(let i=0; i<10; i++) {}
functionFunctionsDeclares functionfunction greet() {}
ifControl FlowConditional statementif(condition) {}
importModulesImports from moduleimport React from 'react';
inOperatorsProperty existence check'name' in person
instanceofOperatorsInstance type checkobj instanceof Array
letVariablesBlock-scoped variablelet count = 0;
newOperatorsCreates instanceconst date = new Date();
nullValuesNull valueconst data = null;
returnFunctionsReturns valuefunction add(a,b) { return a + b; }
staticOOPStatic class memberclass Utils { static helper() {} }
superOOPParent class referencesuper.methodName();
switchControl FlowMulti-way branchswitch(value) { case 1: break; }
thisContextCurrent object referencethis.property
throwError HandlingThrows exceptionthrow new Error('message');
trueValuesBoolean true valueconst isValid = true;
tryError HandlingTries code blocktry { riskyCode(); }
typeofOperatorsType checkingtypeof variable === 'string'
undefinedValuesUndefined valuelet x; // x is undefined
varVariablesFunction-scoped variablevar name = 'John';
voidOperatorsReturns undefinedvoid 0
whileControl FlowWhile loopwhile(condition) {}
withDeprecatedExtends scope chainwith(obj) {} // Not recommended
yieldFunctionsGenerator yieldfunction* gen() { yield 1; }

๐ŸŽฏ Practical Examplesโ€‹

๐Ÿ”„ Control Flow Keywordsโ€‹

// if, else, switch, case, default
function checkGrade(score) {
if (score >= 90) {
return 'A';
} else if (score >= 80) {
return 'B';
} else {
switch (true) {
case score >= 70:
return 'C';
case score >= 60:
return 'D';
default:
return 'F';
}
}
}

// for, while, do, break, continue
function processNumbers() {
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) continue; // Skip even numbers
if (i > 7) break; // Stop when i > 7
console.log(i); // Prints: 1, 3, 5, 7
}
}

๐Ÿ“ฆ Variable Declaration Keywordsโ€‹

// var, let, const
var globalVar = "I'm function-scoped"; // Function-scoped
let blockVar = "I'm block-scoped"; // Block-scoped
const constantVar = "I can't be reassigned"; // Block-scoped, immutable

function demonstrateScope() {
if (true) {
var funcScoped = "accessible outside this block";
let blockScoped = "only accessible in this block";
const alsoBlockScoped = "also only in this block";
}

console.log(funcScoped); // โœ… Works
// console.log(blockScoped); // โŒ Error
// console.log(alsoBlockScoped); // โŒ Error
}

๐Ÿ—๏ธ Object-Oriented Keywordsโ€‹

// class, extends, super, static, new, this
class Animal {
constructor(name) {
this.name = name;
}

static getSpecies() {
return "Unknown species";
}

speak() {
console.log(`${this.name} makes a sound`);
}
}

class Dog extends Animal {
constructor(name, breed) {
super(name); // Call parent constructor
this.breed = breed;
}

speak() {
console.log(`${this.name} barks`);
}
}

const myDog = new Dog("Buddy", "Golden Retriever");
myDog.speak(); // "Buddy barks"

โšก Async Keywordsโ€‹

// async, await
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
const userData = await response.json();
return userData;
} catch (error) {
throw new Error(`Failed to fetch user: ${error.message}`);
}
}

// Using the async function
fetchUserData(123)
.then(user => console.log(user))
.catch(error => console.error(error));

โš ๏ธ Common Mistakes and Best Practicesโ€‹

๐Ÿšซ Don't Use Keywords as Identifiersโ€‹

// โŒ BAD - Using keywords
let class = "Math"; // SyntaxError
let function = "helper"; // SyntaxError
let var = "variable"; // SyntaxError

// โœ… GOOD - Valid alternatives
let className = "Math";
let functionName = "helper";
let variableName = "variable";

๐ŸŽฏ Choose Meaningful Namesโ€‹

// โŒ BAD - Unclear names
let x = "John";
let fn = function() {};
let d = new Date();

// โœ… GOOD - Descriptive names
let userName = "John";
let calculateTotal = function() {};
let currentDate = new Date();

๐Ÿ“ Use Consistent Naming Conventionsโ€‹

// โŒ BAD - Inconsistent
let user_name = "John";
let UserAge = 30;
let USERTYPE = "admin";

// โœ… GOOD - Consistent camelCase
let userName = "John";
let userAge = 30;
let userType = "admin";

๐Ÿงช Practice Exercisesโ€‹

Exercise 1: Identify Valid Identifiersโ€‹

Which of these are valid JavaScript identifiers?

// Your task: Mark each as โœ… valid or โŒ invalid
let _underscore; // ?
let $dollar; // ?
let 123number; // ?
let my-variable; // ?
let firstName; // ?
let class; // ?
let MyClass; // ?
let CONSTANT_VALUE; // ?

Exercise 2: Fix the Keywordsโ€‹

Fix the code by replacing invalid keyword usage:

// Fix this code
let function = "helper";
let class = "Person";
let var = 42;

function let() {
return "this won't work";
}

Exercise 3: Apply Naming Conventionsโ€‹

Rename these variables to follow JavaScript conventions:

// Apply proper naming conventions
let user_first_name = "John";
let USERAGE = 30;
let user-type = "admin";
let IsActive = true;

๐Ÿ”‘ Key Takeawaysโ€‹

  1. ๐Ÿ“ Identifiers are names you create; ๐Ÿ”’ Keywords are reserved by JavaScript
  2. ๐ŸŽฏ Naming conventions make code more readable and maintainable
  3. โš ๏ธ Avoid using keywords as identifiers to prevent syntax errors
  4. ๐ŸŽจ Choose descriptive names that clearly indicate purpose
  5. ๐Ÿ“ Be consistent with your naming patterns throughout your codebase

๐ŸŽ“ Next Chapter: Now that you understand how to name things in JavaScript, let's explore different types of identifiers and data types to understand what kinds of values these names can represent!