JavaScript Syntax
When learning a new programming language, understanding its syntax is like learning the grammar rules of a spoken language. JavaScript syntax refers to the set of rules that define how JavaScript programs are constructed.
Introduction
JavaScript syntax is the foundation upon which all JavaScript code is built. It defines how variables are declared, how statements are organized, how functions are created, and many other aspects of the language. Mastering JavaScript syntax is essential for writing code that not only works but is also readable and maintainable.
In this guide, we'll explore the fundamental elements of JavaScript syntax, with plenty of examples to help you understand how everything fits together.
Basic Structure of JavaScript Code
JavaScript code consists of:
- Statements: Instructions that perform actions
- Expressions: Code that produces a value
- Comments: Text that is not executed
- Variables: Named storage for data
- Operators: Symbols that perform operations on values
Let's look at each of these components.
Statements
Statements are instructions that the JavaScript interpreter executes. Each statement typically ends with a semicolon (;
), although it's often optional in JavaScript.
// This is a statement
let greeting = "Hello, world!";
// This is another statement
console.log(greeting);
// Multiple statements
let x = 5; let y = 10; let z = x + y;
Statement Blocks
Statement blocks are enclosed in curly braces {}
and are used to group statements together.
// A block of statements
{
let name = "John";
let age = 30;
console.log(name + " is " + age + " years old.");
}
Comments
Comments are used to add notes to your code or to prevent code from being executed.
// This is a single-line comment
/*
This is a
multi-line comment
*/
let total = 100; // You can also add comments at the end of a line
// Code that is commented out doesn't run
// console.log("This won't be displayed");
Variables and Data Types
Variables are containers for storing data values. In JavaScript, you can declare variables using var
, let
, or const
.
// Variable declaration using let
let firstName = "John";
// Variable declaration using const (constant)
const PI = 3.14159;
// Variable declaration using var (older style)
var age = 30;
Data Types
JavaScript supports several data types:
// String
let name = "John Doe";
// Number
let age = 30;
let price = 19.99;
// Boolean
let isActive = true;
// Undefined
let result;
// Null
let empty = null;
// Object
let person = {
name: "John",
age: 30
};
// Array (a type of object)
let colors = ["red", "green", "blue"];
// Function (also a type of object)
let greet = function() {
return "Hello!";
};
Expressions
An expression is any valid code that resolves to a value.
// Arithmetic expressions
let sum = 10 + 5; // 15
let product = 4 * 3; // 12
// String expressions
let fullName = "John" + " " + "Doe"; // "John Doe"
// Logical expressions
let isAdult = age >= 18; // true if age is 18 or more
// Function call expressions
let length = "Hello".length; // 5
let upperName = name.toUpperCase(); // "JOHN DOE"
Operators
JavaScript includes various operators for performing operations on values:
Arithmetic Operators
let a = 10;
let b = 3;
console.log(a + b); // Addition: 13
console.log(a - b); // Subtraction: 7
console.log(a * b); // Multiplication: 30
console.log(a / b); // Division: 3.33...
console.log(a % b); // Remainder: 1
console.log(a ** b); // Exponentiation: 1000
Assignment Operators
let x = 10; // Simple assignment
x += 5; // Add and assign: x = x + 5 (x is now 15)
x -= 3; // Subtract and assign: x = x - 3 (x is now 12)
x *= 2; // Multiply and assign: x = x * 2 (x is now 24)
x /= 4; // Divide and assign: x = x / 4 (x is now 6)
x %= 4; // Remainder and assign: x = x % 4 (x is now 2)
Comparison Operators
let a = 5;
let b = 10;
let c = "5";
console.log(a == c); // Equal to (value): true
console.log(a === c); // Strict equal (value and type): false
console.log(a != b); // Not equal to: true
console.log(a > b); // Greater than: false
console.log(a < b); // Less than: true
console.log(a >= 5); // Greater than or equal: true
console.log(b <= 10); // Less than or equal: true
Logical Operators
let x = 5;
let y = 10;
console.log(x > 0 && y > 0); // Logical AND: true
console.log(x > 0 || y < 0); // Logical OR: true
console.log(!(x > 0)); // Logical NOT: false
Control Flow Statements
Control flow statements determine the order in which code is executed.
Conditional Statements
let age = 20;
// If statement
if (age >= 18) {
console.log("You are an adult.");
}
// If...else statement
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
// If...else if...else statement
if (age < 13) {
console.log("You are a child.");
} else if (age < 18) {
console.log("You are a teenager.");
} else {
console.log("You are an adult.");
}
// Ternary operator: condition ? value if true : value if false
let status = age >= 18 ? "adult" : "minor";
console.log(status); // "adult"
Switch Statement
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week.");
break;
case "Friday":
console.log("End of the work week.");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Midweek.");
}
// Output: "Start of the work week."
Loops
Loops execute a block of code repeatedly until a specified condition is met.
For Loop
// Count from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1, 2, 3, 4, 5
While Loop
// Count from 1 to 5 using while
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
// Output: 1, 2, 3, 4, 5
Do...While Loop
// Count from 1 to 5 using do...while
let j = 1;
do {
console.log(j);
j++;
} while (j <= 5);
// Output: 1, 2, 3, 4, 5
For...Of Loop (for arrays)
// Iterate through array elements
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
console.log(fruit);
}
// Output: "apple", "banana", "orange"
For...In Loop (for objects)
// Iterate through object properties
let person = {
name: "John",
age: 30,
city: "New York"
};
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Output: "name: John", "age: 30", "city: New York"
Functions
Functions are blocks of code designed to perform a particular task. They are executed when they are called (invoked).
Function Declaration
// Function declaration
function greet(name) {
return "Hello, " + name + "!";
}
// Function call
let message = greet("John");
console.log(message); // Output: "Hello, John!"
Function Expression
// Function expression
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3)); // Output: 8
Arrow Functions
// Arrow function (ES6+)
const multiply = (a, b) => a * b;
console.log(multiply(4, 5)); // Output: 20
// Arrow function with multiple statements
const divide = (a, b) => {
if (b === 0) {
return "Cannot divide by zero";
}
return a / b;
};
console.log(divide(10, 2)); // Output: 5
Real-world Example: Building a Simple Calculator
Let's put together what we've learned by creating a simple calculator:
function calculator() {
// Get user input
const operation = prompt("Enter operation (add, subtract, multiply, divide):");
const num1 = parseFloat(prompt("Enter first number:"));
const num2 = parseFloat(prompt("Enter second number:"));
let result;
// Perform calculation based on operation
switch (operation.toLowerCase()) {
case "add":
result = num1 + num2;
break;
case "subtract":
result = num1 - num2;
break;
case "multiply":
result = num1 * num2;
break;
case "divide":
if (num2 === 0) {
return "Error: Cannot divide by zero";
}
result = num1 / num2;
break;
default:
return "Error: Invalid operation";
}
// Return the result
return `Result: ${result}`;
}
// Execute the calculator function
console.log(calculator());
/* Example Output:
If user enters:
- Operation: "multiply"
- First number: 5
- Second number: 3
Output: "Result: 15"
*/
Example: Creating a Simple Todo List Manager
Here's a more complex example using multiple JavaScript syntax features:
// Todo List Manager
const todoList = {
tasks: [],
// Add a task
addTask(description) {
const task = {
id: Date.now(),
description: description,
completed: false
};
this.tasks.push(task);
return task;
},
// Remove a task
removeTask(id) {
const index = this.tasks.findIndex(task => task.id === id);
if (index !== -1) {
this.tasks.splice(index, 1);
return true;
}
return false;
},
// Mark task as completed
completeTask(id) {
const task = this.tasks.find(task => task.id === id);
if (task) {
task.completed = true;
return true;
}
return false;
},
// Get all tasks
getAllTasks() {
return this.tasks;
},
// Get completed tasks
getCompletedTasks() {
return this.tasks.filter(task => task.completed);
},
// Get incomplete tasks
getIncompleteTasks() {
return this.tasks.filter(task => !task.completed);
}
};
// Example usage
todoList.addTask("Learn JavaScript");
todoList.addTask("Practice coding");
todoList.addTask("Build a project");
console.log("All tasks:", todoList.getAllTasks());
const secondTaskId = todoList.tasks[1].id;
todoList.completeTask(secondTaskId);
console.log("Completed tasks:", todoList.getCompletedTasks());
console.log("Incomplete tasks:", todoList.getIncompleteTasks());
/* Example Output:
All tasks: [
{ id: 1629380000000, description: 'Learn JavaScript', completed: false },
{ id: 1629380000001, description: 'Practice coding', completed: true },
{ id: 1629380000002, description: 'Build a project', completed: false }
]
Completed tasks: [
{ id: 1629380000001, description: 'Practice coding', completed: true }
]
Incomplete tasks: [
{ id: 1629380000000, description: 'Learn JavaScript', completed: false },
{ id: 1629380000002, description: 'Build a project', completed: false }
]
*/
Summary
In this guide, we've covered the essential elements of JavaScript syntax:
- Statements and expressions: The building blocks of JavaScript code
- Comments: How to document your code
- Variables and data types: How to store and manipulate different kinds of data
- Operators: How to perform operations on values
- Control flow statements: How to control the execution flow of your code
- Loops: How to repeat code execution
- Functions: How to create reusable blocks of code
Understanding JavaScript syntax is fundamental to becoming proficient in the language. As you continue learning, you'll discover that JavaScript has many more features and capabilities, but they all build upon the syntax fundamentals we've explored here.
Practice Exercises
To reinforce your understanding of JavaScript syntax, try these exercises:
- Write a function that takes a number and returns true if it's even, false if it's odd.
- Create a program that calculates the sum of all numbers from 1 to n, where n is provided by the user.
- Write a function that takes an array of numbers and returns a new array containing only the even numbers.
- Create an object representing a book with properties for title, author, and year, and a method that returns a string in the format "Title by Author (Year)".
- Write a program that prints the Fibonacci sequence up to a specified number of terms.
Additional Resources
- MDN Web Docs - JavaScript Guide
- JavaScript.info - The Modern JavaScript Tutorial
- Eloquent JavaScript - A free online book
- JavaScript Style Guide - Best practices for JavaScript coding
Keep practicing and experimenting with different aspects of JavaScript syntax to become more comfortable and proficient with the language!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)