DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-25 Understanding parseInt, NaN, isNaN, Template Literals & Concatenation in JavaScript

Hey folks!
Today, I deepened my understanding of some foundational JavaScript concepts. If you're new to JavaScript, you'll find these super helpful in your journey. Let's break them down with simple explanations and examples.


parseInt() — Convert Strings to Numbers

parseInt() is used to convert a string into an integer.

Syntax:

parseInt(string, radix)
Enter fullscreen mode Exit fullscreen mode
  • string: the value you want to convert.
  • radix: the base (optional) like 10 for decimal, 2 for binary.

Example:

let num = parseInt("42");  // returns 42
let num2 = parseInt("101", 2); // returns 5 (binary to decimal)
Enter fullscreen mode Exit fullscreen mode

It stops reading as soon as it hits a non-numeric character.

parseInt("123abc");  // returns 123
parseInt("abc123");  // returns NaN
Enter fullscreen mode Exit fullscreen mode

What is NaN?

NaN stands for Not-a-Number. It's a special value in JavaScript that means "This is not a valid number."

Example:

let result = parseInt("hello");
console.log(result); // NaN
Enter fullscreen mode Exit fullscreen mode

isNaN() — Check if a Value is NaN

Use isNaN() to check whether a value is NaN.

Example:

let value = parseInt("abc");
console.log(isNaN(value)); // true

console.log(isNaN(123));   // false
Enter fullscreen mode Exit fullscreen mode

Template Literals — Modern Way to Write Strings

Introduced in ES6, template literals make string formatting easier and more readable.

Syntax:
Use backticks (`) instead of quotes, and ${} to inject variables.

Example:

let name = "Tamil";
let age = 25;
let message = `My name is ${name} and I am ${age} years old.`;
console.log(message);
// Output: My name is Tamil and I am 25 years old.
Enter fullscreen mode Exit fullscreen mode

String Concatenation — Old but Gold

Before template literals, we combined strings using the + operator.

Example:

let name = "Tamil";
let age = 25;
let message = "My name is " + name + " and I am " + age + " years old.";
console.log(message);
Enter fullscreen mode Exit fullscreen mode

It works well, but can get messy with long strings or multiple variables.


Summary

Concept Description Example
parseInt() Converts strings to integers parseInt("123") → 123
NaN "Not-a-Number" result parseInt("abc") → NaN
isNaN() Checks if a value is NaN isNaN(parseInt("abc")) → true
Template Literals Easier string formatting `Hello, ${name}`
Concatenation Combine strings with + "Hello " + name

Final Thoughts

Understanding these basics makes working with strings and numbers in JavaScript much easier and cleaner. Whether you're formatting output or validating user input, these tools are essential.

Top comments (0)