JavaScript is a dynamically typed language. Being loosely typed, a variable is literally just a name for a particular value at a particular time. Because there are no rules defining the type of data that a variable must hold, a variable’s value and data type can change during the lifetime of a script.
ECMAScript variables may contain two different types of data: primitive values and reference values. Primitive values are simple atomic pieces of data, while reference values are objects that may be made up of multiple values. The first are said to be accessed by value, while the second
let person = new Object();
person.name = "Nicholas"; // add
person.name = 'Tom'; // change
delete person.name; // delete
let name = "Nicholas";
name.age = 27; // will throw error in strict mode
console.log(name.age); // undefined
new
keyword, JavaScript will create an Object type, but one that behaves like a primitive.
let name1 = "Nicholas";
let name2 = new String("Nicholas");
let name3 = "Nicholas";
name1.age = 27;
name2.age = 26;
console.log(name1.age); // undefined
console.log(name2.age); // 26
console.log(typeof name1); // string
console.log(typeof name2); // object
console.log(name1 === name2); // false
console.log(name1 === name3); // true
All function arguments in ECMAScript are passed by value. If the value is primitive, then it acts just like a primitive variable copy, and if the value is a reference, it acts just like a reference variable copy.
When an argument is passed by value, the value is copied into a local variable (a named argument and, in ECMAScript, a slot in the arguments
object).
typeof
is the best way to determine if a variable is a primitive type. For objects, there are two special cases:
[[Call]]
method should return “function” from typeof
. Since regular expressions implement this method in these browsers, typeof returns “function”.null
, then it returns “object”.instanceof
operator to know what type of object it is.Reference: