Stupid JavaScript Question - Short Answers
25/01/2025 - Raúl Cano
You are shy to ask these questions, let's answer them as fast as junk food.
Index
What’s the difference between ?? and || ?
const nameOne = attendee.name ?? 'Unknown';
const nameTwo = attendee.name || 'Unknown';
nameOne will only be ‘Unkwon’ if attendee.name is null or undefined
nameTwo will be ‘Unknown’ if attendee.name is null, undefined, 0, false, '', NaN or []
?? is a nullish operator, it checks if the value is null or undefined only.
|| is a logical operator, it checks if the value is falsy.
What’s the difference between == and === ?
0 == '0' // true ✅
0 === '0' // false ❌
null == undefined // true ✅
null === undefined // false ❌
0 == false // true ✅
0 === false // false ❌
== compares the values, it’s a loose equality operator.
=== compares the values and the types, it’s a strict equality operator.
What’s the difference between null and undefined?
let name = null; // null
let age; // undefined
typeof null is "object" (JS bug) // amazing 🤣
typeof undefined is "undefined"
Analogy:
Empty fridge (undefined) vs fridge with no food (null)
Note: null only appears when explicitly assigned:
let user1; // undefined
let user2 = null; // null (explicitly set)
let user3 = ''; // empty string
let obj = {};
obj.name; // undefined (property doesn't exist)
What’s the difference between function and arrow function?
That one can be more messy.
// Regular function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
One of the main differences is the this keyword, arrow functions do not have their own this.
(What the hell is -> this)
Arrow functions inherit the this value from outside the function.
// Regular function
const person = {
name: 'John',
myName: function() {
console.log(`My name is ${this.name}`); // ...John
}
};
// Arrow function
const person = {
name: 'John',
myName: () => {
console.log(`My name is ${this.name}`); // ...undefined
}
};
Here we see the oposite. The regular function doesn’t have access to the this value from the outside, while the arrow function does.
const obj = {
name: "Alice",
// Regular function creates its own 'this'
sayHiRegular: function() {
setTimeout(function() {
console.log(`Hi ${this.name}`); // undefined
}, 1000)
},
// Arrow function inherits 'this' from obj
sayHiArrow: function() {
setTimeout(() => {
console.log(`Hi ${this.name}`); // "Hi Alice"
}, 1000)
}
}
It’s tricky, I still struggle with it :/