DEV Community

Anjali Gurjar
Anjali Gurjar

Posted on

JS basic question. with answer

1. Basic Data Types in JavaScript

JavaScript has seven primitive data types and one non-primitive type:

  • Primitive Types:

    1. Number – Represents both integers and floating-point numbers (e.g., 42, 3.14).
    2. String – Represents text (e.g., "Hello", 'World').
    3. Boolean – Represents true or false.
    4. Undefined – Represents a variable that has been declared but not assigned a value.
    5. Null – Represents the intentional absence of any object value.
    6. Symbol (ES6) – Represents a unique identifier.
    7. BigInt (ES11) – Represents large integers beyond Number.MAX_SAFE_INTEGER.
  • Non-Primitive Type:

    1. Object – Includes arrays, functions, dates, and user-defined objects.

2. Types of Values & Memory Diagram

JavaScript values are categorized into two types:

  • Primitive values (stored in Stack Memory)
  • Reference values (Objects) (stored in Heap Memory)

Memory Diagram:

Stack (Primitive Values)
--------------------------------
| name   | "John"  |
| age    |  30     |
| isMale |  true   |
--------------------------------

Heap (Reference Values)
--------------------------------
| obj1 -> { name: "Alice", age: 25 } |
| arr  -> [1, 2, 3, 4]               |
--------------------------------
Enter fullscreen mode Exit fullscreen mode

Primitives are stored by value in the stack, while objects are stored in the heap, and variables in the stack store references to the heap memory.


3. Heap vs Stack (Differences & Connection)

Feature Stack Heap
Definition Memory used for static data like primitives and function calls Memory used for dynamic data like objects
Access Speed Fast (Last In First Out - LIFO) Slower than stack
Storage Stores primitive values and function execution context Stores reference types (objects, arrays)
Memory Management Automatically freed when function ends Requires manual garbage collection

Connection: When a reference type (object) is stored in a variable, its address (reference) is stored in the stack, while the actual object resides in the heap.


4. Internal Property [[Class]]

  • [[Class]] is an internal property of JavaScript objects, which is used to determine the type of an object.
  • It can be accessed using Object.prototype.toString.call(value).
  console.log(Object.prototype.toString.call([]));  // [object Array]
  console.log(Object.prototype.toString.call({}));  // [object Object]
  console.log(Object.prototype.toString.call(null)); // [object Null]
Enter fullscreen mode Exit fullscreen mode

5. Built-in Objects in JavaScript

JavaScript provides several built-in objects, including:

  • Global Objects: Object, Function, Array, Boolean, Number, String, BigInt, Symbol, Date, RegExp, Error
  • Math & Utility Objects: Math, JSON
  • Typed Arrays: Int8Array, Uint8Array, Float32Array, etc.
  • Asynchronous Handling: Promise, AsyncFunction
  • DOM & BOM Objects (Browser-specific): window, document, console

6. Difference between undefined and undeclared

Feature undefined undeclared
Definition A declared variable without a value A variable that has never been declared
Example let x; console.log(x); // undefined console.log(y); // ReferenceError: y is not defined
Type undefined ReferenceError (runtime error)

7. Difference between null and undefined

Feature null undefined
Definition Represents intentional absence of value Represents an uninitialized variable
Type object undefined
Use Case Used when no value is explicitly assigned Default value for uninitialized variables
Example let x = null; let y; console.log(y); // undefined

8. How to Get a Safe undefined Value?

  1. Use void 0 to get undefined safely:
   let x = void 0;
   console.log(x); // undefined
Enter fullscreen mode Exit fullscreen mode
  1. Simply declare a variable without assigning a value:
   let y;
   console.log(y); // undefined
Enter fullscreen mode Exit fullscreen mode
  1. Use typeof check to avoid errors:
   if (typeof someVariable === "undefined") {
       console.log("Variable is undefined");
   }
Enter fullscreen mode Exit fullscreen mode

9. Basic Rules for Writing JavaScript

  1. Use let and const instead of var
    • let and const provide block-scoped variables and prevent hoisting issues.
   let name = "John";
   const age = 30;
Enter fullscreen mode Exit fullscreen mode
  1. Use Strict Mode ("use strict")
    • Helps catch errors early by preventing the use of undeclared variables.
   "use strict";
   let x = 10;  // Correct
   y = 20;  // Error: y is not defined
Enter fullscreen mode Exit fullscreen mode
  1. Always use === instead of ==
    • Avoids type coercion issues.
   console.log(1 == "1");  // true (bad)
   console.log(1 === "1"); // false (good)
Enter fullscreen mode Exit fullscreen mode
  1. Avoid Global Variables

    • Always declare variables inside functions or modules to prevent global scope pollution.
  2. Use Template Literals for String Concatenation

   let name = "Alice";
   console.log(`Hello, ${name}!`); // Good
Enter fullscreen mode Exit fullscreen mode
  1. Use Arrow Functions (=>) for Shorter Syntax
   const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode
  1. Handle Errors with try...catch
   try {
       let result = someUndefinedFunction();
   } catch (error) {
       console.error("An error occurred:", error);
   }
Enter fullscreen mode Exit fullscreen mode
  1. Use Destructuring for Cleaner Code
   const user = { name: "John", age: 25 };
   const { name, age } = user;
Enter fullscreen mode Exit fullscreen mode
  1. Use Default Parameters in Functions
   function greet(name = "Guest") {
       console.log(`Hello, ${name}`);
   }
Enter fullscreen mode Exit fullscreen mode
  1. Optimize Loops with forEach, map, filter
   const numbers = [1, 2, 3];
   numbers.map(num => num * 2); // [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)