Variables & Data Types
Variables & Data Types
Variables & Data Types
The indirect method involves linking the JS file through an HTML file, while the direct
method allows you to run JS code immediately in the browser console window.
Summary
Indirect Method: Connects via HTML file (loads JS when opening the HTML).
Create a JavaScript file (e.g., script.js):
Create an HTML file (e.g., index.html):
Link JS and HTML files (e.g. <script src="script.js"></script>):
Direct Method Using Browser Console: Runs JS code directly in the browser
console window.
Open your Browser and Press F12 or right click on the browser than click inspect
option.
Go to the Console tab.
Type your JS code directly. console.log("Direct connection!");
Variables in JS - (variables names should be meaningful)
In JavaScript, variables are used to store data or information. You can think of a
variable as a box or container that holds or stores a value, like a number, a word,
boolean or any other type of data. The value inside the variable can be changed at
any time.
To create a variable, we use the var, let, const keywords, depending on how we
want the variable to behave.
Example:
let age = 25; // Here, 'age' is a variable that stores the number 25
In this example, age is the name of the box, and it holds the value 25.
Summary
var: Variables can be re-declared and updated (less preferred). Has global scope.
(Before 2015)
Example:
var age = 24;
re-declared
var age = 59;
re-declared
var age = 86
console.log(age) = 86
Note: we can declare variable in var without assigning value (e.g. var age; ) (var
age = 86).
let: Variables cannot be re-declared but can be updated. Has block scope { } .
(ES 6, in 2015)
1. Cannot Redeclare 2. Can be Updated
let age = 24; let age = 24;
Re-declared Updated
let age = 59; age = 59;
Re-declared Updated
let age = 86; age = 86;
1. console.log(age) = Cannot re-declare block-scoped variable ‘age’.
2. console.log(age) = 86
Note: we can declare variable in let without assigning value (e.g. let age; // This
will show undefined in output means we have declared variable but didn’t assign
value to it.) instead we can declare let variable like this (let age = 86).
Note: we cannot declare variable in const without assigning value (e.g. const age;
//This will show error) instead we can declare const variables by assigning value to it
like this (const age = 86 )
For example:
A variable named age clearly indicates it holds a person's age.
A variable named totalCost suggests it stores the total cost of items.
Using meaningful names helps both you and others understand your code better.
What should the Typeof null be if, let's say, it were rectified Now?
The type of null should ideally be "null", because null represents an empty or non-existent
value, and it's not an object.
If the Typeof operator worked correctly for null, the output should be:
Typeof null; // should return "null"
But due to the historical error, it returns "object" instead.
Data Types
Data types tell you what kind of information is stored in a variable. Here are the main
types in JavaScript:
1. Number: This type represents numbers (both whole numbers and decimals).
oExample: let price = 19.99;
2. String: This type represents text. Strings are always in quotes.
o Example: let name = "Alice";
3. Boolean: This type represents true or false values.
o Example: let isStudent = true;
4. BigInt: This type is for very large whole numbers.
o Example: let bigNumber = 12345678901234567890n;
5. Symbol: This type is for creating unique identifiers.
o Example: let uniqueID = Symbol("id");
6. Object: This type is for storing collections of data or more complex entities.
o Example:
let person = {
name: "Bob",
age: 30
};
Summary
Variables: Containers for storing information.
Data Types: Different kinds of information that can be stored in variables (like
numbers, text, true/false values, etc.).
Non-primitive types: These are more complex and can store multiple values or
objects. Instead of holding the value directly, they store a reference to where the
data is stored. For example, an array (list of values) or an object (collection of
properties).
o Example: let person = { name: "John", age: 30 }; (Here, person stores a
reference to an object that holds the name and age).
Summary:
Primitive types = store one value directly.
Non-primitive types = store multiple values or references to objects.
This flexibility allows you to easily work with different types of data, but it can also
lead to unexpected behavior if not managed carefully.
Dynamically Typed in JavaScript
In JavaScript, dynamically typed means you don’t have to specify the type of a
variable when you create it. You can just give it a value, and JavaScript will
understand what type it is.
Example:
let x = 5; // x is a number
x = "Hello"; // now x is a string
In this example, x starts as a number (5) and then changes to a string ("Hello"). You
don’t need to tell JavaScript the type; it knows!
Comparison with Other Languages
In some programming languages, like Java or C++, you have to declare the variable
type first. For example:
int x = 5; // x is a number
x = "Hello"; // This will cause an error
In these languages, you must say int before x to tell the computer that x is a
number, and you cannot change it to a string later.
Example in Java:
1. Integer:
int x = 5; // x is a number
x = "Hello"; // This will cause an error
2. String:
String name = "John"; // name is a string
name = 10; // This will cause an error
3. Boolean:
boolean isActive = true; // isActive is a boolean
isActive = "Yes"; // This will cause an error
Summary:
In Java you must declare the variable type before using it. If you try to assign a
different type later (like assigning a string to an integer variable), it will cause an
error. This is different from JavaScript, where you can change the type without any
issues.
Variable Rules in JS
Here are the key rules for naming variables in JavaScript:
Start with a First Letter: Use a letter, underscore (_), or dollar sign ($), and do
not start with digits or numbers.
Variable Names are Case Sensitive: myVariable and myvariable are different (A,
a).
No Spaces: Use underscores or camelCase instead ( _ , camelCase).
No Special Characters: Avoid characters like (@, #, or %).
No Reserved Words We cannot use JavaScript reserved words (if, else, or function)
as variable names.
However, we can use them if we change the case, like using “Console instead of
console” or
“IF instead of if” but it is not a recommended practice.
Meaningful Names: Choose names that clearly describe the variable's purpose
(e.g., totalCost instead of x).
"case" refers to how letters are capitalized in variable names in JavaScript. It's
important because JavaScript is case sensitive.
For example, myVariable and myvariable are different variables. Using consistent
casing, like camel case or snake case, helps make the code clearer.
BigInt Definition
BigInt is a special number type in JavaScript that allows you to work with whole numbers
larger than 2^53−1, 2^{53} – 1, 253−1.
How It Works
You can create a BigInt by adding an n at the end of a number.
You can also use the BigInt() function.
Why We Use It
BigInt is useful when you need to perform calculations with very large numbers, such as in
financial applications, scientific calculations, or cryptography.
Practical Example
// Creating a BigInt
let largeNumber = 9007199254740991n; // A large number
let evenLargerNumber = BigInt("123456789012345678901234567890"); // Another
large number
// Adding BigInts
let total = largeNumber + evenLargerNumber;
Symbol Definition
Symbol is a unique and immutable data type in JavaScript. Each Symbol is different, even
if they have the same description.
How It Works
You create a Symbol using the Symbol() function.
Why We Use It
Symbols are useful to create unique property keys in objects, preventing name collisions
when different parts of the code might use the same key name.
Practical Example
// Creating symbols
let uniqueKey = Symbol("key1");
let anotherKey = Symbol("key1"); // This is a different symbol
Conclusion
A whole number is a number without fractions or decimals, starting from 0.
The largest whole number you can safely use in JavaScript is
9,007,199,254,740,991.
If you need to work with bigger numbers, you should use BigInt to avoid mistakes
Key Points
1. Largest Whole Number in JavaScript:
o The highest whole number that JavaScript can accurately count and handle
without making mistakes is 253−12^{53} - 1253−1.
2. What is 253−12^{53} - 1253−1?:
o When you calculate 253−12^{53} - 1253−1, you get
9,007,199,254,740,991.
o This means that JavaScript can safely use numbers up to this value without
losing any accuracy.
3. Result Example:
o If you write Number.MAX_SAFE_INTEGER in JavaScript, it will give you
9,007,199,254,740,991.
o If you try to add 1 to this number, you may still get 9,007,199,254,740,991
instead of 9,007,199,254,740,992, which shows that JavaScript can't handle
it correctly beyond this limit.
Example Code
Here’s a simple example to show this:
let maxSafeWholeNumber = Number.MAX_SAFE_INTEGER; // This is
9007199254740991
When you see 253−12^{53} - 1253−1, it means you're using the number 2 raised to the
power of 53, and then subtracting 1. Let's break down what happens if you use
153−11^{53} - 1153−1 and 353−13^{53} - 1353−1.
Summary of Results
For 153−11^{53} - 1153−1:
o Result: 0
For 353−13^{53} - 1353−1:
o Result: Approximately 9,075,335,221,537,702,513
Implications
0: This shows that 153−11^{53} - 1153−1 does not give you any large value; it’s
simply zero.
Large Number: The result of 353−13^{53} - 1353−1 is a very large number, much
larger than what JavaScript can safely handle with the regular number type. For this
large number, you would need to use BigInt in JavaScript to avoid losing precision.
Example Code
Here’s how you could write it in JavaScript:
let result1 = 1 ** 53 - 1; // This will be 0
let result2 = BigInt(3) ** BigInt(53) - BigInt(1); // This will be a very large number
console.log(result1); // Output: 0
console.log(result2.toString()); // Output: 9075335221537702513 (as a BigInt)
Conclusion
153−11^{53} - 1153−1 equals 0.
353−13^{53} - 1353−1 equals a very large number, which should be handled as a
BigInt in JavaScript to ensure accuracy.