JavaScript - Syntax

-

Basic Syntax Rules

JavaScript has basic syntax rules to follow when writing code. These rules help keep your code consistent, readable, and error-free.

Case sensitivity is important in JavaScript syntax. JavaScript distinguishes between uppercase and lowercase letters.

Example: Case Sensitivity

let myVariable = 5;
let myvariable = 10;
// myVariable and myvariable are different variables

Semicolons separate statements in JavaScript. Although semicolons are optional in some cases, always include them at the end of each statement for clarity and consistency.

Example: Semicolons

let x = 5;
console.log(x);

White space, such as spaces and tabs, is ignored by JavaScript. Use white space to make your code more readable and easier to understand. Use white space consistently throughout your code.

Line breaks are also ignored by JavaScript, allowing you to split long lines of code into multiple lines for better readability. You can break lines after operators, commas, or brackets.

Example: Line Breaks

let sum = a + b +
          c + d;

Comments add explanatory notes to your code. They are ignored by JavaScript and do not affect the execution of your program. There are two types of comments in JavaScript:

  1. Single-line comments: These comments start with // and extend until the end of the line.

Example: Single-line Comments

   // This is a single-line comment
   let x = 5; // Another single-line comment
  1. Multi-line comments: These comments start with /* and end with */. They can span multiple lines.

Example: Multi-line Comments

   /*
   This is a
   multi-line comment
   */
   let y = 10;

Using comments can make your code more understandable and help you and other developers maintain and debug your code.

Here is the formatted paragraph:

Variables

Variables are containers for storing data values in JavaScript. They let you store and change data throughout your program. To declare variables in JavaScript, you can use the var, let, or const keywords.

The var keyword is the oldest way to declare variables in JavaScript. Variables declared with var are function-scoped, meaning they are accessible within the function in which they are declared or globally if declared outside any function.

Example: Declaring variables with var

var x = 5;
var name = "John";

The let keyword, introduced in ECMAScript 2015 (ES6), is used to declare block-scoped variables. Variables declared with let are only accessible within the nearest enclosing block, such as an if statement or a loop.

Example: Declaring variables with let

let count = 0;
let isTrue = true;

The const keyword, also introduced in ES6, is used to declare constants - variables whose values cannot be reassigned. Constants must be initialized with a value when they are declared and cannot be changed later.

Example: Declaring constants with const

const PI = 3.14159;
const MAX_SIZE = 100;

When naming variables in JavaScript, follow these naming conventions:

  • Use meaningful and descriptive names that reflect the purpose of the variable.
  • Use camelCase for variable names (e.g., firstName, totalAmount).
  • Avoid using reserved keywords as variable names.
  • Variable names are case-sensitive, so myVariable and myvariable are different variables.

To assign a value to a variable, use the assignment operator (=). You can assign various types of values to variables, such as numbers, strings, booleans, objects, or arrays.

Example: Assigning values to variables

let age = 25;
let message = "Hello, world!";
let isStudent = true;
let person = { name: "John", age: 30 };
let numbers = [1, 2, 3, 4, 5];

You can also reassign values to variables declared with var or let later in your code. However, variables declared with const cannot be reassigned.

Example: Reassigning variables

let count = 0;
count = 5;
console.log(count); // Output: 5

const PI = 3.14;
PI = 3.14159; // Error: Assignment to a constant variable

Data Types

JavaScript has built-in data types to store and work with different kinds of values. These data types are in two categories: primitive data types and object data types.

Primitive data types are simple and immutable values that are not objects. JavaScript has five primitive data types:

  1. Number: Represents numeric values, including integers and floating-point numbers.

Example: Number data type

   let age = 25;
   let price = 9.99;
  1. String: Represents text data, enclosed in single quotes ('') or double quotes ("").

Example: String data type

   let name = "John";
   let message = 'Hello, world!';
  1. Boolean: Represents a logical value, either true or false.

