MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱ MONOTONE ✱
J
A
V
A
S
C
R
I
P
T

01 FOUNDATION

JavaScript is a versatile programming language primarily used for web development, enabling interactive and dynamic content on websites. It runs in web browsers, allowing scripts to interact with the content of the webpage, responding to user actions like clicks, form submissions, and page navigation. JavaScript supports event-driven, functional, and imperative programming styles, making it adaptable to a wide range of applications. It can manipulate the Document Object Model (DOM) to dynamically change both the content and appearance of web pages. JavaScript also plays a crucial role in modern web development frameworks and libraries, like React, Angular, and Vue.js, which facilitate the creation of complex, single-page applications. Additionally, with the advent of Node.js, JavaScript has expanded beyond the browser, enabling server-side scripting and the development of desktop and mobile applications.

Variables

Variables


JavaScript variables are a fundamental aspect of the language, serving as a means to store, retrieve, and manipulate data. They act as named containers for data, significantly enhancing the readability and reusability of code. Instead of repeatedly using specific values, programmers can utilize variables to represent these values, making the code more flexible and easier to manage. In JavaScript, variable declaration is primarily done using one of three keywords: var, let, or const, each serving a specific purpose.


var


The var keyword is the oldest and was widely used in pre-ES6 versions of JavaScript. Variables declared with var are function-scoped, meaning they are accessible within the entire function in which they are declared. If declared outside any function, they are globally accessible. A notable feature of var is that it is subject to hoisting, where the declaration of the variable is moved to the top of its scope, irrespective of where it was initially declared.The introduction of ES6 brought in let and const, providing more options for variable declaration with enhanced scope management.

                
// Example 1: Using 'var' to declare a global variable
var globalVariable = "I am global";
console.log(globalVariable); // Outputs: I am global

                  
// Example 2: 'var' is function-scoped and gets hoisted
function testVar() {
  if(true) {
    var functionScopedVariable = "I am inside a function";
  }
  console.log(functionScopedVariable); // Outputs: I am inside a function
}
testVar();
              
            

let


The let keyword allows for block-scoped variables, restricting their accessibility to the block, statement, or expression where they are declared. This is particularly useful in loops and conditional statements, as it limits the variable's scope to that specific block, enhancing code clarity and preventing unintended errors. Variables declared with let can be reassigned but not redeclared within the same scope. If a let variable is not initialized during declaration, it is assigned the value undefined.

                
// Example 1: 'let' for block-scoped variables
for (let i = 0; i < 3; i++) {
  console.log(i); // Outputs: 0, 1, 2
}
// console.log(i); // Uncaught ReferenceError: i is not defined

                  
// Example 2: Reassigning a 'let' variable
let mutableVariable = "Initial Value";
console.log(mutableVariable); // Outputs: Initial Value
                  
mutableVariable = "Changed Value";
console.log(mutableVariable); // Outputs: Changed Value
                
              

const


For situations where a variable's value is meant to remain constant, const is used. Like let, const also provides block-scoped variables. However, it adds a layer of protection by making the variable's value immutable - once a const variable is assigned a value during declaration, it cannot be reassigned. Attempting to change the value of a const variable results in a runtime error. This feature is particularly useful for maintaining constants and ensuring that their values remain unchanged throughout the execution of the program. Choosing between var, let, and const depends on the specific needs of the program, particularly in terms of scope and the variable's mutability. Understanding these differences is crucial for effective programming in JavaScript, as it directly impacts the functionality and reliability of the code.

              
// Example 1: Declaring a constant
const pi = 3.14;
console.log(pi); // Outputs: 3.14
pi = 3.15; 
// Uncaught TypeError: Assignment to constant variable.

                
// Example 2: 'const' in an object
const person = { name: "Alice", age: 25 };
console.log(person); // Outputs: { name: "Alice", age: 25 }
                
// While the object is constant, its properties can be changed
person.age = 26;
console.log(person); // Outputs: { name: "Alice", age: 26 }
              
            

Data Types


