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)
-
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)
It stops reading as soon as it hits a non-numeric character.
parseInt("123abc"); // returns 123
parseInt("abc123"); // returns NaN
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
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
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.
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);
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)