Example: Boolean data type

   let isStudent = true;
   let isMarried = false;
  1. Undefined: Represents a variable that has been declared but has not been assigned a value.

Example: Undefined data type

   let myVariable;
   console.log(myVariable); // Output: undefined
  1. Null: Represents a deliberate non-value or null value.

Example: Null data type

   let myValue = null;

The object data type is a complex data type that can store collections of key-value pairs. Objects in JavaScript can be created using object literals or constructor functions.

Example: Object data type

let person = {
  name: "John",
  age: 30,
  city: "New York"
};

Example: Checking data types with typeof

let age = 25;
console.log(typeof age); // Output: "number"

let name = "John";
console.log(typeof name); // Output: "string"

let isStudent = true;
console.log(typeof isStudent); // Output: "boolean"

let myVariable;
console.log(typeof myVariable); // Output: "undefined"

let myValue = null;
console.log(typeof myValue); // Output: "object" (a known quirk in JavaScript)

let person = { name: "John", age: 30 };
console.log(typeof person); // Output: "object"

Understanding the different data types in JavaScript is important for working with variables, performing operations, and making decisions in your code. Knowing how to check the data type of a value using typeof can be useful for debugging and making sure variables are used correctly in your programs.

Operators

JavaScript has various operators that let you perform operations on variables and values. These operators include arithmetic, assignment, comparison, logical, string, and the conditional (ternary) operator.

Arithmetic Operators

Arithmetic operators perform mathematical calculations on numbers. The main arithmetic operators in JavaScript are:

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder/Modulo
++ Increment
-- Decrement

Example

let x = 10;
let y = 5;
console.log(x + y); // Output: 15
console.log(x - y); // Output: 5
console.log(x * y); // Output: 50
console.log(x / y); // Output: 2
console.log(x % y); // Output: 0
console.log(++x); // Output: 11
console.log(--y); // Output: 4

Assignment Operators

Assignment operators assign values to variables. The basic assignment operator is the equals sign (=). JavaScript also has compound assignment operators that combine an arithmetic operation with assignment, such as +=, -=, *=, /=, and %=.

Example

let x = 10;
x += 5; // Equivalent to x = x + 5
console.log(x); // Output: 15

let y = 20;
y -= 3; // Equivalent to y = y - 3
console.log(y); // Output: 17

Comparison Operators

Comparison operators compare two values and return a boolean result (true or false). The main comparison operators in JavaScript are:

Operator Description
== Equal to
!= Not equal to
=== Strictly equal to
!== Strictly not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Example

let x = 5;
let y = "5";
console.log(x == y);  // Output: true (loose equality)
console.log(x === y); // Output: false (strict equality)
console.log(x != y);  // Output: false (loose inequality)
console.log(x !== y); // Output: true (strict inequality)
console.log(x > 3);   // Output: true
console.log(x < 10);  // Output: true

Logical Operators

Logical operators combine multiple conditions and return a boolean result. The main logical operators in JavaScript are:

Operator Description
&& Logical AND
\|\| Logical OR
! Logical NOT

Example

let x = 5;
let y = 10;
console.log(x < 10 && y > 5); // Output: true
console.log(x < 10 || y < 5); // Output: true
console.log(!(x === y));      // Output: true

String Operators

String operators concatenate (join) strings together. The main string operator in JavaScript is the concatenation operator (+).

Example

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: "John Doe"

Conditional (Ternary) Operator

The conditional (ternary) operator is a shorthand way to write an if-else statement. It takes three operands: a condition, a value to return if the condition is true, and a value to return if the condition is false.

Example

let age = 20;
let canDrink = (age >= 21) ? "Yes" : "No";
console.log(canDrink); // Output: "No"

Operators are essential for performing various operations and making decisions in your JavaScript code.

Control Structures

Control structures in JavaScript let you control the flow of your program by making decisions, repeating code, and jumping to different parts of your code based on conditions. The main control structures in JavaScript are:

if...else statements