In JavaScript, variables can hold several types of data. Strings represent text and are enclosed in quotes, while Numbers handle both integers and floating-point values without quotes. Booleans represent logical values, either true or false. Arrays store ordered collections of values, accessible via indices. Objects, a versatile construct, can represent more complex data structures, encompassing anything from simple key-value pairs to functions and arrays.

              
// String: A sequence of text, enclosed in single or double quotes.
let myString = 'Hello, World!'; // Using single quotes
let anotherString = "Hello, World!"; // Using double quotes
                
// Number: Represents numerical values, without quotes.
let myNumber = 25; // An integer
let myFloat = 3.14; // A floating-point number
                
// Boolean: Represents a logical entity, can be either true or false.
let myBoolean = true; // The value true
let anotherBoolean = false; // The value false
                
// Array: A structure to store multiple values in a single reference.
let myArray = [1, 'Bob', 'Steve', 10];
// Accessing array elements: myArray[0] (1), myArray[1] ('Bob'), etc.
                
// Object: Can represent complex structures; everything in JavaScript can be an object.
let myObject = {
  name: 'Bob',
  age: 30
};
// Accessing object properties: myObject.name ('Bob'), myObject.age (30)
                
// Example of using an object from the web environment
let pageHeader = document.querySelector('h1'); 
// Selects the first h1 element in the document
              
            

Null & Undefined


In JavaScript, null and undefined are both primitive values, but they signify different meanings. null is an explicitly assigned value used to represent the absence of any object value, indicating that a variable is intentionally left empty or unknown. On the other hand, undefined means a variable has been declared but has not yet been assigned a value. undefined is also the default return value for functions that don't explicitly return anything and the value of properties in objects that have not been set. While null is a deliberate assignment, undefined typically indicates that a variable is in its initial state or that something is missing.

                
// Example of null
let plannedMeetingDate = null; 
// The date is intentionally not set yet

// Example of undefined
let result;
console.log(result); 
// Outputs 'undefined' as result has not been assigned a value

// Function returning undefined by default
function testFunction() {
  let a = 5; // Function doesn't return anything
}
let test = testFunction();
console.log(test); // Outputs 'undefined'

// Trying to access a non-existent object property
let person = { name: 'Alice' };
console.log(person.age); 
// Outputs 'undefined' as age property doesn't exist
              
            
Arithmetic & Assignment Op.

Arithmetic Operators


JavaScript provides several arithmetic operators that allow you to perform mathematical calculations on numbers. The + operator is used for addition, adding two numbers together. The - operator handles subtraction, taking one number away from another. For multiplication, the * operator multiplies two numbers. Division is performed using the / operator, dividing one number by another. Lastly, the % (modulo) operator returns the remainder of a division between two numbers.

              
// Addition: Adds two numbers
let sum = 5 + 3; // sum is now 8

// Subtraction: Subtracts one number from another
let difference = 10 - 4; // difference is now 6

// Multiplication: Multiplies two numbers
let product = 7 * 3; // product is now 21

// Division: Divides one number by another
let quotient = 20 / 5; // quotient is now 4

// Modulo: Returns the remainder of a division
let remainder = 26 % 4; // remainder is now 2
              
            

Assignment Operators


The assignment operator in JavaScript is crucial for assigning values to variables. The basic assignment operator = assigns the right operand's value to its left operand. JavaScript also includes compound assignment operators that combine arithmetic operations with assignment, making code more concise. These operators include += for addition, -= for subtraction, *= for multiplication, and /= for division. Each of these operators performs the specified arithmetic operation on the left operand with the right operand and then assigns the result back to the left operand.

              
// Initialize variables for demonstration
let a = 10, b = 20, c = 4, d = 15;

// '+=' operator: Adds right operand to the left and assigns the result to the left
a += 5; // Equivalent to a = a + 5;
console.log(a); // Outputs: 15

// '-=' operator: Subtracts right operand from the left and assigns the result to the left
b -= 5; // Equivalent to b = b - 5;
console.log(b); // Outputs: 15

// '*=' operator: Multiplies left operand by the right and assigns the result to the left
c *= 3; // Equivalent to c = c * 3;
console.log(c); // Outputs: 12

// '/=' operator: Divides left operand by the right and assigns the result to the left
d /= 3; // Equivalent to d = d / 3;
console.log(d); // Outputs: 5

// Basic assignment
let number = 5; // Assigns the value 5 to the variable 'number'
console.log(number); // Outputs: 5
                
