const abc = 5;
const bcd = 5
console.log(abc===bcd)/// return true
This result is surprising to me.
Since abc will be assigned a different memory location ...and bcd has also a different location
why this is returning true
If the code was
const abc = 5
const bcd = abc
console.log(abc === bcd) ///true here make sense
I seem to be be really confused with the first case since abc and bcd are two different variables and have no relation between them
Any related article or blog would really help.
In javascript all primitives (string, nubmer, bigint, boolean, undefined, symbol, null) are immutable and will be compared by value:
All primitives are immutable, i.e., they cannot be altered. It is important not to confuse a primitive itself with a variable assigned a primitive value. The variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered.
In comparison to that objects (this also includes arrays and functions, basically everything that is not a primitive) are mutable and will be compared by identity.
Example:
console.log("Primitives compare by value:");
console.log(5 === 5); // true
console.log("foo" === "foo"); // true
console.log(true === true); // true
console.log("Objects compare by identity:");
console.log({} === {}); // false
console.log([] === []); // false
console.log(function(){} === function(){}); // false
Javascript also has wrapper objects for the primitive types, which might be the source of your question.
These wrappers wrap a primitive value, and are - as the name suggests - objects. So for primitive wrapper instances your code would be correct:
let a = new Number(1);
let b = new Number(1);
console.log("Primitive wrappers are objects:");
console.log(a === a); // true
console.log(a === b); // false
There is a fundamental difference in JavaScript between primitive values (undefined,null, booleans, numbers, and strings) and objects (including arrays and functions)
I. Primitives are compared by value:
II. Objects are different than primitives.
Objects are not compared by value: Two distinct objects are not equal even if they have the same properties and values.
Therefore, Objects are sometimes called reference types to distinguish them from JavaScript’s primitive types.