if...else statements let you run different code based on a condition. If the condition is true, the code inside the if block is run. If the condition is false, the code inside the else block (if present) is run.

Example: if...else statement

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

You can also chain multiple conditions using else if:

Example: if...else if...else statement

let grade = 85;
if (grade >= 90) {
  console.log("A");
} else if (grade >= 80) {
  console.log("B");
} else if (grade >= 70) {
  console.log("C");
} else {
  console.log("F");
}

switch statements

switch statements provide a way to run different code based on multiple possible values of a variable or expression. The switch statement compares the value of the expression with each case and runs the code block associated with the matching case.

Example: switch statement

let fruit = "apple";
switch (fruit) {
  case "apple":
    console.log("This is an apple.");
    break;
  case "banana":
    console.log("This is a banana.");
    break;
  case "orange":
    console.log("This is an orange.");
    break;
  default:
    console.log("Unknown fruit.");
}

for loops

for loops let you repeat a block of code a specified number of times. The loop consists of three parts: initialization, condition, and increment/decrement.

Example: for loop

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

You can also use for...in loops to iterate over the properties of an object and for...of loops to iterate over the elements of an iterable object (e.g., arrays, strings).

while loops

while loops repeat a block of code as long as a specified condition is true. The loop continues to run until the condition becomes false.

Example: while loop

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

do...while loops

do...while loops are similar to while loops, but the code block is run at least once before the condition is checked. The loop continues to run until the condition becomes false.

Example: do...while loop

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

break and continue statements

The break statement is used to exit a loop early. When found, it immediately ends the loop and continues with the next statement after the loop.

Example: break statement

for (let i = 0; i < 5; i++) {
  if (i === 3) {
    break;
  }
  console.log(i);
}

The continue statement is used to skip the rest of the current iteration and move to the next iteration of the loop.

Example: continue statement

for (let i = 0; i < 5; i++) {
  if (i === 3) {
    continue;
  }
  console.log(i);
}

Control structures give you the power to control the flow of your JavaScript code, letting you make decisions, repeat code, and handle different scenarios based on conditions.

Functions

Functions are important concepts in JavaScript. They let you define reusable code blocks that do specific tasks. Functions can accept inputs (called parameters or arguments) and can return outputs.

To define a function in JavaScript, use the function keyword followed by the function name, a list of parameters in parentheses (if any), and the function body enclosed in curly braces {}.

Example: Defining a function

function greet(name) {
  console.log("Hello, " + name + "!");
}

To call (or invoke) a function, use the function name followed by parentheses containing any arguments you want to pass to the function.

Example: Calling a function

greet("John"); // Output: "Hello, John!"
greet("Jane"); // Output: "Hello, Jane!"

Function parameters are the names listed in the function definition, and arguments are the values passed to the function when it is called.

Example: Function parameters and arguments

function add(a, b) {
  console.log(a + b);
}

add(3, 5); // Output: 8
add(10, 20); // Output: 30

Functions can also return values using the return statement. The return statement specifies the value to be returned by the function. Once a return statement is reached, the function execution stops, and the specified value is returned to the caller.

Example: Returning values from a function

function multiply(a, b) {
  return a * b;
}

let result = multiply(3, 5);
console.log(result); // Output: 15

In ES6, arrow functions were introduced as a more concise way to write functions. Arrow functions use the => syntax and can be written in a shorter form when the function body contains only a single expression.

Example: Arrow functions

const square = (x) => {
  return x * x;
};

console.log(square(4)); // Output: 16

If an arrow function has only one parameter, the parentheses can be omitted. If the function body contains only a single expression, the curly braces and return keyword can also be omitted.

Example: Simplified arrow functions

const double = x => x * 2;

console.log(double(5)); // Output: 10

Functions are a powerful tool in JavaScript that let you organize your code, avoid repetition, and create reusable and modular code blocks. They can be passed as arguments to other functions (known as callback functions) and can be assigned to variables, making them first-class citizens in JavaScript.

Objects

