0% found this document useful (0 votes)
2 views

CoreJavascriptPart2

The document explains the concept of Boolean in JavaScript, detailing primitive boolean values, the Boolean() function, and the new Boolean() constructor. It highlights the differences between truthy and falsy values, emphasizing that the Boolean() function converts values to primitive booleans while the constructor creates Boolean objects that are always truthy. Additionally, it covers string creation, manipulation, and concatenation methods in JavaScript, including the use of template literals for easier string handling.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CoreJavascriptPart2

The document explains the concept of Boolean in JavaScript, detailing primitive boolean values, the Boolean() function, and the new Boolean() constructor. It highlights the differences between truthy and falsy values, emphasizing that the Boolean() function converts values to primitive booleans while the constructor creates Boolean objects that are always truthy. Additionally, it covers string creation, manipulation, and concatenation methods in JavaScript, including the use of template literals for easier string handling.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Core Javascript 02

Boolean()
You're absolutely correct! Let's break down the concept of Boolean in
JavaScript, including its primitive values, the Boolean() function, the Boolean

constructor, and how certain values are evaluated as true or false .

1. Primitive Boolean Values


In JavaScript, the primitive boolean data type can have one of two values: true

or false . These are used to represent logical conditions.

Example:

var primitiveTrue = true;


var primitiveFalse = false;

console.log(primitiveTrue); // Output: true


console.log(primitiveFalse); // Output: false

Here, primitiveTrue is a primitive boolean with the value true , and primitiveFalse is
a primitive boolean with the value false .

2. Boolean Function ( Boolean() )


The Boolean() function is used to convert a value to a boolean. It returns true for
"truthy" values and false for "falsy" values.

Example:

var functionTrue = Boolean(true);


var functionFalse = Boolean(false);

console.log(functionTrue); // Output: true


console.log(functionFalse); // Output: false

In this example, Boolean(true) returns true , and Boolean(false) returns false .

Core Javascript 02 1
Falsy Values:
Certain values are considered "falsy" in JavaScript, meaning they will be
converted to false when passed to the Boolean() function. These include:

null

false

NaN

undefined

"" (empty string)

Example:

console.log(Boolean(0)); // Output: false


console.log(Boolean(-0)); // Output: false
console.log(Boolean(null)); // Output: false
console.log(Boolean(NaN)); // Output: false
console.log(Boolean(undefined)); // Output: false
console.log(Boolean("")); // Output: false

Truthy Values:
Any value that is not "falsy" is considered "truthy," meaning it will be converted
to true when passed to the Boolean() function.

Example:

console.log(Boolean(1)); // Output: true


console.log(Boolean("Hello")); // Output: true
console.log(Boolean([])); // Output: true (empty array is truthy)
console.log(Boolean({})); // Output: true (empty object is truthy)

3. Boolean Constructor ( new Boolean() )

Core Javascript 02 2
The constructor creates a Boolean object. However, using the new
Boolean

Boolean() constructor is generally not recommended because it creates an object

wrapper around the boolean value, which can lead to unexpected behavior.

Example:

var constructorTrue = new Boolean(true);


var constructorFalse = new Boolean(false);

console.log(constructorTrue); // Output: [Boolean: true]


console.log(constructorFalse); // Output: [Boolean: false]

Here, constructorTrue and constructorFalse are objects, not primitive boolean


values. This can cause issues when comparing them to primitive booleans.

Important Note:
When you use the Boolean constructor with new , it creates an object, not a
primitive boolean. This means that even if the value is true , the object itself is
always "truthy."

Example:

var objTrue = new Boolean(true);


var objFalse = new Boolean(false);

if (objTrue) {
console.log("This will always run because objTrue is an object.");
}

if (objFalse) {
console.log("This will also run because objFalse is an object.");
}

Even though objFalse represents false , it is still an object, so it evaluates as


"truthy" in a conditional statement.

4. Implicit Conversion to Boolean

Core Javascript 02 3
JavaScript automatically converts values to booleans in certain contexts, such
as in if statements or with logical operators ( && , || ). This is called implicit
conversion.

Example:

if (0) {
console.log("This won't run because 0 is falsy.");
} else {
console.log("0 is falsy."); // Output: 0 is falsy.
}

if ("Hello") {
console.log("This will run because non-empty strings are truthy."); // Out
put: This will run...
}

5. Special Cases
Here are some special cases where certain values are evaluated as true or
false :

Empty Array ( [] ) and Empty Object ( {} ): Both are considered truthy.

console.log(Boolean([])); // Output: true


console.log(Boolean({})); // Output: true

String with Spaces: A string containing only spaces is truthy because it is


not empty.

console.log(Boolean(" ")); // Output: true

Negative Numbers: Negative numbers are truthy because they are not 0 .

console.log(Boolean(-1)); // Output: true

Practice Question for Interview

Core Javascript 02 4
Q: What is the difference between using the Boolean() function and the new

