The Core of JavaScript: Unpacking Variables, Types, and Operators

·

7 min read

The Core of JavaScript: Unpacking Variables, Types, and Operators

Introduction: Why These Building Blocks Matter

Before diving into specifics, let me tell you that these are the foundation of JavaScript for building a simple calculator, a to-do list, or a large-scale web application.
Variables allow you to store data, data types define what kind of data you’re working with, and operators allow you to manipulate and compare the data.

Mastering the core building blocks of JavaScript, such as variable declarations, data types, and operators, is the first step towards becoming a confident web developer.

Now, let’s expolore each part in details:

Variables: Storing Data in JavaScript

Variables are labeled as containers that store data, numbers, text, true, false, or complex data structures that you can use and manipulate in your code.

JavaScript provides 3 keywords to declare variables: var, let, and const. Each has unique characteristics regarding their scope and mutability.

  • var

    var is the oldest way to declare variables in JavaScript, introduced in its first version.

    Scope: It is function-scoped, meaning variables declared with varwill be accessible throughout the function or globally if declared outside the function.

    Behavior: It can be redeclared with the same name again and updated within the same scope.

    Variables are hoisted, means you can reference them before declaration, so their value will be undefined until it is assigned.

function testVar() {
  console.log(x); // Undefined, because 'x' is hoisted but not assigned yet.

  var x = 10;

  if (true) {
    var x = 20;
    console.log(x); // 20, because 'x' is now 20 after redeclaration inside the 'if' block.
  }
  console.log(x); // 20, the value of 'x' has been updated to 20 within the 'if' block, and 'var' allows this change to persist outside the block within the function.
}

testVar();

let: Flexible and Block-Scoped

  • let was introduced in ES6 in 2015. This feature has brought a new level of control over the scope of variables and how they can be manipulated.

    Scope: Block-scoped. A variable declared with let is only accessible within the block (e.g., {} of an if statement or loop) where it’s defined.

    Behavior: It can be updated but not redeclared in the same scope.

    Not hoisted in a usable way. Accessing it before declaration throws an error.

      function testLet() {
        console.log(x); // This will throw an error
        let x = 10; // Variable 'x' is declared and assigned 10
    
        if (true) {
          let x = 20; // This creates a new 'x' inside the block with the value 20
          console.log(x); // This will print 20
        }
        console.log(x); // This will print 10, as the outer 'x' remains unchanged
      }
    
      testLet();
    

    Let’s discuss why it’s throwing an ReferenceError

    The first console.log(x) will throw a ReferenceError. This happens because of hoisting and the Temporal Dead Zone (TDZ).

    let and const variables are hoisted to the top of their scope (just like var), but they are not initialized at the top. This means that while the variable is moved to the top during execution, its value is not available until the actual declaration is reached in the code.

    Temporal Dead Zone (TDZ): The Temporal Dead Zone (TDZ) is the time between when a variable is hoisted to the top and when it is actually initialized. During this period, accessing the variable will result in a ReferenceError.

const: Constants with a Twist

Also introduced in ES6, const is used to declare variables that shouldn’t be reassigned.

  • Scope: Block-scoped, like let.

  • Behavior: Cannot be reassigned or redeclared after the initial assignment.

    However, if the value is an object or array, its properties or elements can still be modified.

  •   const z = 30;
      z = 40; // Error: Assignment to constant variable
    
      const arr = [1, 2, 3];
      arr.push(4); // Allowed: [1, 2, 3, 4]
      console.log(arr);
    

    While arr can’t be reassigned to a new array, its contents can change because const only locks the binding, not the value itself. You cannot change the reference of arr, but you can modify the elements inside the array.

Data Types: What Variables Can Hold

JavaScript is a dynamically typed language, means the typed of variable is determined at runtime.