// Assignment with strings
let greeting = "Hello, world!"; // Assigns the string "Hello, world!" to the variable 'greeting'
console.log(greeting); // Outputs: Hello, world!
                
// Reassignment
let age = 30; // Initially assigns 30 to 'age'
console.log(age); // Outputs: 30
                
age = 31; // Reassigns the value of 'age' to 31
console.log(age); // Outputs: 31
                
// Assigning the result of an expression
let sum = 10 + 5; // Assigns the result of 10 + 5, which is 15, to 'sum'
console.log(sum); // Outputs: 15
                
// Assigning the value of another variable
let firstNumber = 7;
let secondNumber = firstNumber; // Assigns the value of 'firstNumber' to 'secondNumber'
console.log(secondNumber); // Outputs: 7 
              
            
Comments

Single & Multi-Line Comments


In JavaScript, single-line comments are created using two forward slashes //, and they comment out everything from the slashes to the end of the line. Multi-line comments start with /* and end with */, spanning multiple lines if needed. Single-line comments are typically used for brief notes or to quickly disable a line of code. In contrast, multi-line comments are suited for longer explanations or for commenting out large sections of code during development or debugging. Both types of comments are essential for making code more understandable and maintainable.


                
// This is a single-line comment
let x = 5; // This comment is after a line of code

/* This is a multi-line comment
   which can span across
   several lines */
let y = 10;
              
            
Strings

Strings