Boolean() constructor in JavaScript?

Answer:

The Boolean() function converts a value to a primitive boolean ( true or false ).

The new Boolean() constructor creates a Boolean object that wraps around
the boolean value. However, this object is always "truthy" in conditional
statements, even if it represents false .

Example:

let primitiveBool = Boolean(false);


let objectBool = new Boolean(false);

console.log(primitiveBool); // Output: false


console.log(objectBool); // Output: [Boolean: false]

if (primitiveBool) {
console.log("This won't run because primitiveBool is false.");
} else {
console.log("primitiveBool is false."); // Output: primitiveBool is false.
}

if (objectBool) {
console.log("This will run because objectBool is an object."); // Output: T
his will run...
}

Summary
Primitive Booleans: Represented by true or false .

Boolean() Function: Converts a value to a primitive boolean ( true or false ).

Constructor: Creates a Boolean object, which is generally not


new Boolean()

recommended because it behaves differently in conditional statements.

Falsy Values: 0 , 0 , null , false , NaN , undefined , "" (empty string).

Truthy Values: Any value that is not falsy is truthy.

Core Javascript 02 5
By understanding how booleans work in JavaScript, you'll be able to handle
logical conditions and evaluate expressions more effectively! 😊

In JavaScript, strings can be created and manipulated in various ways. Let's


break down the different methods and syntax you've provided:

1. Primitive Strings
Primitive strings are immutable sequences of characters. They can be created
using single quotes ( ' ), double quotes ( " ), or backticks ( ` ).

var str1 = "Hello GeekyShows"; // Double quotes


var str2 = 'Hello GeekyShows'; // Single quotes
var str3 = `Hello GeekyShows`; // Backticks (Template literals)

Double Quotes ( " ) and Single Quotes ( ' ): These are the most common
ways to define strings. Both are functionally identical.

Backticks ( ` ): Introduced in ES6, backticks allow for template literals,


which enable multi-line strings and string interpolation.

2. String Constructor
You can also create a string using the String constructor with the new keyword.
This creates a String object rather than a primitive string.

var str4 = new String("Hello GeekyShows"); // Using double quotes


var str5 = new String('Hello GeekyShows'); // Using single quotes
var str6 = new String(`Hello GeekyShows`); // Using backticks

Note: When you use the new String() constructor, it creates a String object,
not a primitive string. This is generally not recommended unless you have a
specific reason to use an object instead of a primitive.

3. Accessing Strings

Core Javascript 02 6
You can access and display strings in various ways using document.write() or other
methods.

a) Directly Writing Strings

document.write("Hello GeekyShows");
document.write('Hello GeekyShows');
document.write(`Hello GeekyShows`);

All three methods will output the same result: Hello GeekyShows .

b) Using Variables

var str = "Hello GeekyShows";


document.write(str);

var strObj = new String("Hello GeekyShows");


document.write(strObj);

Both str (primitive) and strObj (object) will output the same result: Hello

GeekyShows .

4. Escaping Characters
Sometimes you need to include quotes inside a string. You can escape them
using a backslash ( \\ ).

document.write("Hello \\"GeekyShows\\" World"); // Output: Hello "GeekyS


hows" World
document.write('Hello \\'GeekyShows\\' World'); // Output: Hello 'GeekySh
ows' World

document.write('Hello "World" GeekyShows'); // Output: Hello "World" G


eekyShows
document.write("Hello 'World' GeekyShows"); // Output: Hello 'World' Ge
ekyShows

Double Quotes Inside Double Quotes: You need to escape the inner quotes
using \\" .

Core Javascript 02 7
Single Quotes Inside Single Quotes: You need to escape the inner quotes
using \\' .

Mixing Quotes: If you use double quotes for the outer string, you can freely
use single quotes inside without escaping, and vice versa.

5. Template Literals (Backticks)


Template literals allow for multi-line strings and string interpolation.

var name = "GeekyShows";


var greeting = `Hello ${name}! Welcome to the world of JavaScript.`;

document.write(greeting); // Output: Hello GeekyShows! Welcome to the w


orld of JavaScript.

String Interpolation: You can embed variables or expressions inside a


string using ${} .

Multi-line Strings: Template literals allow you to write strings across


multiple lines without needing special characters like \\n .

Summary of Key Points:


1. Primitive Strings:

Created using " , ' , or ` .

Immutable and lightweight.

2. String Objects:

Created using new String() .

Rarely used; prefer primitives unless necessary.

3. Escaping Characters:

Use \\ to escape quotes inside strings.

Mixing quotes avoids the need for escaping.

4. Template Literals:

Allow for multi-line strings and string interpolation.

Very useful for dynamic content.

Core Javascript 02 8
Example Code:

// Primitive strings
var str1 = "Hello GeekyShows";
var str2 = 'Hello GeekyShows';
var str3 = `Hello GeekyShows`;

// String objects
var strObj1 = new String("Hello GeekyShows");
var strObj2 = new String('Hello GeekyShows');
var strObj3 = new String(`Hello GeekyShows`);

// Writing strings
document.write("Hello GeekyShows<br>");
document.write('Hello GeekyShows<br>');
document.write(`Hello GeekyShows<br>`);

// Escaping quotes
document.write("Hello \\"GeekyShows\\" World<br>");
document.write('Hello \\'GeekyShows\\' World<br>');

// Template literals with interpolation


var name = "GeekyShows";
var greeting = `Hello ${name}! Welcome to the world of JavaScript.`;
document.write(greeting);

This code demonstrates the different ways to create and manipulate strings in
JavaScript.

In JavaScript, string concatenation refers to the process of combining two or


more strings into a single string. There are several ways to concatenate strings
in JavaScript, including using the + operator and the concat() method.

1. String Concatenation Using the + Operator

Core Javascript 02 9
The + operator is the most common way to concatenate strings in JavaScript.
It allows you to combine multiple strings together.

Example:

var str1 = "Hello";


var str2 = "GeekyShows";

// Concatenating two variables


document.write(str1 + str2); // Output: HelloGeekyShows

// Concatenating a variable with a string literal


document.write(str1 + " GeekyShows"); // Output: Hello GeekyShows

// Concatenating multiple strings


document.write(str1 + " Something " + str2); // Output: Hello Something Ge
ekyShows

Note: When using the + operator, if there is no space between the strings,
they will be concatenated without any space. You can add spaces manually
by including them in quotes ( " " ).

2. Using the concat() Method


The concat() method is another way to concatenate strings. It accepts any
number of arguments and returns a new string that is the result of
concatenating the arguments to the original string.

Syntax:

string.concat(string1, string2, ..., string_n);

Example:

var str1 = "Hello";


var str2 = "GeekyShows";

// Concatenating two strings using concat()


var new_str = str1.concat(str2);

Core Javascript 02 10
document.write(new_str); // Output: HelloGeekyShows

// Concatenating multiple strings using concat()


var new_str2 = str1.concat(" Something ", str2);
document.write(new_str2); // Output: Hello Something GeekyShows

// Concatenating multiple strings directly


var result = "Hello".concat(" Something ", "GeekyShows");
document.write(result); // Output: Hello Something GeekyShows

Note: The concat() method does not modify the original string; it returns a
new concatenated string.

3. Key Differences Between + and concat()


Feature + Operator concat() Method

Syntax str1 + str2 str1.concat(str2)

Generally faster and more Slightly slower, less commonly


Performance
commonly used used

Can concatenate strings and


Flexibility Only works with strings
numbers

Returns a new concatenated


Return Value Returns a new concatenated string
string

4. Common Use Cases

a) Concatenating Variables and Strings

var firstName = "John";


var lastName = "Doe";

// Using + operator
document.write(firstName + " " + lastName); // Output: John Doe

// Using concat() method


document.write(firstName.concat(" ", lastName)); // Output: John Doe

b) Concatenating Multiple Strings

Core Javascript 02 11
var greeting = "Hello";
var name = "GeekyShows";

// Using + operator
document.write(greeting + " " + name + "! Welcome!"); // Output: Hello Ge
ekyShows! Welcome!

// Using concat() method


document.write(greeting.concat(" ", name, "! Welcome!")); // Output: Hello
GeekyShows! Welcome!

c) Concatenating Numbers and Strings


