CoreJavascriptPart2
CoreJavascriptPart2
Boolean()
You're absolutely correct! Let's break down the concept of Boolean in
JavaScript, including its primitive values, the Boolean() function, the Boolean
Example:
Here, primitiveTrue is a primitive boolean with the value true , and primitiveFalse is
a primitive boolean with the value false .
Example:
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
Example:
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:
Core Javascript 02 2
The constructor creates a Boolean object. However, using the new
Boolean
wrapper around the boolean value, which can lead to unexpected behavior.
Example:
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:
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.");
}
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 :
Negative Numbers: Negative numbers are truthy because they are not 0 .
Core Javascript 02 4
Q: What is the difference between using the Boolean() function and the new
Answer:
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:
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 .
Core Javascript 02 5
By understanding how booleans work in JavaScript, you'll be able to handle
logical conditions and evaluate expressions more effectively! 😊
1. Primitive Strings
Primitive strings are immutable sequences of characters. They can be created
using single quotes ( ' ), double quotes ( " ), or backticks ( ` ).
Double Quotes ( " ) and Single Quotes ( ' ): These are the most common
ways to define strings. Both are functionally identical.
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.
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.
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
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 ( \\ ).
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.
2. String Objects:
3. Escaping Characters:
4. Template Literals:
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>');
This code demonstrates the different ways to create and manipulate strings in
JavaScript.
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:
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 ( " " ).
Syntax:
Example:
Core Javascript 02 10
document.write(new_str); // Output: HelloGeekyShows
Note: The concat() method does not modify the original string; it returns a
new concatenated string.
// Using + operator
document.write(firstName + " " + lastName); // Output: John Doe
Core Javascript 02 11
var greeting = "Hello";
var name = "GeekyShows";
// Using + operator
document.write(greeting + " " + name + "! Welcome!"); // Output: Hello Ge
ekyShows! Welcome!
// Using + operator
document.write(str + num); // Output: The answer is 42
Example:
Core Javascript 02 12
var fullName = `Full Name: ${firstName} ${lastName}`;
document.write(fullName); // Output: Full Name: John Doe
2. concat() Method:
3. Template Literals:
Introduced in ES6.
Example Code:
// Using + operator
var str1 = "Hello";
var str2 = "GeekyShows";
document.write(str1 + " " + str2 + "<br>"); // Output: Hello GeekyShows
Core Javascript 02 13
var greeting = `Welcome to ${str2}!`;
document.write(greeting); // Output: Welcome to GeekyShows!
Numbers
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.
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.
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.
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)
1. Primitive Numbers:
Core Javascript 02 15
These are simple numeric values like 10 , 10.45 , etc.
var a = 10;
var b = 10;
2. Number Objects:
console.log(a === b); // Output: false (because they are different objec
ts)
1. NaN (Not-a-Number):
var result = 0 / 0;
console.log(result); // Output: NaN
2. 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 :
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) :
2. toPrecision(precision) :
3. toString(base) :
Core Javascript 02 17
console.log(num.toString(16)); // Output: "a" (hexadecimal representati
on)
4. Number.isNaN(value) :
5. Number.isFinite(value) :
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.
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.
Core Javascript 02 19
converted to a number).
Examples Explained
Example 1: a + b
Example 2: a - b
Example 3: b + c + a
Core Javascript 02 20
First, b+c is evaluated. Since both b and c are numbers, their sum is 10 +
20 = 30 .
Example 4: a + b + c
The result of a+b is "50" + "10" (converted to a string), which gives "5010" .
First, "Result: " + b is evaluated. Since "Result: " is a string, the + operator
performs string concatenation.
Next, "Result: 10" + c is evaluated. Again, since "Result: 10" is a string, the +
Core Javascript 02 21
The result is "Result: 10" + "20" , which gives "Result: 1020" .
Key Takeaways
1. + Operator:
3. Order Matters:
The order in which operations are performed affects the result. For
example:
4. Type Conversion:
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);
Output: "102030"
2. console.log(b + c + a);
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.
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.
3. Detection: You can use the isNaN() function to check if a value is NaN .
Examples
1. Basic Example
2. Arithmetic Operations
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.
check if a value is NaN , as it only returns true for the actual NaN value.
function divide(a, b) {
if (b === 0) {
return NaN; // Return NaN if the divisor is zero
}
return a / b;
}
Summary
NaN : Represents an undefined or unrepresentable number.
Core Javascript 02 25
Certainly! Here's a focused explanation on the global isNaN() function in
JavaScript:
Syntax
isNaN(value)
Key Points
1. Purpose: Determines whether a value is NaN or cannot be converted to a
number.
Examples
1. Basic Example
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() :
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.
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.
You can also specify the number of digits after the decimal point:
3. toFixed()
The toFixed() method converts a number to a string, keeping a specified number
of decimals.
4. toPrecision()
The toPrecision() method converts a number to a string, rounding it to a specified
number of significant digits.
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.
7. isInteger()
The isInteger() method checks if a value is an integer.
8. isNaN()
The isNaN() method checks if a value is NaN (Not-a-Number).
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.
Summary
toString() : Converts a number to a string.
Core Javascript 02 29
toFixed() : Converts a number to a string with a specified number of decimals.
significant digits.
These methods provide powerful tools for working with numbers in JavaScript,
allowing you to format, convert, and validate numeric values effectively.
1. Number()
The Number() function converts a value to a number.
Syntax
Number(value)
Examples
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
3. parseInt()
The parseInt() function parses a string and returns an integer.
Syntax
parseInt(string, radix)
radix : An integer between 2 and 36 that represents the base of the numeral
system to be used.
Examples
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.
These global methods are essential for converting and manipulating different
data types in JavaScript, making them versatile tools for various programming
tasks.
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.
0 = Sunday
1 = Monday
Core Javascript 02 32
2 = Tuesday
...
6 = Saturday
0 = January
1 = February
2 = March
...
11 = December
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();
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.
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.
Syntax
new Date(milliseconds)
Example
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
Examples
// 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)
Omitting Arguments: You can omit some arguments if they are not needed.
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:
new Date(dateString)
Core Javascript 02 36
Example
The example given in the image is:
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
2. Short Date
Format: MM/DD/YYYY
Example: "06/21/2018"
3. Long Date
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