Home » JavaScript Syntax Tutorial with Examples

JavaScript Syntax Tutorial with Examples

JavaScript syntax refers to the set of rules that defines how JavaScript code is written and structured. Understanding JavaScript syntax is crucial for writing correct and efficient programs.

This tutorial will cover the most important aspects of JavaScript syntax, including variables, data types, operators, conditionals, loops, functions, and objects.

In this tutorial, you’ll learn:

Variables and Constants
Data Types
Operators
Conditionals (if/else statements)
Loops
Functions
Objects
Arrays
Template Literals

1. Variables and Constants

In JavaScript, variables are used to store data. You can declare variables using the let, const, or var keywords.

let: Allows you to declare variables that can be reassigned later.
const: Declares constants whose value cannot be changed once assigned.
var: The old way of declaring variables, which has function-scoped behavior. It’s better to use let and const in modern JavaScript.

Example 1: Variable Declaration

let name = "Alice";    // Declaring a variable
const age = 30;        // Declaring a constant
var city = "New York"; // Declaring a variable using var (old syntax)

console.log(name, age, city);

In this example:

name is declared with let, and its value can be changed.
age is declared with const, meaning it cannot be reassigned.
city is declared with var, which behaves similarly to let but is function-scoped.

2. Data Types

JavaScript supports multiple data types, including:

Number: Represents numeric values (integers and floats).
String: Represents text data.
Boolean: Represents logical values (true or false).
Object: Represents collections of key-value pairs.
Array: A special type of object used for storing ordered lists of values.
Undefined: A variable that has been declared but has not been assigned a value.
Null: Represents an intentional absence of value.

Example 2: Basic Data Types

let age = 25;                    // Number
let name = "Alice";               // String
let isStudent = true;             // Boolean
let city;                         // Undefined
let emptyValue = null;            // Null

console.log(typeof age);          // Output: number
console.log(typeof name);         // Output: string
console.log(typeof isStudent);    // Output: boolean
console.log(typeof city);         // Output: undefined
console.log(typeof emptyValue);   // Output: object (null is treated as an object in JavaScript)

3. Operators

JavaScript provides a wide range of operators to perform various operations on variables and values:

Arithmetic operators: +, -, *, /, %
Assignment operators: =, +=, -=, *=, /=
Comparison operators: ==, ===, !=, !==, <, >, <=, >=
Logical operators: &&, ||, !

Example 3: Using Operators

let x = 10;
let y = 5;

let sum = x + y;              // Arithmetic
let isEqual = (x === y);      // Comparison (strict equality)
let isGreater = (x > y);      // Comparison

let isBothTrue = (x > 0 && y > 0);  // Logical AND
let isEitherTrue = (x < 0 || y > 0);  // Logical OR

console.log(sum, isEqual, isGreater, isBothTrue, isEitherTrue);

In this example:

Arithmetic operators are used to calculate sum.
Comparison operators check for equality and inequality.
Logical operators (&&, ||) are used to evaluate conditions.

4. Conditionals (if/else statements)

Conditional statements in JavaScript allow you to execute different blocks of code based on conditions.

Example 4: Basic if/else Statement

let age = 18;

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

In this example:

The if statement checks if age is greater than or equal to 18.
If the condition is true, the first block is executed; otherwise, the else block is executed.

Example 5: if/else if/else Statement

let score = 85;

if (score >= 90) {
    console.log("Grade A");
} else if (score >= 80) {
    console.log("Grade B");
} else {
    console.log("Grade C");
}

5. Loops

Loops are used to repeatedly execute a block of code as long as a certain condition is met.

Example 6: for Loop

for (let i = 0; i < 5; i++) {
    console.log("Number:", i);
}

In this example:

The for loop runs 5 times, with the variable i incrementing by 1 in each iteration.

Example 7: while Loop

let i = 0;
while (i < 5) {
    console.log("Number:", i);
    i++;
}

In this example:

The while loop runs as long as the condition i < 5 is true.

6. Functions

Functions allow you to encapsulate code in reusable blocks. Functions can take input values (parameters) and return results.

Example 8: Function Declaration

function greet(name) {
    return `Hello, ${name}!`;
}

console.log(greet("Alice"));  // Output: Hello, Alice!

In this example:

The greet function takes a name parameter and returns a greeting message.

Example 9: Function Expression (Anonymous Function)

const add = function(x, y) {
    return x + y;
};

console.log(add(5, 10));  // Output: 15

7. Objects

Objects are key-value pairs that store data in a structured way. You can define methods (functions) inside objects.

Example 10: Defining and Accessing Object Properties

let person = {
    name: "Alice",
    age: 30,
    greet: function() {
        console.log(`Hello, my name is ${this.name}`);
    }
};

console.log(person.name);  // Accessing properties
person.greet();            // Output: Hello, my name is Alice

In this example:

The object person has properties (name, age) and a method (greet).

8. Arrays

Arrays are ordered lists of values and are a special type of object in JavaScript.

Example 11: Declaring and Accessing Arrays

let fruits = ["apple", "banana", "orange"];

console.log(fruits[0]);  // Output: apple
console.log(fruits.length);  // Output: 3

fruits.push("grape");  // Adding an element to the array
console.log(fruits);  // Output: ["apple", "banana", "orange", "grape"]

9. Template Literals

Template literals provide a way to embed expressions and variables inside strings using backticks (`).

Example 12: Using Template Literals

let name = "Alice";
let age = 30;

let greeting = `Hello, my name is ${name}, and I am ${age} years old.`;
console.log(greeting);  // Output: Hello, my name is Alice, and I am 30 years old.

In this example:

Template literals allow variables to be easily embedded within strings using ${}.

Conclusion

This tutorial covers the fundamental syntax of JavaScript, including variables, data types, operators, conditionals, loops, functions, objects, arrays, and template literals. Here's a summary of what you've learned:

Variables store data, and you can declare them with let, const, or var.
Data types include numbers, strings, booleans, objects, arrays, and more.
Operators allow you to perform arithmetic, comparison, and logical operations.
Conditionals like if/else help execute code based on conditions.
Loops like for and while are used to repeat code.
Functions encapsulate reusable blocks of code.
Objects and arrays store collections of data.
Template literals make it easier to work with strings.

By mastering these essential elements of JavaScript syntax, we will cover these and many other topics in greater detail on this site.

You may also like