When concatenating numbers and strings, JavaScript automatically converts
the numbers to strings.

var num = 42;


var str = "The answer is ";

// Using + operator
document.write(str + num); // Output: The answer is 42

// Using concat() method


document.write(str.concat(num)); // Output: The answer is 42

5. Template Literals (Backticks) for Concatenation


Another modern way to concatenate strings is by using template literals
(introduced in ES6). Template literals allow you to embed expressions inside
backticks ( ` ) using ${} .

Example:

var firstName = "John";


var lastName = "Doe";

// Using template literals

Core Javascript 02 12
var fullName = `Full Name: ${firstName} ${lastName}`;
document.write(fullName); // Output: Full Name: John Doe

Advantages of Template Literals:

Easier to read and write, especially when dealing with multiple


variables.

Automatically handles spaces and line breaks.

Summary of Key Points:


1. + Operator:

Most common and efficient way to concatenate strings.

Can concatenate strings and numbers.

2. concat() Method:

Accepts multiple arguments and returns a new concatenated string.

Less commonly used compared to the + operator.

3. Template Literals:

Introduced in ES6.

Allow for easy embedding of variables and expressions using ${} .

Handle multi-line strings and automatic spacing.

Example Code:

// Using + operator
var str1 = "Hello";
var str2 = "GeekyShows";
document.write(str1 + " " + str2 + "<br>"); // Output: Hello GeekyShows

// Using concat() method


var new_str = str1.concat(" ", str2);
document.write(new_str + "<br>"); // Output: Hello GeekyShows

// Using template literals

Core Javascript 02 13
var greeting = `Welcome to ${str2}!`;
document.write(greeting); // Output: Welcome to GeekyShows!

This code demonstrates the different methods of string concatenation in


JavaScript, including the + operator, concat() method, and template literals.

Numbers

Let's break down the concept of Numbers in JavaScript, including their


primitive and object representations, as well as how to work with them.

1. Primitive Numbers
In JavaScript, numbers are represented as primitive values. These can be
integers (whole numbers) or floating-point numbers (decimals). JavaScript
uses double-precision 64-bit floating-point format (as per the IEEE 754
standard) to represent all numbers, whether they are integers or decimals.

Examples of Primitive Numbers:

var a = 10; // Whole Number (Integer)


var b = 10.45; // Decimal Number (Floating Point)
var c = 5e3; // Exponential Notation: 5 x 10^3 = 5000
var d = 34e-5; // Exponential Notation: 34 x 10^-5 = 0.00034

5e3 means 5 × 10³, which equals 5000.

34e-5 means 34 × 10⁻⁵, which equals 0.00034.

2. Number Object
JavaScript also provides a Number object that wraps around primitive numbers.
This is created using the new Number() constructor. However, it's important to

Core Javascript 02 14
note that using the Number constructor creates an object, not a primitive
number.

Example of Using the Number Constructor:

var a = new Number(10); // Creates a Number object for 10


var b = new Number(10.45); // Creates a Number object for 10.45
var c = new Number(5e3); // Creates a Number object for 5000

While this creates a Number object, it's generally not recommended to use
the new Number() constructor because it creates an object wrapper around
the number, which can lead to unexpected behavior when comparing
values.

3. Accessing and Displaying Numbers


You can access and display numbers using various methods, such as
document.write() , console.log() , or directly embedding them in HTML.

Example:

var a = 10;
var b = 10.45;
var c = 5e3;
var d = new Number(10);

document.write(a); // Output: 10
document.write(b); // Output: 10.45
document.write(c); // Output: 5000
document.write(d); // Output: 10 (but it's a Number object)

In the case of d , even though it represents the number 10 , it is a Number


object, not a primitive number.

4. Differences Between Primitive Numbers and Number


Objects
There are key differences between primitive numbers and Number objects:

1. Primitive Numbers:

Core Javascript 02 15
These are simple numeric values like 10 , 10.45 , etc.

They are lightweight and efficient.

Comparisons between primitive numbers work as expected.

var a = 10;
var b = 10;

console.log(a === b); // Output: true

2. Number Objects:

These are created using the new Number() constructor.

They are objects, not primitive values.

Comparisons between Number objects do not work as expected


because objects are compared by reference, not by value.

var a = new Number(10);


var b = new Number(10);

console.log(a === b); // Output: false (because they are different objec
ts)

5. Special Number Values


JavaScript has some special number values that you should be aware of:

1. NaN (Not-a-Number):

Represents an invalid number.

Often returned when a mathematical operation fails (e.g., dividing zero


by zero).

var result = 0 / 0;
console.log(result); // Output: NaN

2. Infinity :

Represents positive infinity.

Core Javascript 02 16
Occurs when a number exceeds the largest possible value in
JavaScript.

var largeNumber = 1 / 0;
console.log(largeNumber); // Output: Infinity

3. Infinity :

Represents negative infinity.

Occurs when a number goes below the smallest possible value.

var smallNumber = -1 / 0;
console.log(smallNumber); // Output: -Infinity

6. Number Methods
The Number object provides several useful methods for working with numbers:

1. toFixed(digits) :

Formats a number to a fixed number of decimal places.

var num = 10.4567;


console.log(num.toFixed(2)); // Output: "10.46"

2. toPrecision(precision) :

Formats a number to a specified precision (total number of digits).

var num = 10.4567;


console.log(num.toPrecision(4)); // Output: "10.46"

3. toString(base) :

Converts a number to a string, optionally in a specified base (e.g.,


binary, hexadecimal).

var num = 10;


console.log(num.toString(2)); // Output: "1010" (binary representation)

Core Javascript 02 17
console.log(num.toString(16)); // Output: "a" (hexadecimal representati
on)

4. Number.isNaN(value) :

Checks if a value is NaN .

console.log(Number.isNaN(NaN)); // Output: true


console.log(Number.isNaN(10)); // Output: false

5. Number.isFinite(value) :

Checks if a value is a finite number (not Infinity or Infinity ).

console.log(Number.isFinite(10)); // Output: true


console.log(Number.isFinite(Infinity)); // Output: false

Practice Question for Interview


Q: What is the difference between primitive numbers and Number objects in
JavaScript?
Answer:

Primitive Numbers: These are simple numeric values like 10 , 10.45 , etc.
They are lightweight and efficient. Comparisons between primitive numbers
work as expected.

var a = 10;
var b = 10;
console.log(a === b); // Output: true

Number Objects: These are created using the new Number() constructor. They
are objects, not primitive values. Comparisons between Number objects do
not work as expected because objects are compared by reference, not by
value.

var a = new Number(10);


var b = new Number(10);

Core Javascript 02 18
console.log(a === b); // Output: false (because they are different objec
ts)

Summary
Primitive Numbers: Simple numeric values (integers or floating-point
numbers) stored as double-precision 64-bit floating-point numbers.

Number Objects: Created using the new Number() constructor, but generally
not recommended because they behave differently in comparisons.

Special Values: NaN , Infinity , and Infinity are special number values in
JavaScript.

Number Methods: Useful methods like toFixed() , toPrecision() , and toString()

allow you to format and convert numbers.

By understanding how numbers work in JavaScript, you'll be able to handle


numeric data effectively in your programs! 😊

combine numbers and strings | Type


Coercion | +
In JavaScript, when you combine numbers and strings, the behavior depends
on the operator being used. Let's break down the examples you provided to
understand how JavaScript handles these operations.

Key Concept: Type Coercion


JavaScript automatically converts between types (e.g., numbers to strings or
vice versa) based on the context. This is called type coercion. The + operator
behaves differently depending on whether it's used with numbers or strings:

1. If one operand is a string: The + operator performs string concatenation.

2. If both operands are numbers: The + operator performs addition.

3. Other arithmetic operators ( , , / , etc.): These always perform arithmetic


operations, even if one operand is a string (as long as the string can be

Core Javascript 02 19
converted to a number).

Examples Explained

Example 1: a + b

var a = "50"; // String


var b = 10; // Number

document.write(a + b); // Output: "5010"

Here, a is a string ( "50" ) and b is a number ( 10 ).

Since one operand ( a ) is a string, the + operator performs string


concatenation.

The result is "50" + "10" (converted to a string), which gives "5010" .

Example 2: a - b

var a = "50"; // String


var b = 10; // Number

document.write(a - b); // Output: 40

The operator always performs arithmetic subtraction.

JavaScript automatically converts the string "50" to the number 50

because arithmetic operations require numbers.

The result is 50 - 10 , which equals 40 .

Example 3: b + c + a

var b = 10; // Number


var c = 20; // Number
var a = "50"; // String

document.write(b + c + a); // Output: "3050"

Core Javascript 02 20
First, b+c is evaluated. Since both b and c are numbers, their sum is 10 +

20 = 30 .

Next, 30 + a is evaluated. Since a is a string ( "50" ), the + operator


performs string concatenation.

The result is "30" + "50" , which gives "3050" .

Example 4: a + b + c

var a = "50"; // String


var b = 10; // Number
var c = 20; // Number

document.write(a + b + c); // Output: "501020"

First, a + b is evaluated. Since a is a string ( "50" ), the + operator performs


string concatenation.

The result of a+b is "50" + "10" (converted to a string), which gives "5010" .

Next, "5010" + c is evaluated. Since "5010" is a string, the + operator again


performs string concatenation.

The result is "5010" + "20" , which gives "501020" .

Example 5: var x = "Result: " + b + c

var b = 10; // Number


var c = 20; // Number

var x = "Result: " + b + c;


document.write(x); // Output: "Result: 1020"

First, "Result: " + b is evaluated. Since "Result: " is a string, the + operator
performs string concatenation.

The result of "Result: " + b is "Result: 10" .

Next, "Result: 10" + c is evaluated. Again, since "Result: 10" is a string, the +

operator performs string concatenation.

Core Javascript 02 21
The result is "Result: 10" + "20" , which gives "Result: 1020" .

Key Takeaways
1. + Operator:

If one operand is a string, the + operator performs string


concatenation.

If both operands are numbers, the + operator performs addition.

2. Other Arithmetic Operators ( , , / , etc.):

These always perform arithmetic operations, even if one operand is a


string (as long as the string can be converted to a number).

3. Order Matters:

The order in which operations are performed affects the result. For
example:

"50" + 10 + 20 results in "501020" .

10 + 20 + "50" results in "3050" .

4. Type Conversion:

JavaScript automatically converts strings to numbers for arithmetic


operations like , , / .

However, for + , if one operand is a string, the other operand is also


converted to a string.

Practice Question for Interview


Q: What will be the output of the following code?

var a = "10";
var b = 20;
var c = "30";

console.log(a + b + c);
console.log(b + c + a);
console.log(a - b);
console.log(b - c);

Core Javascript 02 22
Answer:

1. console.log(a + b + c);

"10" + 20 + "30" → "1020" + "30" → "102030"

Output: "102030"

2. console.log(b + c + a);

20 + "30" + "10" → "2030" + "10" → "203010"

Output: "203010"

3. console.log(a - b);

"10" - 20 → 10 - 20 → 10

Output: 10

4. console.log(b - c);

20 - "30" → 20 - 30 → 10

Output: 10

Summary
When combining numbers and strings in JavaScript, the behavior depends
on the operator and the order of operations.

The + operator performs string concatenation if one operand is a string.

Other arithmetic operators ( , , / , etc.) always perform arithmetic


operations, converting strings to numbers if possible.

Understanding type coercion is crucial for predicting the outcome of such


operations.

By mastering how JavaScript handles numbers and strings, you'll be able to


write more predictable and bug-free code! 😊

NaN stands for "Not-a-Number

Core Javascript 02 23
NaN stands for "Not-a-Number" in JavaScript. It is a special value that
represents an undefined or unrepresentable number. NaN is returned by
operations that result in an undefined or unrepresentable value, such as
dividing zero by zero or attempting to convert a non-numeric string to a
number.

Key Points about NaN


1. Type: NaN is of type Number .

2. Comparison: NaN is not equal to itself ( NaN !== NaN ).

3. Detection: You can use the isNaN() function to check if a value is NaN .

Examples

1. Basic Example

console.log(NaN); // Output: NaN

2. Arithmetic Operations

console.log(0 / 0); // Output: NaN


console.log(Math.sqrt(-1)); // Output: NaN

3. Converting Non-Numeric Strings

console.log(Number("abc")); // Output: NaN


console.log(parseInt("abc")); // Output: NaN

4. Checking for NaN

console.log(isNaN(NaN)); // Output: true


console.log(isNaN("abc")); // Output: true
console.log(isNaN(5)); // Output: false

Important Notes

Core Javascript 02 24
Function: The isNaN function checks if a value is
isNaN NaN or if it is a non-
numeric value that cannot be converted to a number.

Function: The Number.isNaN function is a more reliable way to


Number.isNaN

check if a value is NaN , as it only returns true for the actual NaN value.

console.log(Number.isNaN(NaN)); // Output: true


console.log(Number.isNaN("abc")); // Output: false
console.log(Number.isNaN(5)); // Output: false

Example of NaN in Practice

function divide(a, b) {
if (b === 0) {
return NaN; // Return NaN if the divisor is zero
}
return a / b;
}

console.log(divide(10, 2)); // Output: 5


console.log(divide(10, 0)); // Output: NaN

Summary
NaN : Represents an undefined or unrepresentable number.

Type: NaN is of type Number .

Comparison: NaN is not equal to itself.

Detection: Use isNaN() or Number.isNaN() to check for NaN .

Understanding NaN is important for handling edge cases in numerical


operations and ensuring that your code behaves correctly when dealing with
undefined or unrepresentable values.

Core Javascript 02 25
Certainly! Here's a focused explanation on the global isNaN() function in
JavaScript:

Global isNaN() Function


The global isNaN() function is used to determine whether a value is NaN (Not-a-
Number) or a value that cannot be converted to a number. This function
converts the tested value to a number before performing the check.

Syntax

isNaN(value)

Key Points
1. Purpose: Determines whether a value is NaN or cannot be converted to a
number.

2. Return Value: Returns true if the value is NaN or cannot be converted to a


number; otherwise, it returns false .

3. Conversion: The global isNaN() function converts the tested value to a


number before testing it.

Examples

1. Basic Example

console.log(isNaN(NaN)); // Output: true


console.log(isNaN(123)); // Output: false

2. Converting Non-Numeric Strings

console.log(isNaN("abc")); // Output: true


console.log(isNaN("123")); // Output: false (because "123" can be converte
d to a number)

3. Checking Different Data Types

Core Javascript 02 26
console.log(isNaN(undefined)); // Output: true
console.log(isNaN(null)); // Output: false (because null is converted to 0)
console.log(isNaN("")); // Output: false (because an empty string is convert
ed to 0)

Explanation
Global isNaN() :

Converts the value to a number before testing.

Returns true if the converted value is NaN .

Returns false if the converted value is a valid number.

Summary
Global isNaN() : Converts the value to a number and then checks if it is NaN .

The global isNaN() function is useful for checking if a value is NaN or cannot be
converted to a number, making it a handy tool for validating numerical inputs in
your JavaScript code.

Number object provides several useful


methods
In JavaScript, the Number object provides several useful methods for working
with numeric values. These methods allow you to convert numbers to strings,
format numbers, check for finite values, and more. Here's an overview of some
commonly used Number methods:

1. toString()
The toString() method converts a number to a string.

Core Javascript 02 27
let num = 123;
console.log(num.toString()); // Output: "123"

2. toExponential()
The toExponential() method converts a number to a string, using exponential
notation.

let num = 123456;


console.log(num.toExponential()); // Output: "1.23456e+5"

You can also specify the number of digits after the decimal point:

console.log(num.toExponential(2)); // Output: "1.23e+5"

3. toFixed()
The toFixed() method converts a number to a string, keeping a specified number
of decimals.

let num = 123.456;


console.log(num.toFixed(2)); // Output: "123.46"

4. toPrecision()
The toPrecision() method converts a number to a string, rounding it to a specified
number of significant digits.

let num = 123456.789;


console.log(num.toPrecision(5)); // Output: "123460"

You can also use it with exponential notation:

console.log(num.toPrecision(3)); // Output: "1.23e+5"

5. valueOf()
The valueOf() method returns the primitive value of a number.

Core Javascript 02 28
let num = 123;
console.log(num.valueOf()); // Output: 123

6. isFinite()
The isFinite() method checks if a value is a finite number.

console.log(Number.isFinite(123)); // Output: true


console.log(Number.isFinite(Infinity)); // Output: false

7. isInteger()
The isInteger() method checks if a value is an integer.

console.log(Number.isInteger(123)); // Output: true


console.log(Number.isInteger(123.45)); // Output: false

8. isNaN()
The isNaN() method checks if a value is NaN (Not-a-Number).

console.log(Number.isNaN(NaN)); // Output: true


console.log(Number.isNaN(123)); // Output: false

9. isSafeInteger()
The isSafeInteger() method checks if a value is a safe integer, which means it is an
integer within the range of -(2^53 - 1) to 2^53 - 1.

console.log(Number.isSafeInteger(123)); // Output: true


console.log(Number.isSafeInteger(123.45)); // Output: false
console.log(Number.isSafeInteger(9007199254740992)); // Output: false (o
ut of safe range)

Summary
toString() : Converts a number to a string.

toExponential() : Converts a number to a string in exponential notation.

Core Javascript 02 29
toFixed() : Converts a number to a string with a specified number of decimals.

: Converts a number to a string with a specified number of


toPrecision()

significant digits.

valueOf() : Returns the primitive value of a number.

isFinite() : Checks if a value is a finite number.

isInteger() : Checks if a value is an integer.

isNaN() : Checks if a value is NaN .

isSafeInteger() : Checks if a value is a safe integer.

These methods provide powerful tools for working with numbers in JavaScript,
allowing you to format, convert, and validate numeric values effectively.

several global methods


JavaScript provides several global methods that can be used to work with
various data types. These methods are available globally and can be used
without needing to call them on a specific object. Here are some commonly
used global methods:

1. Number()
The Number() function converts a value to a number.

Syntax

Number(value)

Examples

console.log(Number("123")); // Output: 123


console.log(Number("123.45")); // Output: 123.45
console.log(Number("abc")); // Output: NaN (Not-a-Number)
console.log(Number(true)); // Output: 1
console.log(Number(false)); // Output: 0

Core Javascript 02 30
console.log(Number(null)); // Output: 0
console.log(Number(undefined)); // Output: NaN

2. parseFloat()
The parseFloat() function parses a string and returns a floating-point number.

Syntax

parseFloat(string)

Examples

console.log(parseFloat("123.45")); // Output: 123.45


console.log(parseFloat("42")); // Output: 42
console.log(parseFloat("123.45 more text")); // Output: 123.45
console.log(parseFloat("more text 123.45")); // Output: NaN
console.log(parseFloat("abc")); // Output: NaN

3. parseInt()
The parseInt() function parses a string and returns an integer.

Syntax

parseInt(string, radix)

string : The string to be parsed.

radix : An integer between 2 and 36 that represents the base of the numeral
system to be used.

Examples

console.log(parseInt("123")); // Output: 123


console.log(parseInt("123.45")); // Output: 123
console.log(parseInt("123 more text")); // Output: 123
console.log(parseInt("more text 123")); // Output: NaN
console.log(parseInt("0x1A")); // Output: 26 (hexadecimal to decimal)

Core Javascript 02 31
console.log(parseInt("1010", 2)); // Output: 10 (binary to decimal)
console.log(parseInt("abc")); // Output: NaN

Summary
Number() : Converts a value to a number.

parseFloat() : Parses a string and returns a floating-point number.

parseInt() : Parses a string and returns an integer.

These global methods are essential for converting and manipulating different
data types in JavaScript, making them versatile tools for various programming
tasks.

Sure! Here's a simplified explanation of the Date object in JavaScript:

Date Object
The Date object in JavaScript helps you work with dates and times. It provides
many useful methods to manipulate and format dates and times.

Key Points
1. Client Machine Date and Time:

The Date object uses the date and time settings from the client's
machine. If the client's date or time is wrong, your script will use that
incorrect information.

2. Days of the Week:

Days of the week are numbered starting from 0:

0 = Sunday

1 = Monday

Core Javascript 02 32
2 = Tuesday

...

6 = Saturday

3. Months of the Year:

Months of the year are numbered starting from 0:

0 = January

1 = February

2 = March

...

11 = December

4. Days of the Month:

Days of the month start with 1 (e.g., January 1st is day 1).

Example
Here's a simple example to illustrate how to use the Date object:

// Create a new Date object with the current date and time
let now = new Date();

// Get the current year


let year = now.getFullYear();
console.log("Year:", year);

// Get the current month (0-11)


let month = now.getMonth();
console.log("Month:", month); // Output will be 0 for January, 1 for Februar
y, etc.

// Get the current day of the month (1-31)


let day = now.getDate();
console.log("Day of the month:", day);

// Get the current day of the week (0-6)


let dayOfWeek = now.getDay();

Core Javascript 02 33
console.log("Day of the week:", dayOfWeek); // Output will be 0 for Sunda
y, 1 for Monday, etc.

Summary
Client Machine Date and Time: The Date object uses the client's machine
date and time.

Days of the Week: Numbered from 0 (Sunday) to 6 (Saturday).

Months of the Year: Numbered from 0 (January) to 11 (December).

Days of the Month: Start with 1.

The Date object provides a convenient way to work with dates and times in
JavaScript, allowing you to easily manipulate and format date and time values.

Creating a Date object in JavaScript can be done in several ways, depending on


the information you have. Here’s a simplified explanation of how to create Date

objects using different constructors:

1. Creating a Date Object with Milliseconds


You can create a Date object by passing the number of milliseconds since
January 1, 1970 (the Unix epoch).

Syntax

new Date(milliseconds)

Example

var tarikh = new Date(86400000); // 86,400,000 milliseconds = 1 day


document.write(tarikh); // Output: Date representing January 2, 1970

2. Creating a Date Object with Specific Date and Time


Components

Core Javascript 02 34
You can create a Date object by specifying the year, month, day, hours,
minutes, seconds, and milliseconds. You can omit some of the arguments if you
don't need to specify them.

Syntax

new Date(year, month, day, hours, minutes, seconds, milliseconds)

Examples

// Full date and time


var tarikh = new Date(2018, 4, 25, 9, 45, 35, 0); // May 25, 2018, 09:45:35 A
M
document.write(tarikh);

// Omitting milliseconds
var tarikh = new Date(2018, 4, 25, 9, 45, 35); // May 25, 2018, 09:45:35 AM
document.write(tarikh);

// Omitting seconds
var tarikh = new Date(2018, 4, 25, 9, 45); // May 25, 2018, 09:45:00 AM
document.write(tarikh);

// Omitting minutes
var tarikh = new Date(2018, 4, 25, 9); // May 25, 2018, 09:00:00 AM
document.write(tarikh);

// Omitting hours
var tarikh = new Date(2018, 4, 25); // May 25, 2018, 00:00:00 AM
document.write(tarikh);

// Omitting day
var tarikh = new Date(2018, 4); // May 1, 2018, 00:00:00 AM (months are ze
ro-indexed)
document.write(tarikh);

// Using milliseconds

Core Javascript 02 35
var tarikh = new Date(86400000); // January 2, 1970, 00:00:00 AM
document.write(tarikh);

Key Points
1. Milliseconds: You can create a Date object by passing the number of
milliseconds since January 1, 1970.

2. Specific Date and Time: You can create a Date object by specifying the
year, month, day, hours, minutes, seconds, and milliseconds. Months are
zero-indexed (0 = January).

3. Omitting Arguments: You can omit some of the arguments if you don't
need to specify them.

Summary
Milliseconds: new Date(milliseconds) creates a date based on milliseconds since
January 1, 1970.

Specific Date and Time: new Date(year, month, day, hours, minutes, seconds, milliseconds)

creates a date with the specified components.

Omitting Arguments: You can omit some arguments if they are not needed.

These methods provide flexibility in creating Date objects in JavaScript,


allowing you to work with dates and times in various formats.

Certainly! The image you provided explains how to create a date object in
JavaScript and provides examples of different date formats. Here's a detailed
explanation:

Creating a Date Object in JavaScript


In JavaScript, you can create a new date object using the Date constructor. The
syntax is:

new Date(dateString)

This creates a new date object from a date string.

Core Javascript 02 36
Example
The example given in the image is:

var tarikh = new Date("May 12, 2018 10:16:05");

This line of code creates a new date object tarikh with the date and time set to
May 12, 2018, at 10:16:05.

Date Formats
The image also provides a table of different date formats:

1. ISO Date

Format: YYYY-MM-DD

Example: "2018-06-21" (The International Standard)

2. Short Date

Format: MM/DD/YYYY

Example: "06/21/2018"

3. Long Date

Format: MMMM DD YYYY

Example: "June 21 2018" or "21 June 2018"

Explanation of Formats
ISO Date: This format is widely used and follows the international standard
for date representation. It starts with the year, followed by the month, and
then the day.

Short Date: This format is commonly used in the United States. It starts
with the month, followed by the day, and then the year.

Long Date: This format is more descriptive and can vary slightly in
representation. It typically includes the full name of the month, the day, and
the year.

Summary

Core Javascript 02 37
The image provides a clear explanation of how to create a date object in
JavaScript using a date string and illustrates different date formats that can be
used to represent dates. This is useful for understanding how dates are
handled and formatted in JavaScript.

Core Javascript 02 38

You might also like