JavaScript Basic Syntax

re! Here’s a detailed explanation of the basic syntax of JavaScript to help you get started with programming.

1. Variables

Variables are used to store data values. In JavaScript, you can declare variables using let, const, or var.

  • let: Allows you to declare a block-scoped variable, which means it’s limited to the block in which it is defined.

      let name = "Alice";
    
  • const: Declares a block-scoped variable that cannot be reassigned. It's used for constants.

      const PI = 3.14;
    
  • var: An older way to declare variables. It’s function-scoped, which means it can lead to unexpected behavior in some cases.

      var age = 25;
    

2. Data Types

JavaScript has several data types, including:

  • String: Represents text data, enclosed in single or double quotes.

      let greeting = "Hello, world!";
    
  • Number: Represents both integer and floating-point numbers.

      let count = 10;
      let price = 99.99;
    
  • Boolean: Represents true or false.

      let isOnline = true;
    
  • Null: Represents the intentional absence of any value.

      let emptyValue = null;
    
  • Undefined: A variable that has been declared but not assigned a value.

      let notAssigned;
    
  • Object: A collection of key-value pairs.

      let person = {
          name: "Alice",
          age: 30
      };
    
  • Array: A special type of object that holds a list of values.

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

3. Operators

JavaScript includes various operators:

  • Arithmetic Operators: +, -, *, /, % (modulus).

      let sum = 5 + 3; // 8
      let remainder = 10 % 3; // 1
    
  • Assignment Operators: =, +=, -=, etc.

      let x = 10;
      x += 5; // x is now 15
    
  • Comparison Operators: ==, ===, !=, !==, <, >, <=, >=.

      let isEqual = (5 == "5"); // true (type coercion)
      let isStrictEqual = (5 === "5"); // false (no type coercion)
    
  • Logical Operators: && (AND), || (OR), ! (NOT).

      let isAdult = (age >= 18 && age < 65); // true if age is between 18 and 65
    

4. Control Structures

  • Conditional Statements:

      if (age >= 18) {
          console.log("Adult");
      } else {
          console.log("Not an adult");
      }
    
  • Switch Statement:

      switch (day) {
          case 1:
              console.log("Monday");
              break;
          case 2:
              console.log("Tuesday");
              break;
          default:
              console.log("Not a valid day");
      }
    
  • Loops:

    • For Loop:

        for (let i = 0; i < 5; i++) {
            console.log(i); // Prints 0 to 4
        }
      
    • While Loop:

        let count = 0;
        while (count < 5) {
            console.log(count);
            count++;
        }
      

5. Functions

Functions are reusable blocks of code. They can be declared in different ways:

  • Function Declaration:

      function greet(name) {
          return "Hello, " + name;
      }
      console.log(greet("Alice")); // "Hello, Alice"
    
  • Function Expression:

      const add = function (a, b) {
          return a + b;
      };
      console.log(add(3, 5)); // 8
    
  • Arrow Function (ES6 feature):

      const multiply = (a, b) => a * b;
      console.log(multiply(2, 4)); // 8
    

6. Objects and Arrays

  • Creating an Object:

      let car = {
          make: "Toyota",
          model: "Camry",
          year: 2020
      };
      console.log(car.make); // "Toyota"
    
  • Accessing Array Elements:

      let colors = ["red", "green", "blue"];
      console.log(colors[0]); // "red"
    

7. Comments

You can add comments in your code using // for single-line comments and /* ... */ for multi-line comments.

// This is a single-line comment
/*
This is a 
multi-line comment
*/

Putting It All Together

Here’s a simple program that uses many of these elements:

// Function to calculate the area of a rectangle
function calculateArea(length, width) {
    return length * width;
}

// Variables
let length = 5;
let width = 10;

// Calculate area and display it
let area = calculateArea(length, width);
console.log("Area of the rectangle:", area); // Area of the rectangle: 50

Did you find this article valuable?

Support Sarthak by becoming a sponsor. Any amount is appreciated!