In JavaScript, strings are a primitive data type used to represent text. They consist of a sequence of characters, which can include letters, numbers, spaces, and symbols. Strings are enclosed in either single quotes (') or double quotes ("), and both types of quotes offer the same functionality. The choice between single and double quotes is often based on personal or organizational coding standards, and it's common to stick with one type for consistency. JavaScript also supports template literals (enclosed in backticks `) for strings, which allow for embedded expressions and multi-line strings.


                
// String enclosed in single quotes
let singleQuoteString = 'Hello, World!';

// String enclosed in double quotes
let doubleQuoteString = "JavaScript is fun!";

// String with numbers and symbols
let stringWithNumbers = 'Version 2.0 - Released in 2021!';
              
            

String Concatenation


String concatenation in JavaScript is the process of joining two or more strings together into one. This is most commonly achieved using the + operator. When the + operator is used between strings, it appends the second string to the first, creating a new combined string. Concatenation is not limited to just two strings and can involve multiple strings. It's also flexible enough to concatenate strings with other data types, such as numbers or boolean values, which are converted to strings during the concatenation process.

                
// Basic concatenation of two strings
let greeting = "Hello, " + "world!"; // "Hello, world!"

// Concatenating multiple strings
let fullName = "John" + " " + "Doe"; // "John Doe"

// Concatenating strings with a variable
let name = "Alice";
let welcomeMessage = "Hi, " + name + "!"; // "Hi, Alice!"

// Concatenating strings with other data types
let age = 30;
let ageStatement = "I am " + age + " years old."; // "I am 30 years old."

// Concatenating strings with numbers and boolean values
let score = 75;
let pass = true;
let result = "Score: " + score + ", Pass: " + pass; // "Score: 75, Pass: true"
                
              

String Interpolation & Template Literals


String interpolation in JavaScript is a technique for embedding expressions, such as variables or calculations, within strings. It is achieved using template literals, which are enclosed in backticks (`) instead of regular quotes. Inside these template literals, expressions are placed within placeholders, marked by ${}. This allows for dynamic string creation, where the expressions inside the placeholders are evaluated and their results are seamlessly integrated into the string. Template literals also support multi-line strings and improve readability, especially when concatenating long strings or multiple variables.

              
// Embedding a variable in a string
let name = "Alice";
let greeting = `Hello, ${name}!`; // "Hello, Alice!"

// Using an expression in a string
let price = 10;
let taxRate = 0.05;
let totalPrice = `Total: $${price * (1 + taxRate)}`; // "Total: $10.5"

// Multi-line string using template literals
let item = "coffee";
let quantity = 3;
let order = `You ordered ${quantity} units of:
${item}`; // "You ordered 3 units of:\ncoffee"
              
            

03 FUNCTIONS

Functions in programming are reusable blocks of code that perform specific tasks, enabling better organization and readability of code. They are defined by a unique name and can accept parameters for input, allowing flexibility in their usage. When called, a function's code is executed, and then control returns to the part of the program where it was called. Functions can return values, making their outputs usable in various parts of the program. The use of functions enhances code reusability since the same function can be utilized multiple times with varying inputs. In programming languages, functions can be either built-in, provided by the language itself, or user-defined, created by the programmer for specific tasks. They play a crucial role in modularizing code, breaking down complex problems into smaller, manageable segments.

Function Declaration

In JavaScript, function declarations are a fundamental way to define functions, which are reusable blocks of code. They begin with the 'function' keyword, followed by a unique name that is used to call the function. Optionally, the function can have parameters, listed inside parentheses and separated by commas, to pass data into the function. The core functionality of the function is written inside a set of curly braces {}, encompassing the function body where the specific tasks are coded.

              
function calculateArea(width, height) {
  return width * height;
}              
              
            

A function is called by using its name followed by parentheses. If the function requires arguments, these values are placed inside the parentheses, separated by commas. When the function is called, the JavaScript engine runs the code within the function's body, using the provided arguments if any.

              
// Definining the function
function calculateArea(width, height) {
  return width * height;
}

// Calling the function
calculateArea(5, 10); // 50
              
            

The return keyword within a function is used to pass back a value from the function to the point where it was called. When return is encountered, the function stops executing and sends the specified value back to the caller. If the return keyword is omitted in a function that is expected to produce a value, the function will return undefined by default, which is a common mistake.

              
function addNumbers(a, b) {
  return a + b;
}
  
let sum = addNumbers(5, 3);      
              
            
Arrow Functions

Arrow functions, introduced in ES6, offer a more concise syntax compared to traditional function expressions. They are anonymous and change the way this binds in functions. An arrow function is written with a pair of parentheses () that encloses its parameters, followed by a fat arrow => and the function body. In cases where there's only one parameter, the parentheses around the parameter can be omitted. If the function consists of a single expression, curly braces {} for the body and the return keyword are not required; the result of the expression is returned automatically. However, for more complex functions with multiple expressions, curly braces are necessary, and the return keyword must be explicitly used.

              
// Arrow function with two parameters
const sum = (firstParam, secondParam) => { 
  return firstParam + secondParam; 
}; 

console.log(sum(2, 5)); // Prints: 7

                
// Arrow function with no parameters
const printHello = () => { 
  console.log('hello'); 
}; 

printHello(); // Prints: hello

                
// Arrow function with a single parameter
const checkWeight = weight => { 
  console.log(`Baggage weight : ${weight} kilograms.`); 
}; 

checkWeight(25); // Prints: Baggage weight : 25 kilograms.

                
// Concise arrow function
const multiply = (a, b) => a * b; 

console.log(multiply(2, 30)); // Prints: 60              
              
            
Anonymous Functions

Anonymous functions in JavaScript are functions that are defined without a name. These functions are often used in situations where a function is required as an argument, such as in callbacks or event handlers, and where the function does not need to be called from elsewhere. Anonymous functions can be created using the traditional function keyword or using the arrow function syntax introduced in ES6. Since they don't have a name, they cannot be referred to elsewhere, which is useful for preventing namespace pollution and providing encapsulation.

              
// Named function
function namedFunction() {
  console.log("This is a named function.");
}
namedFunction(); // Calls the named function

                
// Anonymous function using the 'function' keyword
let anonFunc = function() {
  console.log("This is an anonymous function.");
};
anonFunc(); // Calls the anonymous function

                
// Anonymous function using arrow function syntax
let anonArrowFunc = () => {
  console.log("This is an anonymous arrow function.");
};
anonArrowFunc(); // Calls the anonymous arrow function            
              
            
Function Expression

Function expressions in JavaScript allow the creation of functions within an expression, and they can be either named or anonymous. Unlike function declarations, function expressions are not hoisted, so they must be defined before they are used in the code. These expressions are often assigned to a variable, which can then be used as a reference to the function.

              
const square = function(number) {
  return number * number;
};
              
console.log(square(4)); // Outputs: 16