JavaScript Syntax

JavaScript – Syntax, Variables, Data Types & Examples

Understand the JavaScript Syntax.

JavaScript Syntax

JavaScript syntax defines the formal rules and structure used to write valid JavaScript code. It shares many similarities with popular programming languages such as C and Java, making it easier for developers with prior programming experience to learn. JavaScript is a case-sensitive language, typically uses semicolons to terminate statements, and relies on curly braces { } to group and define blocks of executable code.

Example: Hello World in JavaScript

JavaScript Example

console.log("Welcome to JavaScript Learning!");
                    
Try it Yourself »

JavaScript Values

In JavaScript, values represent the actual data that a program processes and manipulates. Every JavaScript expression evaluates to a value, whether it is a number, text, or a more complex data structure. A solid understanding of JavaScript values is essential for writing readable, maintainable, and reliable code.

JavaScript values are generally divided into two main categories:

  • Fixed Values (Literals) – Values written directly into the source code.
  • Variable Values (Variables) – Values stored in variables that can change while the program is running.

JavaScript Literals

Literals are fixed values that are written directly into JavaScript code. They represent constant data and do not change unless the code itself is modified. JavaScript supports several types of literals, such as numeric, string, boolean, and object literals.

Example: Numeric Literals in JavaScript

JavaScript Example

let userAge = 25;
let productPrice = 99.99;
let temperatureCelsius = -5;

console.log(userAge);
console.log(productPrice);
console.log(temperatureCelsius);
    
Try it Yourself »

Example: String Literals in JavaScript

JavaScript Example

let companyName = "TechWorld Solutions";
let courseTitle = 'JavaScript for Beginners';
let websiteStatus = "Online and Available";

console.log(companyName);
console.log(courseTitle);
console.log(websiteStatus);
Try it Yourself »

JavaScript Variables

In JavaScript, a variable is a named container used to store data values. Variables allow programs to save information, reuse it, and update it dynamically as the code executes. They can store numbers, strings, objects, arrays, and even functions.

JavaScript provides three keywords for declaring variables: var, let, and const. Each keyword defines how the variable behaves in terms of scope and reassignment:

  • var: The original way to declare variables. It is function-scoped and generally avoided in modern JavaScript.
  • let: Block-scoped and recommended for variables whose values may change.
  • const: Block-scoped and cannot be reassigned. Ideal for values that should remain constant.

Based on where they are declared, JavaScript variables are commonly categorized as:

  • Local Variables – Declared inside a function or block and accessible only within that specific scope.
  • Global Variables – Declared outside all functions or blocks and accessible throughout the entire program.

Example: Local vs Global Variables in JavaScript

JavaScript Example

let programmingLanguage = "JavaScript"; // Global variable

function displayProfile() {
    let yearsOfExperience = 5; // Local variable
    console.log(programmingLanguage); // Accessible inside the function
    console.log(yearsOfExperience);    // Accessible inside the function
}

displayProfile();

// console.log(yearsOfExperience); 
// ❌ Error: Local variable is not accessible outside the function
Try it Yourself »

JavaScript Operators

JavaScript operators are symbols that instruct the language to perform specific operations on values and variables. They are used to carry out calculations, compare data, and assign values, forming the core logic behind every JavaScript program.

JavaScript includes several categories of operators. Some of the most commonly used ones are:

  • Arithmetic Operators – Used to perform mathematical operations such as addition (+), subtraction (-), multiplication (*), and division (/).
  • Assignment Operators – Used to assign and update values stored in variables, most commonly using the = symbol.

Example: Using Arithmetic and Assignment Operators

JavaScript Example

let distanceInKm = 240;
let travelTimeInHours = 4;

// Calculate average speed using arithmetic operators
let averageSpeed = distanceInKm / travelTimeInHours;

console.log("Average Speed:", averageSpeed, "km/h");
Try it Yourself »

JavaScript Expressions

A JavaScript expression is any valid piece of code that evaluates to a single value. Expressions can combine variables, operators, and literal values to produce a result. When JavaScript evaluates an expression, it returns a value that can be stored in a variable, displayed to the user, or used as part of another expression.

Expressions are widely used for performing calculations, processing data, and controlling program logic in real-world JavaScript applications.

Example: Arithmetic Expressions in JavaScript

JavaScript Example

let originalPrice = 80;
let discount = 20;

// Expression to calculate the discounted price
let finalPrice = originalPrice - discount;

// Expression to calculate half of the final price
let halfPrice = finalPrice / 2;

console.log("Final Price:", finalPrice);
console.log("Half Price:", halfPrice);
Try it Yourself »

JavaScript Keywords

JavaScript keywords are reserved words that have a specific, predefined meaning within the language. They are used to define program structure, declare variables, create functions, control execution flow, and implement logic. Because keywords are an essential part of JavaScript syntax, they cannot be used as identifiers such as variable or function names.

