JavaScript Syntax: A Beginner's Guide to Writing Valid and Readable Code

JavaScript syntax is the set of rules and conventions that govern how we write JavaScript code. It defines the structure, meaning, and style of our code. By following the JavaScript syntax, we can create valid and readable code that can be executed by the JavaScript engine.

Keywords

Keywords are reserved words that have a special meaning in JavaScript. They are used to perform specific actions, define variables, declare functions, create classes, control the flow of the program, and more. Some examples of keywords are let, const, var, function, class, if, else, for, while, switch, case, break, return, throw, try, catch, finally, await, async, yield, import, export, and new.

We cannot use keywords as identifiers, which are names for variables, functions, classes, and other entities. For example, we cannot write:

Javascript
                    
let function = 42; // SyntaxError: Unexpected token 'function'
                    
                

Identifiers

Identifiers are names that we give to variables, functions, classes, and other entities in our code. They allow us to refer to them and manipulate them. Identifiers must follow these rules:

  • They can contain letters, digits, underscores, and dollar signs.
  • They must start with a letter, an underscore, or a dollar sign. They cannot start with a digit.
  • They are case-sensitive, meaning that foo and Foo are different identifiers.
  • They cannot be keywords or reserved words.

Some examples of valid identifiers are:

Javascript
                    
let x = 10;
const PI = 3.14;
var hello_world = "Hello, world!";
function add(a, b) {
  return a + b;
}
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

Comments

Comments are pieces of text that are ignored by the JavaScript engine. They are used to explain, document, or annotate our code. They can help us and other developers understand the purpose, logic, and functionality of our code. There are two types of comments in JavaScript:

  1. Single-line comments: They start with // and end at the end of the line. They are used to comment out a single line of code or write a short note.
  2. Multi-line comments: They start with /* and end with */. They can span multiple lines of code. They are used to comment out a block of code or write a long description.

Some examples of comments are:

Javascript
                    
// This is a single-line comment
let x = 10; // This is another single-line comment

/* This is a multi-line comment
  that can span
  multiple lines of code */
let y = 20; /* This is also a multi-line comment */

Statements

Statements are instructions that tell the JavaScript engine what to do. They usually end with a semicolon (;). They can perform actions, assign values, call functions, create objects, and more. Some examples of statements are:

Javascript
                    
let x = 10; // A statement that declares a variable and assigns a value to it
x++; // A statement that increments the value of x by one
console.log(x); // A statement that calls a function and prints the value of x to the console
let person = new Person("Alice", 25); // A statement that creates an object using a constructor function

Expressions

Expressions are pieces of code that produce a value. They can be literals, variables, operators, function calls, or combinations of them. Some examples of expressions are:

Javascript
                    
10 // A literal expression that produces the value 10
x // A variable expression that produces the value of x
x + y // A binary operator expression that produces the sum of x and y
Math.sqrt(x) // A function call expression that produces the square root of x
person.name // A member access expression that produces the name property of person

Operators

Operators are symbols that perform operations on one or more operands, which are the values or expressions that the operators act on. Operators can be classified into different types, such as:

  • Arithmetic operators: They perform mathematical calculations, such as addition, subtraction, multiplication, division, remainder, exponentiation, and increment/decrement. Some examples are +, -, *, /, %, **, ++, and --.
  • Assignment operators: They assign a value to a variable or a property. Some examples are =, +=, -=, *=, /=, and %=.
  • Comparison operators: They compare two values and return a boolean value (`true` or `false`) indicating the result of the comparison. Some examples are ==, ===, !=, !==, <, >, <=, and >=.
  • Logical operators: They perform logical operations, such as conjunction, disjunction, negation, and conditional. Some examples are `&&`, `||`, `!`, and `??`.
  • Bitwise operators: They perform operations on the binary representation of the operands, such as bitwise AND, OR, XOR, NOT, shift, and rotate. Some examples are &, |, ^, ~, <<, >>, and >>>.
  • String operators: They perform operations on strings, such as concatenation and template literals. Some examples are + and `.
  • Unary operators: They operate on a single operand, such as typeof, delete, and void.
  • Ternary operator: It is the only operator that operates on three operands, and it is used to perform conditional expressions. It has the form condition ? value1 : value2, where condition is a boolean expression, and value1 and value2 are any expressions. It returns value1 if condition is true, and value2 if condition is false.

Literals

Literals are fixed values that are written directly in the code. They can be of different types, such as:

  • Number literals: They represent numeric values, such as integers, decimals, fractions, and scientific notation. Some examples are 10, 3.14, 1/2, and 1.23e4.
  • String literals: They represent textual values, enclosed in single quotes (`' '`) or double quotes (`" "`). Some examples are `'Hello'`, `"World"`, and `"JavaScript"`.
  • Boolean literals: They represent logical values, either `true` or `false`.
  • Null literal: It represents the absence of a value, and it is written as `null`.
  • Undefined literal: It represents an uninitialized value, and it is written as `undefined`.
  • Object literals: They represent objects, which are collections of properties and methods. They are written as comma-separated key-value pairs, enclosed in curly braces (`{ }`). Some examples are `{name: "Alice", age: 25}` and `{add: function(a, b) {return a + b;}}`.
  • Array literals: They represent arrays, which are ordered lists of values. They are written as comma-separated values, enclosed in square brackets ([ ]). Some examples are [1, 2, 3] and ["red", "green", "blue"].
  • Regular expression literals: They represent regular expressions, which are patterns used to match text. They are written as a pattern, enclosed in slashes (/ /), followed by optional flags. Some examples are /[a-z]+/i and /^\d{3}-\d{3}-\d{4}$/.
  • Template literals: They represent strings that can contain expressions, variables, and other features. They are written as text, enclosed in backticks (`). Some examples are `Hello, ${name}!` and `The area is ${Math.PI * r * r}.`.

Semicolons

Semicolons (;) are used to separate statements in JavaScript. They indicate the end of a statement and the start of a new one. They are optional in most cases, as the JavaScript engine can insert them automatically based on certain rules. However, it is recommended to use them explicitly to avoid errors and confusion. Some examples of semicolons are:

Javascript
                    
let x = 10; // A semicolon after an assignment statement
x++; // A semicolon after an increment statement
console.log(x); // A semicolon after a function call statement

This is just the foundation of JavaScript syntax. There's a whole world of exciting possibilities waiting to be explored. Keep learning, keep coding, and unlock the power of JavaScript to build stunning web experiences!