Basic Syntax of JavaScript


The basic syntax of JavaScript involves using a set of rules and conventions to write code that the JavaScript engine (within a web browser or other runtime environment) can interpret and execute. Below are the key components of JavaScript's syntax:

1. Variables

  • Variables are used to store data values. You can declare a variable using var, let, or const.
var x = 10; // Old way, function-scoped let y = 20; // Newer way, block-scoped const z = 30; // Newer way, block-scoped, and cannot be reassigned

2. Data Types

  • JavaScript supports various data types, including numbers, strings, booleans, objects, arrays, and more.
let number = 42; // Number let text = "Hello World"; // String let isTrue = true; // Boolean let person = {name: "John", age: 30}; // Object let array = [1, 2, 3, 4, 5]; // Array

3. Operators

  • JavaScript has various operators, including arithmetic, comparison, logical, and assignment operators.
let sum = 5 + 10; // Arithmetic (+, -, *, /, %) let isEqual = (sum === 15); // Comparison (===, !==, <, >, <=, >=) let andOperator = true && false; // Logical (&&, ||, !)

4. Functions

  • Functions are reusable blocks of code that perform a specific task.
function sayHello(name) { return "Hello, " + name; } let greeting = sayHello("Alice"); // Calling the function console.log(greeting); // Output: "Hello, Alice"

5. Conditionals

  • Conditional statements allow you to execute different code based on certain conditions.
let age = 18; if (age >= 18) { console.log("You are an adult."); } else { console.log("You are a minor."); }

6. Loops

  • Loops are used to repeat a block of code multiple times.
for (let i = 0; i < 5; i++) { console.log("Iteration: " + i); } let j = 0; while (j < 5) { console.log("While loop iteration: " + j); j++; }

7. Objects

  • Objects are collections of key-value pairs, allowing you to group related data and functions.
let car = { make: "Toyota", model: "Camry", year: 2021, start: function() { console.log("Car started"); } }; console.log(car.make); // Accessing object property car.start(); // Calling object method

8. Arrays

  • Arrays are used to store multiple values in a single variable.
let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits[0]); // Accessing array element fruits.push("Orange"); // Adding an element to the array

9. Comments

  • Comments are used to explain code and are ignored by the JavaScript engine.
// This is a single-line comment /* This is a multi-line comment */

10. Events

  • JavaScript can respond to user actions (events) like clicks, keypresses, or page loads.
document.getElementById("myButton").onclick = function() { alert("Button clicked!"); };

11. Error Handling

  • JavaScript uses try, catch, finally, and throw to handle errors.
try { let result = someFunction(); } catch (error) { console.log("An error occurred: " + error.message); } finally { console.log("This code runs no matter what."); }

12. ES6+ Features

  • Modern JavaScript (ES6 and beyond) introduces features like arrow functions, template literals, destructuring, and more.
const add = (a, b) => a + b; // Arrow function let name = "Alice"; console.log(`Hello, ${name}`); // Template literal let [first, second] = [1, 2]; // Array destructuring

Example: Putting It All Together

// Declaring variables let name = "Alice"; let age = 25; // Function to greet the user function greetUser(userName) { return `Hello, ${userName}!`; } // Conditional logic if (age >= 18) { console.log(greetUser(name)); // Calling the function } else { console.log("You are too young."); } // Looping through an array let colors = ["Red", "Green", "Blue"]; for (let i = 0; i < colors.length; i++) { console.log(colors[i]); // Output each color } // Working with objects let user = { name: "Alice", age: 25, greet: function() { return `Hi, I'm ${this.name}`; } }; console.log(user.greet()); // Calling an object method