Some commonly used JavaScript keywords include function, let, var, const, return, if, and else. These keywords help developers write structured, readable, and maintainable JavaScript programs.

Example: Using JavaScript Keywords in a Function

JavaScript Example

function calculateTotalPrice(price, quantity) {
    let total = price * quantity;
    return total;
}

let itemPrice = 15;
let itemQuantity = 4;

let finalAmount = calculateTotalPrice(itemPrice, itemQuantity);
console.log("Total Amount:", finalAmount);
Try it Yourself »

JavaScript Comments

JavaScript comments are explanatory notes written within the source code that are ignored by the JavaScript engine during execution. Although comments do not affect how a program runs, they are essential for improving code readability, long-term maintainability, and effective collaboration between developers.

Developers commonly use comments to explain complex logic, document important decisions, leave reminders, or temporarily disable sections of code while debugging or testing.

JavaScript supports two primary types of comments:

  • Single-line comments
  • Multi-line comments

Single-line Comments

Single-line comments begin with // and continue until the end of the line. They are best suited for short explanations or inline notes that clarify a specific line of code.

// This is a single-line comment
let count = 5; // Initialize the counter with a starting value

Multi-line Comments

Multi-line comments are written between /* and */. They are useful when you need to add longer explanations or document sections of code.

/*
  This is a multi-line comment
  It can span across multiple lines
*/
let totalUsers = 5;
        

JavaScript Data Types

JavaScript data types describe the type of data that a variable can hold. JavaScript is a dynamically typed language, meaning variables do not require an explicit data type declaration. Instead, the data type is automatically determined at runtime based on the value assigned.

This dynamic behavior allows developers to write flexible and concise code, making JavaScript one of the most popular languages for building modern web applications across the USA, UK, Canada, Europe, and beyond.

JavaScript data types are generally classified into two main categories:

  • Primitive Data Types – Represent simple, immutable values such as numbers, strings, and booleans.
  • Non-Primitive (Reference) Data Types – Represent complex structures that can store multiple values, such as arrays and objects.

Example: Common JavaScript Data Types

JavaScript Example

// String (Primitive)
let platformName = "TechWorld Academy";

// Number (Primitive)
let registeredUsers = 1250;

// Boolean (Primitive)
let isPlatformOnline = true;

// Array (Non-Primitive)
let supportedRegions = ["USA", "UK", "Canada", "Europe"];

// Object (Non-Primitive)
let instructorProfile = {
    name: "Alex Brown",
    experienceYears: 6,
    specialization: "JavaScript",
    active: true
};

console.log(platformName);
console.log(registeredUsers);
console.log(isPlatformOnline);
console.log(supportedRegions);
console.log(JSON.stringify(instructorProfile));
Try it Yourself »

JavaScript Functions

A JavaScript function is a reusable block of code that performs a specific task. Functions help structure applications by breaking complex logic into smaller, manageable pieces. They reduce code duplication, improve readability, and make programs easier to test and maintain. A function executes only when it is called (also known as being invoked).

In modern web development, functions are essential for handling calculations, responding to user actions, processing data, and implementing business logic in applications used across the USA, UK, Canada, Europe, and worldwide.

Function Syntax

function functionName(parameters) {
    // code to be executed
    // return a value (optional)
}

Example: JavaScript Function with Parameters and Return Value

JavaScript Example

function calculateFinalPrice(price, tax) {
    let total = price + tax;
    return total;
}

let productPrice = 45;
let taxAmount = 5;

let finalPrice = calculateFinalPrice(productPrice, taxAmount);
console.log("Final Price:", finalPrice);
Try it Yourself »

JavaScript Identifiers

JavaScript identifiers are names used to uniquely identify variables, functions, classes, and other elements within a program. Choosing descriptive and meaningful identifiers improves code readability, reduces confusion, and makes long-term maintenance easier—especially in large or collaborative projects.

In JavaScript, identifiers must follow specific naming rules defined by the language:

  • They must begin with a letter (A–Z or a–z).
  • They may also start with a dollar sign ($) or an underscore (_).
  • They cannot start with a numeric character.
  • Only letters, numbers, underscores, and dollar signs are allowed.
  • JavaScript identifiers are case-sensitive.

JavaScript Camel Case

Camel case is the most widely used naming convention in JavaScript. In camelCase, the first word starts with a lowercase letter, while each subsequent word begins with an uppercase letter. This convention is strongly recommended and commonly followed by developers in the USA, UK, Canada, Europe, and the global JavaScript community.

Example: Valid JavaScript Identifiers

JavaScript Example

// Valid JavaScript identifiers
let userName = "Alice";
let _accountStatus = "Active";
let $monthlySubscription = 29.99;
let totalLogins2024 = 120;

console.log(userName);
console.log(_accountStatus);
console.log($monthlySubscription);
console.log(totalLogins2024);
Try it Yourself »