← कोर्स पर वापस जाएँ: JavaScript from scratch

Conversions, strict comparison and review

वीडियो जल्द आ रहा है

JavaScript is a dynamically typed language: a variable can hold a number today and a text tomorrow, and the engine converts types automatically when it thinks it is necessary. That automatic conversion is called coercion and it is one of the biggest sources of surprises for beginners. In this lesson you will learn to convert types explicitly and to compare values without traps.

Explicit conversion

To turn a text into a number use Number(), parseInt() or parseFloat(). Number is strict: if the text contains anything that is not numeric, it returns NaN. parseInt and parseFloat read the beginning of the text and stop when they find something they do not understand. To convert to text use String() or the toString() method, and to convert to boolean use Boolean(). This matters a lot with forms, because everything a user types arrives as text.

javascript
console.log(Number('42'));       // 42
console.log(Number('42px'));     // NaN
console.log(parseInt('42px'));   // 42
console.log(parseFloat('3.5kg')); // 3.5
console.log(Number(''));         // 0 (surprise!)
console.log(Number(true));       // 1
console.log(String(123) + 1);    // '1231'
console.log('5' + 3);            // '53' (the + joins text)
console.log('5' - 3);            // 2   (the - converts to number)
console.log(Boolean('hello'));   // true

Truthy and falsy values

When a value is used where a boolean is expected, for example in an if, JavaScript converts it. There are only eight falsy values: false, 0, -0, 0n, '' (empty text), null, undefined and NaN. Everything else is truthy, even the text '0', the text 'false', an empty array [] and an empty object {}. If you remember that short list, you will always know what is going to happen.

=== versus ==

The == operator compares after converting types and produces results that are hard to remember, like 0 == '' (true) or null == undefined (true). The === operator compares value and type without converting anything, and that is why it is the one you should always use. The same goes for !== versus !=. There is one special case: NaN is not equal even to itself, so to detect it use Number.isNaN().

javascript
console.log(5 == '5');   // true  (coercion)
console.log(5 === '5');  // false (different types)
console.log(0 == '');    // true
console.log(0 === '');   // false
console.log(null == undefined);  // true
console.log(null === undefined); // false
console.log(NaN === NaN);        // false
console.log(Number.isNaN(NaN));  // true

const raw = ' 25 ';
const age = Number(raw.trim());
console.log(age + 1); // 26, not '25 1'

Validating input data step by step

A pattern you will use in almost all your projects is to receive a text, convert it and check that the result makes sense before using it. The order matters: first the text is cleaned with trim, then it is converted with Number and finally it is checked with Number.isNaN and with business rules, such as the age being between 0 and 120. If the text is empty, Number returns 0, so it is wise to check for the empty string before converting. This small discipline prevents hard-to-find errors later and prepares you to work with forms in week 7.

javascript
function parseAge(input) {
  const text = input.trim();
  if (text === '') return null;       // empty: do not convert
  const age = Number(text);
  if (Number.isNaN(age)) return null; // not a number
  if (age < 0 || age > 120) return null;
  return age;
}

console.log(parseAge(' 25 '));  // 25
console.log(parseAge(''));      // null
console.log(parseAge('abc'));   // null
console.log(parseAge('200'));   // null

जो सीखा उसे परखें

प्रश्न 1 / 7

What does '5' + 3 give?

✎ मेरे नोट्स

केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर

← पिछलाअगला →