JavaScript Syntax and Keywords: Complete Guide #
First, let's look into JavaScript syntax and keywords.
Before that, JavaScript is a programming language that conforms to the ECMAScript specification. It is high-level, often just-in-time compiled, and multi-paradigm. Let's break down the topics:
- Basic Syntax
- Keywords (reserved words)
- Examples
We'll also note that JavaScript is case-sensitive and uses Unicode.
Let's start. #
1. Basic Syntax #
Case Sensitivity: All variables, function names, and operators are case-sensitive. For example,
myVariableandmyvariableare different.Statements: Each statement should end with a semicolon (
;), though JavaScript has Automatic Semicolon Insertion (ASI). It's good practice to include them to avoid errors.Comments:
javascript.js// This is a single-line comment/*This is a multi-line comment.It can span multiple lines.*/Blocks: Curly braces
{}define blocks of code, used in functions, conditionals, loops, and object literals.Whitespace: Spaces, tabs, and newlines are ignored except within strings and regular expressions. Proper indentation improves readability.
2. Variables #
Declaration:
var: Function-scoped, hoisted (declaration moved to top of function). Avoid in modern JavaScript.let: Block-scoped, can be reassigned.const: Block-scoped, cannot be reassigned after initialization. Must be initialized at declaration.
javascript.jsvar a = 1; // Avoid in modern JSlet b = 2; // Can be changed laterconst c = 3; // Cannot be reassigned{let d = 4;const e = 5;}// console.log(d); // ReferenceError: d is not definedHoisting:
vardeclarations are hoisted (initialized asundefined).letandconstare hoisted but not initialized (Temporal Dead Zone).
3. Data Types #
JavaScript is dynamically typed. Types are associated with values, not variables.
Primitive Types:
String: Textual data. Can use single quotes, double quotes, or backticks (template literals).Number: Both integer and floating-point. IncludesInfinity,-Infinity,NaN.Boolean:trueorfalse.null: Intentional absence of any object value.undefined: Variable has been declared but not assigned.BigInt: For integers larger than 2^53 - 1. Appendn.Symbol: Unique and immutable primitive, often used as object property keys.
Non-Primitive Types:
Object,Array,Function,Date,RegExp,Error, etc.
Type Checking:
javascript.jstypeof "Hello" // "string"typeof 42 // "number"typeof true // "boolean"typeof undefined // "undefined"typeof null // "object" (historical quirk)typeof Symbol() // "symbol"typeof BigInt(1) // "bigint"typeof [] // "object"typeof function() {} // "function"
4. Operators #
Arithmetic:
+,-,*,/,%,**,++,--Assignment:
=,+=,-=,*=,/=,%=,**=Comparison:
==,===,!=,!==,>,<,>=,<=Logical:
&&,||,!Bitwise:
&,|,^,~,<<,>>,>>>Ternary:
condition ? expr1 : expr2Optional Chaining (ES2020):
javascript.jsobj?.proparr?.[0]func?.()Nullish Coalescing (ES2020):
javascript.jsconst value = input ?? 'default';
5. Control Flow #
Conditionals:
javascript.jsif (condition) {// code} else if (otherCondition) {// code} else {// code}switch (value) {case 1:// codebreak;default:// code}Loops:
javascript.jsfor (let i = 0; i < 5; i++) { console.log(i); }while (condition) { /* code */ }do { /* code */ } while (condition);for (const value of array) { /* code */ }for (const key in object) {if (object.hasOwnProperty(key)) {// code}}Loop Control:
break,continue
6. Functions #
Functions are fundamental building blocks of code designed to perform specific tasks or calculate values. They allow for code reusability, organization, and modularity within a program.
Key aspects of JavaScript functions: #
-Definition: Functions are typically defined using the function keyword, followed by a name, parentheses (which can contain parameters), and curly braces {} enclosing the function's body (the code to be executed).
function greet(name) { console.log("Hello, " + name + "!"); }
Execution (Calling/Invoking): #
- A function's code runs only when it is explicitly called or invoked. This is done by writing the function's name followed by parentheses, potentially including arguments if parameters are defined.
greet("Alice"); // Calls the greet function, passing "Alice" as the argument
Parameters and Arguments:
- Parameters are variables listed within the parentheses in the function definition, acting as placeholders for values. Arguments are the actual values passed to these parameters when the function is called.
Return Values:
- Functions can return a value using the return keyword. This value can be captured and used by the calling code. If no return statement is used, or an empty return is used, the function implicitly returns undefined.
function add(a, b) { return a + b; } let sum = add(5, 3); // sum will be 8
Types of Functions: #
Function Declarations: The most common way to define functions, as shown above. Function Expressions: Functions assigned to variables. They can be named or anonymous.
- Declaration:
function greet(name) { return `Hello, ${name}`; }
- Expression:
const greet = function(name) { return `Hello, ${name}`; };
Arrow Function:
A concise syntax for writing function expressions, particularly useful for shorter functions and callbacks. They have different this binding behavior compared to regular functions.
javascript.jsconst greet = name => `Hello, ${name}`;const square = x => x * x;const noArgs = () => console.log('Hi');const sumArray = arr => {let sum = 0;for (const n of arr) {sum += n;}return sum;};
Default + Rest Params:
javascript.jsfunction greet(name = 'Guest') { return `Hi ${name}`; }function sum(...args) { return args.reduce((a,b) => a+b, 0); }IIFE:
javascript.js(function() { console.log('Runs immediately'); })();
7. Objects & Arrays #
Objects:
javascript.jsconst person = {name: 'Alice',greet() { console.log(`Hi, I'm ${this.name}`); },['dynamic' + 'Key']: 'value'};Arrays:
javascript.jsconst fruits = ['apple', 'banana'];fruits.push('cherry');fruits.pop();Destructuring:
javascript.jsconst [first, second] = fruits;const { name, greet } = person;
8. Reserved Keywords #
JavaScript keywords are reserved words that have special meaning and functionality within the language. These words cannot be used as identifiers (like variable names, function names, or property names) because they are already designated for specific purposes by the JavaScript engine.
Here are some common categories of JavaScript keywords: #
Variable Declaration: #
var: Declares a variable with function-scope or global-scope.let: Declares a block-scoped local variable, optionally initializing it to a value.const: Declares a block-scoped, read-only named constant.
Control Flow: #
if, else, else if: Used for conditional execution of code blocks.switch, case, default: Used for multi-way conditional branching.for, while, do: Used for creating loops.break: Terminates a loop or switch statement.continue: Skips the current iteration of a loop and proceeds to the next.return: Specifies the value to be returned by a function.try, catch, finally, throw: Used for error handling.
Functions and Classes: #
function: Declares a function.class: Declares a class.extends: Used for class inheritance.super: Used to call the parent class's constructor or methods.this: Refers to the current object context.new: Creates an instance of an object.async, await: Used for asynchronous operations with Promises.
Operators: #
typeof: Returns a string indicating the type of the unevaluated operand.instanceof: Tests if an object is an instance of a particular class or constructor function.delete: Deletes a property from an object.void: Evaluates an expression and returns undefined. Other:import, export: Used for module management.debugger: Invokes any available debugging functionality.null: Represents the intentional absence of any object value.true, false: Boolean literal values.All keywords:
break, case, catch, class, const, continue, debugger, default, delete, do,else, 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, let, await, static, enum,implements, interface, package, private, protected, public, arguments, eval
9. Modern Features (ES6+) #
Template Literals #
JavaScript template literals, introduced in ECMAScript 2015 (ES6), are a powerful and flexible way to create strings. They offer several advantages over traditional single or double-quoted strings:
- Multiline Strings: Template literals allow you to create strings that span multiple lines without needing to use escape characters like \n. You simply add new lines within the backticks.
const multiLineString = `This is a string that spans multiple lines.`;
- String Interpolation: You can embed expressions directly within a template literal using the ${expression} syntax. The expression is evaluated, and its result is inserted into the string. This makes dynamic string creation much cleaner and more readable than concatenation with the + operator.
const name = "Alice"; const age = 30; const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
- Tagged Templates: This is an advanced feature where a function can be "tagged" before a template literal. The tag function receives the string parts and the embedded expressions as arguments, allowing for custom processing and manipulation of the template literal's content.
function highlight(strings, ...values) { let str = ''; strings.forEach((s, i) => { str += s; if (values[i]) { str += `<mark>${values[i]}</mark>`; } }); return str; } const item = 'JavaScript'; const price = 99; const message = highlight`The ${item} book costs ${price} dollars.`; // Result: "The <mark>JavaScript</mark> book costs <mark>99</mark> dollars."
Template literals are enclosed in backticks (`) instead of single or double quotes. They significantly enhance code readability and maintainability when dealing with complex or dynamic string constructions.
Destructuring: #
In JavaScript, destructuring is a convenient way to extract values from arrays or properties from objects and assign them to distinct variables. It allows for more concise and readable code when working with data structures.
Key Concepts of Destructuring:
Unpacking: Destructuring unpacks values from an array or properties from an object into individual variables.
Assignment: The left-hand side of a destructuring assignment specifies the variables you want to create and what they should be assigned to, based on the structure of the array or object on the right-hand side.
Arrays: Array destructuring uses square brackets [] on the left-hand side to assign array elements to variables based on their position (index).
Objects: Object destructuring uses curly braces {} on the left-hand side to assign object properties to variables based on their property names.
Examples of Destructuring: #
- Array Destructuring:
Basic Assignment:
const numbers = [1, 2, 3];const [a, b, c] = numbers;console.log(a); // Output: 1console.log(b); // Output: 2console.log(c); // Output: 3
- Skipping Elements:
const colors = ['red', 'green', 'blue'];const [firstColor, , thirdColor] = colors;console.log(firstColor); // Output: redconsole.log(thirdColor); // Output: blueUse code with caution.
- Rest Parameter: Using the rest operator
...to gather remaining elements into a new array.
const numbers = [10, 20, 30, 40, 50];const [first, second, ...rest] = numbers;console.log(first); // Output: 10console.log(second); // Output: 20console.log(rest); // Output: [30, 40, 50]Use code with caution.
- Object Destructuring:
Basic Assignment:
const person = { name: 'Sara', age: 25 };const { name, age } = person;console.log(name); // Output: Saraconsole.log(age); // Output: 25
- Renaming Variables: Assigning a property value to a variable with a different name.
const person = { name: "Alice", age: 25 };const { name: fullName } = person;console.log(fullName); // Output: AliceUse code with caution.
- Default Values: Providing a default value if a property is not present or has a value of undefined.
const person = { name: 'Jack' };const { name, age = 26 } = person;console.log(name); // Output: Jackconsole.log(age); // Output: 26Use code with caution.
Note: Default values are not used if the property has a value like null, false, or 0.
- Nested Object Destructuring: Extracting values from nested objects.
const user = { id: 1, profile: { username: "johnDoe", email: "john@example.com" }};const { profile: { username, email } } = user;console.log(username); // Output: johnDoeconsole.log(email); // Output: john@example.com
- Rest/Spread Properties: Using the rest operator (...) to collect remaining properties into a new object.
const user = { name: 'Alex', address: '15th Park Avenue', age: 43 };const { age, ...restDetails } = user; console.log(age); // Output: 43console.log(restDetails); // Output: { name: 'Alex', address: '15th Park Avenue' } const newArr = [...fruits, 'date'];const newObj = { ...person, age: 40 };function logAll(...args) { console.log(args); }
- Destructuring in Function Parameters: Destructuring can be used directly within function parameters to extract values from arguments.
function greet({ name, age }) { console.log(`Hello, ${name}. You are ${age} years old.`);}greet({ name: "Peter", age: 50 }); // Output: Hello, Peter. You are 50 years old.
Why Use Destructuring? #
Readability and Conciseness: Destructuring reduces boilerplate code and makes it easier to understand how data is being extracted and used. Parameter Handling: It simplifies working with function parameters, especially when dealing with objects or arrays.
Default Values: Destructuring makes it easy to assign default values to variables when the corresponding property or element is missing or undefined.
Handling Nested Data: It provides a clear syntax for extracting values from nested objects and arrays.
In summary, JavaScript destructuring is a powerful syntax feature that enhances code readability and efficiency by providing a clean way to extract values from data structures.
Modules: #
JavaScript modules are a fundamental feature for structuring and organizing code in modern JavaScript development. They allow developers to break down large applications into smaller, independent, and reusable units of code, making projects more manageable, maintainable, and scalable.
Key aspects of JavaScript modules: #
Encapsulation and Reusability: Modules encapsulate latreed code (variables, functions, classes) within a single file. This promotes code organization and prevents naming collisions in the global scope. The encapsulated code can then be easily reused across different parts of an application or even in other projects.
export Keyword: The export keyword is used within a module to make specific variables, functions, or classes accessible from outside that module.
There are two main types of exports: #
Named Exports: Exporting multiple items individually, which must be imported by their specific names.
Default Exports: Exporting a single, primary item from a module, which can be imported with any name. A module can only have one default export.
import Keyword: #
The import keyword is used in another file to bring in the exported functionalities from a module.
Importing Named Exports: Requires destructuring the imported items using curly braces (e.g., import { name, age } from './person.js';).
Importing Default Exports: Does not require curly braces and can be assigned any local name (e.g., import message from './message.js';).
Module Specifiers: When importing, you provide a module specifier, which is a string indicating the path to the module file. This can be a relative path (e.g., ./utils.js) or a bare specifier for built-in modules or those installed via package managers.
Strict Mode by Default: Modules automatically operate in strict mode, which helps catch common coding errors and enforces stricter parsing and error handling.
javascript.jsexport const pi = 3.14;export default function() {}import { pi } from './math.js';import myDefault from './default.js';
Classes: #
JavaScript classes, introduced in ECMAScript 2015 (ES6), provide a more structured and familiar syntax for creating objects and implementing object-oriented programming (OOP) principles. While JavaScript inherently uses a prototype-based inheritance model, classes serve as "syntactic sugar" over this underlying mechanism, making it easier for developers accustomed to class-based languages like Java or C++ to write OOP code in JavaScript.
Key Aspects of JavaScript Classes #
classkeyword Used to declare a class, defining a blueprint for creating objects.constructor()method A special method automatically called when a new instance of the class is created using thenewkeyword. It's used to initialize object properties.Methods: Functions defined within the class that encapsulate behavior related to the objects created from that class.
thiskeyword Refers to the current instance of the class within its methods and constructor, allowing access to its properties and other methods.Inheritance: Achieved using the
extendskeyword, allowing a derived class to inherit properties and methods from a base class.super()Used within a derived class's constructor to call the constructor of its parent class, ensuring proper initialization of inherited properties.Getters and Setters: Special methods (
getandset) that allow you to define custom logic for retrieving and setting property values, respectively.Static members Methods or properties declared with the
statickeyword, which belong to the class itself rather than to individual instances. They are accessed directly on the class name.Private elements Introduced more recently, allowing for truly private class fields and methods using a
#prefix, ensuring they cannot be accessed from outside the class.
Example #
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); }} const person1 = new Person("Alice", 30);person1.greet(); // Output: Hello, my name is Alice and I am 30 years old. ```javascript class Person { #privateField; constructor(name) { this.name = name; } greet() { console.log(`Hi ${this.name}`); } static species = 'Homo sapiens'; }
Promises and Async/Await #
In JavaScript, Promises and async/await are tools for handling asynchronous operations, which are tasks that don't immediately return a result and might take some time to complete (e.g., fetching data from an API or reading a file).
Promises #
A Promise represents the eventual result of an asynchronous operation.
It acts as a placeholder for a value that might not be available yet.
States of a Promise
- Pending: The operation hasn't finished yet.
- Fulfilled (or Resolved): The operation completed successfully.
- Rejected: The operation failed.
.then() Used to handle a fulfilled promise.
.catch() Used to handle a rejected promise (errors).
Chaining Promises can be chained using
.then()to handle a sequence of asynchronous operations where each step depends on the previous one.
Async/Await #
A
async/awaitis a modern JavaScript feature (introduced in ES2017) that simplifies working with promises, making asynchronous code look and behave more like synchronous code.The async keyword is used to declare an asynchronous function. An
asyncfunction always returns a Promise.The
awaitkeyword can only be used inside an async function. await pauses the execution of the async function until the promise it's waiting on settles (either fulfills or rejects).When the promise fulfills, await returns its fulfillment value; if it rejects, await throws the rejected value. Error handling is done using try...catch blocks, similar to synchronous code.
Example #
fetchData() .then(data => { // Process the data when the promise is fulfilled console.log(data); }) .catch(error => { // Handle errors when the promise is rejected console.error(error); }); ## 10. Error Handling ```javascripttry { throw new Error('Oops');} catch (e) { console.error(e.message);} finally { console.log('Cleanup');}
11. Strict Mode #
"use strict";
- Prevents accidental globals
- Disallows duplicates
- Safer eval
Key Practices #
- Prefer
constandletovervar - Use
===not== - Arrow functions for non-methods
- Template literals for strings
- Modular code (ES6 modules)
Advanced Features Timeline #
- ES2022: Top-level await, class static blocks, Array.at()
- ES2023: findLast, findLastIndex, hashbang
- Stage 4: Record & Tuple, decorators


Loading discussion...