Objects are a basic data type in JavaScript that lets you store and organize data in key-value pairs. They represent real-world entities and can contain properties and methods.

To create an object in JavaScript, use object literal notation. Object literals are defined using curly braces {}, and properties are specified as key-value pairs separated by commas.

Example

let person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  city: "New York"
};

To access the properties of an object, use dot notation (.) or bracket notation ([]). Dot notation is used when you know the name of the property, while bracket notation is used when the property name is dynamic or contains special characters.

Example

console.log(person.firstName); // Output: "John"
console.log(person["lastName"]); // Output: "Doe"

let propertyName = "age";
console.log(person[propertyName]); // Output: 30

You can change the values of object properties by assigning new values to them using dot notation or bracket notation.

Example

person.age = 31;
console.log(person.age); // Output: 31

person["city"] = "Los Angeles";
console.log(person.city); // Output: "Los Angeles"

You can also add new properties to an object by assigning a value to a new property key.

Example

person.email = "john@example.com";
console.log(person.email); // Output: "john@example.com"

Objects can also have methods, which are functions that are associated with an object. Methods are defined as properties that hold function values.

Example

let person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  city: "New York",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

console.log(person.fullName()); // Output: "John Doe"

The this keyword inside the method refers to the object itself, allowing you to access its properties.

Objects in JavaScript are dynamic, meaning you can add, change, or delete properties and methods at any time. They provide a way to organize related data and functions into a single entity.

Objects are widely used in JavaScript for various purposes, such as representing user-defined data structures, configuring options for functions or libraries, and creating complex data models. They are a key part of object-oriented programming in JavaScript and form the foundation for more advanced concepts like prototypes and classes.

Arrays

Arrays are ordered collections of data in JavaScript. They let you store multiple values in a single variable and access them by their index (position).

To create an array in JavaScript, use square brackets []. Array elements are separated by commas.

Example: Creating an array

let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "hello", true, null];

To access array elements, use the index of the element you want to access. Array indexes start at 0 for the first element, 1 for the second element, and so on.

Example: Accessing array elements

let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // Output: "apple"
console.log(fruits[1]); // Output: "banana"
console.log(fruits[2]); // Output: "orange"

You can change the value of an array element by assigning a new value to the specific index.

Example: Changing array elements

let numbers = [1, 2, 3, 4, 5];
numbers[2] = 10;
console.log(numbers); // Output: [1, 2, 10, 4, 5]

Arrays in JavaScript come with built-in methods that let you manipulate and work with array data. Some commonly used array methods are:

Method Description
push() Adds one or more elements to the end of an array.
pop() Removes the last element from an array.
shift() Removes the first element from an array.
unshift() Adds one or more elements to the beginning of an array.
concat() Joins two or more arrays and returns a new array.
slice() Returns a new array with a portion of the original array.
splice() Changes the contents of an array by removing, replacing, or adding elements.
forEach() Runs a function for each element in the array.
map() Creates a new array with the results of calling a function for each element.
filter() Creates a new array with elements that pass a test implemented by a function.
reduce() Runs a reducer function on each element of the array and returns a single value.

Example: Using array methods

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

// Adding elements
fruits.push("grape");
console.log(fruits); // Output: ["apple", "banana", "orange", "grape"]

// Removing elements
fruits.pop();
console.log(fruits); // Output: ["apple", "banana", "orange"]

// Concatenating arrays
let moreFruits = ["kiwi", "mango"];
let allFruits = fruits.concat(moreFruits);
console.log(allFruits); // Output: ["apple", "banana", "orange", "kiwi", "mango"]

// Slicing arrays
let slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // Output: ["banana", "orange"]

// Mapping arrays
let upperCaseFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(upperCaseFruits); // Output: ["APPLE", "BANANA", "ORANGE"]

Arrays are a powerful and flexible data structure in JavaScript. They let you store, organize, and manipulate collections of data efficiently. With the various array methods available, you can easily perform common operations like adding, removing, transforming, and searching elements within arrays.