Skip to content

JavaScript Basic Syntax

JavaScript syntax is the set of rules and structures that must be followed when writing JavaScript code. Mastering the basic syntax is the first and most important step in learning JavaScript. In this chapter, we'll learn the basic syntax rules of JavaScript.

JavaScript Statements

JavaScript programs consist of a series of executable statements. Statements are instructions that perform specific tasks. In JavaScript, statements usually end with a semicolon (😉, but the semicolon is optional.

javascript
let x = 5;
let y = 6;
let z = x + y;

Statement Separators

Although semicolons are optional, it's recommended to always use semicolons to separate statements for code clarity and to avoid potential issues.

javascript
// Recommended approach
let name = "John";
console.log(name);

// Not recommended (though it works)
let age = 25
console.log(age)

JavaScript Code Blocks

JavaScript statements can be combined into code blocks, wrapped with curly braces {}. Code blocks are typically used in functions, conditional statements, and loop statements.

javascript
function myFunction() {
    let message = "Hello World";
    console.log(message);
    return message;
}

JavaScript Comments

Comments are parts of the code that are not executed, used to explain the purpose of the code and improve readability.

Single-Line Comments

Comments starting with // are single-line comments, where the comment content extends from // to the end of the line.

javascript
// This is a single-line comment
let x = 5; // This is also a single-line comment

Multi-Line Comments

Comments wrapped with /* */ are multi-line comments that can span multiple lines.

javascript
/*
This is a multi-line comment
It can span multiple lines
Used for detailed code explanations
*/
let y = 10;

JavaScript Variables

Variables are containers for storing data values. In JavaScript, variables are declared using the var, let, or const keywords.

javascript
var name = "John";
let age = 25;
const PI = 3.14159;

Variable Naming Rules

  1. Variable names must start with a letter, underscore (_), or dollar sign ($)
  2. Variable names can contain letters, numbers, underscores, and dollar signs
  3. Variable names are case-sensitive
  4. JavaScript reserved keywords cannot be used as variable names
javascript
// Correct variable naming
let myVariable = "correct";
let _private = "correct";
let $price = 99.99;
let userName123 = "correct";

// Incorrect variable naming
// let 123name = "wrong"; // Cannot start with a number
// let my-variable = "wrong"; // Cannot contain hyphens
// let let = "wrong"; // Cannot use reserved keywords

JavaScript Data Types

JavaScript has multiple data types, including:

  • String: Used to store text
  • Number: Used to store numeric values
  • Boolean: Represents true or false
  • Object: Used to store complex data
  • Array: Special object type used to store ordered data collections
  • null: Represents "no value"
  • undefined: Represents an undefined value
javascript
let name = "John";        // String
let age = 25;            // Number
let isStudent = true;    // Boolean
let person = {           // Object
    name: "Jane",
    age: 30
};
let colors = ["red", "green", "blue"]; // Array
let empty = null;        // null
let notDefined;          // undefined

JavaScript Operators

Operators are used to perform operations on operands.

Arithmetic Operators

javascript
let x = 10;
let y = 5;

console.log(x + y);  // Addition: 15
console.log(x - y);  // Subtraction: 5
console.log(x * y);  // Multiplication: 50
console.log(x / y);  // Division: 2
console.log(x % y);  // Modulus (remainder): 0
console.log(x ** y); // Exponentiation: 100000

Assignment Operators

javascript
let x = 10;

x += 5;  // Equivalent to x = x + 5
x -= 3;  // Equivalent to x = x - 3
x *= 2;  // Equivalent to x = x * 2
x /= 4;  // Equivalent to x = x / 4

Comparison Operators

javascript
let x = 5;
let y = 10;

console.log(x == y);  // Equal to: false
console.log(x != y);  // Not equal to: true
console.log(x === y); // Strict equal to: false
console.log(x !== y); // Strict not equal to: true
console.log(x > y);   // Greater than: false
console.log(x < y);   // Less than: true
console.log(x >= y);  // Greater than or equal to: false
console.log(x <= y);  // Less than or equal to: true

Logical Operators

javascript
let x = 5;
let y = 10;

console.log(x < 10 && y > 5);  // Logical AND: true
console.log(x < 10 || y < 5);  // Logical OR: true
console.log(!(x == y));        // Logical NOT: true

JavaScript Functions

Functions are reusable code blocks used to perform specific tasks.

javascript
// Function declaration
function greet(name) {
    return "Hello, " + name + "!";
}

// Call function
let message = greet("John");
console.log(message); // Output: Hello, John!

JavaScript Conditional Statements

Conditional statements are used to execute different code blocks based on different conditions.

javascript
let age = 18;

if (age >= 18) {
    console.log("You are an adult");
} else {
    console.log("You are a minor");
}

JavaScript Loop Statements

Loop statements are used to repeatedly execute code blocks.

javascript
// for loop
for (let i = 0; i < 5; i++) {
    console.log("Loop count: " + i);
}

// while loop
let count = 0;
while (count < 5) {
    console.log("Count: " + count);
    count++;
}

JavaScript Error Handling

JavaScript provides the try...catch statement to handle errors.

javascript
try {
    // Code that might cause errors
    let result = x / y;
} catch (error) {
    // Handle error
    console.log("Error occurred: " + error.message);
} finally {
    // Code that will execute regardless of errors
    console.log("Execution completed");
}

JavaScript Strict Mode

Strict mode is a restricted variant of JavaScript that eliminates some of the unreasonable and imprecise aspects of the JavaScript language.

javascript
"use strict";

// In strict mode, undeclared variables will cause an error
// x = 5; // This will cause an error
let x = 5; // Correct approach

JavaScript Code Style Suggestions

  1. Use consistent indentation: Usually use 2 or 4 spaces for indentation
  2. Use meaningful variable names: Variable names should clearly express their purpose
  3. Add comments: Add comments to explain complex logic
  4. Keep code concise: Avoid overly long lines of code and deeply nested structures
  5. Use code formatting tools: Use tools like Prettier to maintain consistent code style
javascript
// Good code style example
function calculateArea(width, height) {
    // Calculate rectangle area
    const area = width * height;
    
    // Output result
    console.log("Rectangle area is: " + area);
    
    return area;
}

// Call function
calculateArea(10, 5);

Summary

JavaScript basic syntax includes:

  1. Statements: The basic unit of JavaScript programs, usually ending with a semicolon
  2. Code Blocks: A collection of statements wrapped in curly braces
  3. Comments: Single-line comments (//) and multi-line comments (/* */)
  4. Variables: Declared using var, let, const, following naming rules
  5. Data Types: Strings, numbers, booleans, objects, arrays, etc.
  6. Operators: Arithmetic, assignment, comparison, logical operators
  7. Functions: Reusable code blocks
  8. Conditional Statements: if...else statements
  9. Loop Statements: for loops, while loops
  10. Error Handling: try...catch statements
  11. Strict Mode: Improves code quality and safety

Mastering these basic syntax elements is an important first step in learning JavaScript. In the next chapter, we'll dive deeper into JavaScript data types.

Content is for learning and research only.