Primitive Data Types

  • String: Represents a sequence of characters.

    Example: "Hello, World!", 'JavaScript'

  • Number: Represents both integer and floating-point numbers.

    Example: 10, 3.14, -100

  • BigInt: Represents very large integers that are beyond the range of the Number type.

    Example: 9007199254740991n, 1234567890123456789012345678901234567890n

  • Boolean: Represents a logical value, either true or false.

    Example: true, false

  • undefined: A variable that has been declared but not yet assigned a value is automatically assigned the value undefined.

    Example: let x; (x is undefined until it gets assigned a value)

  • null: Represents the intentional absence of any value. It is an empty or non-existent reference.

    Example: let x = null;

  • Symbol: A unique and immutable primitive value, often used as object property keys.

    Example: let sym = Symbol('description');

  • undefined vs null:

    • undefined is automatically assigned to variables that are declared but not initialized.

    • null is used to intentionally assign "no value" to a variable, such as for clearing a variable.

Non-Primitive Data Types (Reference Types)

Reference types are more complex types. They store references to the data (rather than the actual data) and can be changed or mutated.

  • Object: A collection of key-value pairs (properties and methods). Objects can store multiple values of different types.

      let person = {
        name: "Darshan",
        age: 23,
        isStudent: true
      };
    
  • Array: A special type of object used for storing ordered collections of values. Arrays can hold values of any data type.

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

Function: Functions in JavaScript are also objects, and they are callable blocks of code that can accept parameters and return a result.

function greet() {
  console.log("Hello, Decode with Darshan!");
}
String"Hello", 'JavaScript'Sequence of characters
Number10, 3.14, -100Numeric values (integers and floats)
BigInt1234567890123456789012345678901234567890nVery large integers
Booleantrue, falseLogical values (true or false)
undefinedlet x;Variable declared but not initialized
nulllet x = null;Intentionally no value
SymbolSymbol('id')Unique identifier
Object{ name: "Alice", age: 25 }Collection of key-value pairs
Array["apple", "banana"]Ordered collection of values

Operators: Manipulating and Comparing Values

Operators are symbols that perform operations on values, categorized into arithmetic, comparison, and logical types.

Arithmetic Operators

  • +: Addition, adds two numbers or concatenates strings.

  • -: Subtraction, subtracts the second number from the first.

  • *: Multiplication, multiplies two numbers.

  • /: Division, divides the first number by the second.

  • %: Modulus, returns the remainder of division.

      let sum = 5 + 3; // 8
      let difference = 5 - 3; // 2
      let product = 5 * 3; // 15
      let quotient = 5 / 3; // approximately 1.666
      let remainder = 5 % 3; // 2
    
  • Note: The + operator also concatenates strings, e.g., "Hello, " + "World!" results in "Hello, World!".

Comparison Operators

  • ==: Equality, checks if values are equal, performing type coercion (e.g., 5 == "5" is true).

  • ===: Strict equality, checks if values and types are equal (e.g., 5 === "5" is false).

  • !=: Inequality, opposite of ==, with type coercion.

  • !==: Strict inequality, opposite of ===, no type coercion.

  • <: Less than, compares numerical or string order.

  • >: Greater than, compares numerical or string order.

  • <=: Less than or equal to.

  • >=: Greater than or equal to.

      let a = 5;
      let b = "5";
      console.log(a == b); // true (type-coercion)
      console.log(a === b); // false (different types)
      console.log(a < b); // false (numerical comparison)
    

    The difference between == and === can lead to bugs, as == may coerce types in unexpected ways, like 0 == false being true, making === safer for precise comparisons.

Logical Operators

  • &&: Logical AND, returns true if both operands are true, otherwise false. Uses short-circuiting: if the first operand is false, the second isn’t evaluated.

  • ||: Logical OR, returns true if at least one operand is true, otherwise false. Short-circuits if the first operand is true.

  • !: Logical NOT, inverts the boolean value (true to false, false to true).

      let isTrue = true;
      let isFalse = false;
      console.log(isTrue && isFalse); // false
      console.log(isTrue || isFalse); // true
      console.log(!isTrue); // false
    

Conclusion

Mastering JavaScript's core building blocks—variables, data types, and operators—is essential for web development. Variables in JavaScript can be declared using `var`, `let`, or `const`, each with unique scope and behavior characteristics. JavaScript is a dynamically typed language, featuring primitive data types such as strings, numbers, and booleans, and complex reference types like objects and arrays. Operators, divided into arithmetic, comparison, and logical categories, enable data manipulation and comparison. Understanding these foundational elements helps in creating everything from simple scripts to complex web applications.