JavaScript Glossary for Beginners

Dive into the world of JavaScript with our extensive glossary tailored for beginners. This comprehensive guide covers 100 essential JavaScript terms, starting from basic concepts like variables and data types, and progressing to more advanced topics such as closures, promises, and modern ES6+ features. Each term is explained concisely with practical code examples, making it the perfect reference for newcomers to JavaScript and a valuable refresher for experienced developers. Whether you're just starting your coding journey or looking to solidify your JavaScript knowledge, this glossary is your go-to resource for understanding the language that powers the web.

Sep 6, 2024

JavaScript Glossary for Beginners

  1. Variable A container for storing data values that can be changed.
    1. let age = 25; age = 26; // Value can be changed
  1. Constant A container for storing data values that cannot be changed after declaration.
    1. const PI = 3.14159; PI = 3.14; // This would cause an error
  1. Data type The classification of data that tells the compiler or interpreter how to use that data.
    1. // JavaScript has several data types: let stringType = "Hello"; // String let numberType = 42; // Number let booleanType = true; // Boolean let undefinedType; // Undefined let nullType = null; // Null let arrayType = [1, 2, 3];// Array let objectType = {}; // Object
  1. String A sequence of characters enclosed in single or double quotes.
    1. let greeting = "Hello, World!"; let name = 'Alice';
  1. Number A numeric data type that includes integers and floating-point numbers.
    1. let integer = 42; let floatingPoint = 3.14;
  1. Boolean A logical data type that can have only two values: true or false.
    1. let isRaining = true; let isSunny = false;
  1. Undefined A variable that has been declared but not assigned a value.
    1. let undefinedVariable; console.log(undefinedVariable); // Output: undefined
  1. Null A special value that represents "nothing" or "no value".
    1. let emptyValue = null;
  1. Array An ordered list of values enclosed in square brackets.
    1. let fruits = ["apple", "banana", "orange"];
  1. Object A collection of key-value pairs enclosed in curly braces.
    1. let person = { name: "John", age: 30, isStudent: false };
  1. Function A reusable block of code that performs a specific task.
    1. function greet(name) { return "Hello, " + name + "!"; } console.log(greet("Alice")); // Output: Hello, Alice!
  1. Operator Symbols that perform operations on variables and values.
    1. let sum = 5 + 3; // Addition operator let product = 4 * 2; // Multiplication operator
  1. Conditional statement Code structures that execute different actions based on specified conditions.
    1. let age = 18; if (age >= 18) { console.log("You can vote!"); } else { console.log("You're too young to vote."); }
  1. Loop A control structure that repeats a block of code multiple times.
    1. for (let i = 0; i < 5; i++) { console.log(i); }
  1. Console.log() A method used to output messages to the console for debugging.
    1. console.log("This is a debug message");
  1. Alert() A method that displays a dialog box with a message and an OK button.
    1. alert("Hello, World!");
  1. Prompt() A method that displays a dialog box asking the user to input some text.
    1. let name = prompt("What's your name?"); console.log("Hello, " + name);
  1. Comment Text in the code that is ignored by the JavaScript engine, used for explanations.
    1. // This is a single-line comment /* This is a multi-line comment */
  1. Semicolon A character used to separate JavaScript statements.
    1. let x = 5; let y = 10; let z = x + y;
  1. Camel case A naming convention where the first word is lowercase and subsequent words start with uppercase.
    1. let firstName = "John"; let lastName = "Doe";
  1. Concatenation The process of combining two or more strings.
    1. let firstName = "John"; let lastName = "Doe"; let fullName = firstName + " " + lastName; // "John Doe"
  1. Template literal A way to create strings that allows embedded expressions and multi-line strings.
    1. let name = "Alice"; let greeting = `Hello, ${name}! Welcome to JavaScript.`;
  1. Comparison operator Operators used to compare two values or expressions.
    1. let x = 5; let y = 10; console.log(x < y); // true console.log(x === 5); // true
  1. Logical operator Operators used to combine or manipulate boolean values.
    1. let isAdult = true; let hasLicense = false; console.log(isAdult && hasLicense); // false (AND) console.log(isAdult || hasLicense); // true (OR)
  1. Assignment operator Operators used to assign values to variables.
    1. let x = 5; // Simple assignment x += 3; // Add and assign (x is now 8) x *= 2; // Multiply and assign (x is now 16)
  1. If statement A conditional statement that executes a block of code if a specified condition is true.
    1. let age = 18; if (age >= 18) { console.log("You're an adult"); }
  1. Else statement Used with an if statement to execute a block of code when the if condition is false.
    1. let age = 16; if (age >= 18) { console.log("You're an adult"); } else { console.log("You're a minor"); }
  1. Else if statement Used to specify a new condition if the first condition is false.
    1. let score = 75; if (score >= 90) { console.log("A"); } else if (score >= 80) { console.log("B"); } else if (score >= 70) { console.log("C"); } else { console.log("F"); }
  1. Switch statement A control flow statement that executes different code blocks based on different cases.
    1. let day = "Monday"; switch (day) { case "Monday": console.log("Start of the week"); break; case "Friday": console.log("End of the work week"); break; default: console.log("Midweek"); }
  1. For loop A loop that repeats a block of code a specified number of times.
    1. for (let i = 0; i < 5; i++) { console.log(i); }
  1. While loop A loop that executes a block of code as long as a specified condition is true.
    1. let i = 0; while (i < 5) { console.log(i); i++; }
  1. Do...while loop A loop that executes a block of code once before checking the condition, then repeats as long as the condition is true.
    1. let i = 0; do { console.log(i); i++; } while (i < 5);
  1. Break statement Used to exit a loop prematurely.
    1. for (let i = 0; i < 10; i++) { if (i === 5) break; console.log(i); }
  1. Continue statement Skips the rest of the current iteration and continues with the next one.
    1. for (let i = 0; i < 5; i++) { if (i === 2) continue; console.log(i); }
  1. Array method Built-in functions that can be used on arrays.
    1. let fruits = ["apple", "banana", "orange"]; fruits.push("grape"); // Adds an element to the end fruits.pop(); // Removes the last element fruits.forEach(fruit => console.log(fruit)); // Iterates over elements
  1. String method Built-in functions that can be used on strings.
    1. let str = "Hello, World!"; console.log(str.toLowerCase()); // "hello, world!" console.log(str.split(", ")); // ["Hello", "World!"] console.log(str.length); // 13
  1. Math object An object that provides mathematical operations and constants.
    1. console.log(Math.PI); // 3.141592653589793 console.log(Math.round(4.7)); // 5 console.log(Math.random()); // Random number between 0 and 1
  1. Date object An object that represents a single moment in time.
    1. let now = new Date(); console.log(now.getFullYear()); // Current year console.log(now.getMonth()); // Current month (0-11)
  1. Return statement Used to specify the value that a function should return.
    1. function add(a, b) { return a + b; } console.log(add(5, 3)); // 8
  1. Parameter A variable in a function definition that represents an input value.
    1. function greet(name) { // 'name' is a parameter console.log("Hello, " + name); }
  1. Argument The actual value passed to a function when it is called.
    1. function greet(name) { console.log("Hello, " + name); } greet("Alice"); // "Alice" is an argument
  1. Scope The context in which variables are declared and can be accessed.
  1. Global scope Variables declared outside any function or block, accessible from anywhere in the code.
    1. let globalVar = "I'm global"; function testScope() { console.log(globalVar); // Accessible }
  1. Local scope Variables declared inside a function, only accessible within that function.
    1. function testScope() { let localVar = "I'm local"; console.log(localVar); // Accessible } // console.log(localVar); // This would cause an error
  1. Block scope Variables declared inside a block (like in an if statement or loop), only accessible within that block.
    1. if (true) { let blockVar = "I'm in a block"; console.log(blockVar); // Accessible } // console.log(blockVar); // This would cause an error
  1. Hoisting JavaScript's behavior of moving declarations to the top of their scope.
    1. console.log(x); // undefined (not an error) var x = 5; // The above is interpreted as: // var x; // console.log(x); // x = 5;
  1. Callback function A function passed as an argument to another function, to be executed later.
    1. function doSomething(callback) { console.log("Doing something"); callback(); } doSomething(() => console.log("Callback executed"));
  1. Anonymous function A function without a name, often used as an argument to other functions.
    1. let greet = function(name) { console.log("Hello, " + name); }; greet("Alice");
  1. Arrow function A concise way to write function expressions.
    1. let add = (a, b) => a + b; console.log(add(5, 3)); // 8
  1. Ternary operator A shorthand way of writing an if-else statement in one line.
    1. let age = 20; let status = age >= 18 ? "Adult" : "Minor"; console.log(status); // "Adult"
  1. Truthy and falsy values Values that are considered true or false when evaluated in a boolean context.
    1. // Falsy values: false, 0, "", null, undefined, NaN // All other values are truthy if ("hello") console.log("This will run"); if (0) console.log("This won't run");
  1. Type coercion Automatic conversion of values from one data type to another.
    1. console.log("5" + 3); // "53" (string) console.log("5" - 3); // 2 (number)
  1. Strict equality Compares values without type coercion.
    1. console.log(5 === "5"); // false console.log(5 === 5); // true
  1. Loose equality Compares values with type coercion.
    1. console.log(5 == "5"); // true console.log(5 == 5); // true
  1. DOM (Document Object Model) A programming interface for HTML and XML documents.
    1. // Accessing and modifying DOM elements document.body.style.backgroundColor = "lightblue";
  1. Event listener A function that waits for a specific event to occur.
    1. document.getElementById("myButton").addEventListener("click", function() { console.log("Button clicked!"); });
  1. Event handler A function that runs when an event occurs.
    1. function handleClick() { console.log("Button clicked!"); } document.getElementById("myButton").onclick = handleClick;
  1. querySelector() Selects the first element that matches a CSS selector.
    1. let element = document.querySelector(".myClass");
  1. getElementById() Selects an element by its ID.
    1. let element = document.getElementById("myId");
  1. createElement() Creates a new HTML element.
    1. let newDiv = document.createElement("div");
  1. appendChild() Adds a node to the end of the list of children of a specified parent node.
    1. let newP = document.createElement("p"); document.body.appendChild(newP);
  1. JSON (JavaScript Object Notation) A lightweight data interchange format.
    1. let obj = {name: "John", age: 30}; let json = JSON.stringify(obj); // Convert to JSON string let parsed = JSON.parse(json); // Parse JSON string
  1. AJAX (Asynchronous JavaScript and XML) A technique for creating fast and dynamic web pages.
    1. // Using XMLHttpRequest (old way) let xhr = new XMLHttpRequest(); xhr.open("GET", "<https://api.example.com/data>", true); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send();
  1. Fetch API A modern interface for making HTTP requests.
    1. fetch("<https://api.example.com/data>") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
  1. Promise An object representing the eventual completion or failure of an asynchronous operation.
    1. let promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Done!"), 1000); }); promise.then(result => console.log(result));
  1. Async/Await A way to write asynchronous code that looks synchronous.
    1. async function fetchData() { try { let response = await fetch("<https://api.example.com/data>"); let data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } }
  1. Try...catch statement Used to handle exceptions (errors) in code.
    1. try { // Code that might throw an error throw new Error("Oops!"); } catch (error) { console.error(error.message); }
  1. Throw statement Used to create custom errors.
    1. function divide(a, b) { if (b === 0) { throw new Error("Cannot divide by zero"); } return a / b; }
  1. Error object Represents an error when runtime error occurs.
    1. try { throw new Error("Custom error message"); } catch (error) { console.log(error.name); // "Error" console.log(error.message); // "Custom error message" }
  1. Destructuring assignment A way to unpack values from arrays or properties from objects into distinct variables.
    1. let [a, b] = [1, 2]; // Array destructuring let {x, y} = {x: 3, y: 4}; // Object destructuring
  1. Spread operator Allows an iterable to be expanded in places where zero or more arguments or elements are expected.
    1. let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
  1. Rest parameter Allows a function to accept an indefinite number of arguments as an array.
    1. function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sum(1, 2, 3, 4)); // 10
  1. Default parameter Allows parameters to have predetermined values if no value or undefined is passed.
    1. function greet(name = "Guest") { console.log(`Hello, ${name}!`); } greet(); // "Hello, Guest!" greet("Alice"); // "Hello, Alice!"
  1. Template tag function A function that can be used to modify the output of a template literal.
    1. function highlight(strings, ...values) { return strings.reduce((acc, str, i) => `${acc}${str}<span class="highlight">${values[i] || ''}</span>`, ''); } let name = "Alice"; console.log(highlight`Hello, ${name}!`); // "Hello, <span class="highlight">Alice</span>!"
  1. Map object A collection of key-value pairs where both the keys and values can be of any type.
    1. let map = new Map(); map.set("name", "John"); map.set(1, "number one"); console.log(map.get("name")); // "John"
  1. Set object A collection of unique values of any type.
    1. let set = new Set([1, 2, 3, 3, 4]); console.log(set.size); // 4 set.add(5); console.log(set.has(3)); // true
  1. Symbol A unique and immutable primitive data type.
    1. let sym1 = Symbol("description"); let sym2 = Symbol("description"); console.log(sym1 === sym2); // false
  1. Iterator An object that defines a next() method to access the next item in a collection.
    1. let arr = [1, 2, 3]; let iterator = arr[Symbol.iterator](); console.log(iterator.next().value); // 1
  1. Generator function A function that can be paused and resumed, yielding multiple values.
    1. function* numberGenerator() { yield 1; yield 2; yield 3; } let gen = numberGenerator(); console.log(gen.next().value); // 1
  1. Module A way to organize and encapsulate code.
    1. // math.js export function add(a, b) { return a + b; }
  1. Import statement Used to import bindings from other modules.
    1. import { add } from './math.js'; console.log(add(2, 3)); // 5
  1. Export statement Used to export functions, objects, or primitive values from a module.
    1. export const PI = 3.14159; export function circumference(r) { return 2 * PI * r; }
  1. Closure A function that has access to variables in its outer (enclosing) lexical scope.
    1. function outer() { let x = 10; return function inner() { console.log(x); }; } let closureFn = outer(); closureFn(); // 10
  1. Higher-order function A function that takes one or more functions as arguments or returns a function.
    1. function multiplyBy(factor) { return function(number) { return number * factor; }; } let double = multiplyBy(2); console.log(double(5)); // 10
  1. Pure function A function that always returns the same output for the same input and has no side effects.
    1. function add(a, b) { return a + b; }
  1. Recursion A technique where a function calls itself to solve a problem.
    1. function factorial(n) { if (n <= 1) return 1; return n * factorial(n - 1); } console.log(factorial(5)); // 120
  1. Memoization An optimization technique that stores the results of expensive function calls.
    1. function memoize(fn) { const cache = {}; return function(...args) { const key = JSON.stringify(args); if (key in cache) { return cache[key]; } const result = fn.apply(this, args); cache[key] = result; return result; }; }
  1. Prototype The mechanism by which JavaScript objects inherit features from one another.
    1. function Person(name) { this.name = name; } Person.prototype.greet = function() { console.log(`Hello, I'm ${this.name}`); }; let person = new Person("Alice"); person.greet(); // "Hello, I'm Alice"
  1. Inheritance A way to create a class as a child of another class.
    1. class Animal { constructor(name) { this.name = name; } } class Dog extends Animal { bark() { console.log("Woof!"); } }
  1. Class A template for creating objects, providing initial values and implementations.
    1. class Rectangle { constructor(height, width) { this.height = height; this.width = width; } area() { return this.height * this.width; } }
  1. Constructor A special method for creating and initializing objects created within a class.
    1. class Person { constructor(name) { this.name = name; } } let person = new Person("Alice");
  1. Method A function that is a property of an object or class.
    1. let person = { name: "Alice", greet() { console.log(`Hello, I'm ${this.name}`); } }; person.greet(); // "Hello, I'm Alice"
  1. Static method A method that belongs to the class itself rather than to instances of the class.
    1. class MathOperations { static square(x) { return x * x; } } console.log(MathOperations.square(5)); // 25
  1. Getter A method that gets the value of a specific property.
    1. class Circle { constructor(radius) { this._radius = radius; } get diameter() { return this._radius * 2; } } let circle = new Circle(5); console.log(circle.diameter); // 10
  1. Setter A method that sets the value of a specific property.
    1. class Circle { constructor(radius) { this._radius = radius; } set radius(value) { if (value > 0) { this._radius = value; } } } let circle = new Circle(5); circle.radius = 10;
  1. This keyword A keyword that refers to the object it belongs to.
    1. let person = { name: "Alice", greet() { console.log(`Hello, I'm ${this.name}`); } }; person.greet(); // "Hello, I'm Alice"
  1. Bind(), call(), and apply() methods Methods used to set the this value for a function.
    1. function greet(greeting) { console.log(`${greeting}, I'm ${this.name}`); } let person = { name: "Alice" }; greet.call(person, "Hi"); // "Hi, I'm Alice" greet.apply(person, ["Hello"]); // "Hello, I'm Alice" let boundGreet = greet.bind(person); boundGreet("Hey"); // "Hey, I'm Alice"
  1. Regular expression A pattern used to match character combinations in strings.
    1. let pattern = /\\d+/; console.log(pattern.test("123")); // true console.log("abc123def".match(pattern)); // ["123"]
  1. Proxy object An object that wraps another object and intercepts operations.
    1. let target = { x: 10, y: 20 }; let handler = { get: function(obj, prop) { return prop in obj ? obj[prop] : 37; } }; let proxy = new Proxy(target, handler); console.log(proxy.x); // 10 console.log(proxy.z); // 37
  1. Reflect API Provides methods for interceptable JavaScript operations.
    1. let obj = { x: 1, y: 2 }; console.log(Reflect.has(obj, 'x')); // true Reflect.set(obj, 'z', 3); console.log(obj.z); // 3
 

Conclusion

Remember, practice makes perfect, so start coding and experimenting with these concepts using DeepDev