Skip navigation

Tag Archives: type

Pass by value and pass by reference is age old concept. It is working similar way in JavaScript too. If you like to see some code so that you can understand better. Keep reading.

Brief theory before jump into code. JavaScript primitive types (string, number, boolean, null and undefined) are passed by value. Whereas non-primitive types (objects, arrays, functions, etc.) are passed by reference.

// Primitive types: Immutable by default
let x = 5
let y = x
y = 10
console.log(x) // output 5
console.log(y) // output 10

// Non-primitive types: Mutable
let animal = {
    name: 'Rat'
let anotherAnimal = animal = 'Horse'
console.log(animal) // {name: "Horse"}
console.log(anotherAnimal) // {name: "Horse"}
console.log(animal === anotherAnimal) // true

This knowledge might be useful while learning react.js, redux architecture.


I learned something interesting about JavaScript undefined. Here is the axioms and proofs.

  1. undefined is a type.
  2. undefined type has only one value. that values is undefined.
  3. There is a global variable called undefined
  4. global undefined variable has default value undefined
  5. global undefined variable is not a constant
  6. undefined is not a keyword
Proof (tested in firebug console)

1. typeof undefined \\undefined

2. undefined = 1; alert(typeof undefined !== 'undefined'); // false

3. var name = undefined;  \\ global variable undefined is assigned to name

4. alert(name); \\ undefined, that means undefined global variable has value undefined

5. undefined = 'rajakvk';  \\ we can change value

6. var undefined = 'rajakvk';  \\ no syntax error
    var if = 'rajakvk';  \\ SyntaxError: missing variable name

This gives very interesting findings and helps to understand strange JavaScript bugs.