Variables & Data Types

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

What is JavaScript?

JavaScript is a programming language used to give instructions to the computer.

How does it work?


 Input
We give input, in the form of instructions written in JavaScript.
 Processing
The computer reads and processes the JavaScript code.
 Output
The computer processes these instructions and gives us the output. The output is
dependent on the input.

Variables and Data Types

First JavaScript Code and its writing styles


console.log() is used to print massage on browser’s console window; following are the
writing styles;

 console.log(“Anabia Muhammad”); - Double quotes and semicolon


 console.log(‘Anabia Muhammad’); - SINGLE quotes and semicolon
 console.log(“Anabia Muhammad”) - Double quotes and NO semicolon
 console.log(‘Anabia Muhammad’) - SINGLE quotes and NO semicolon

How to connect JS file to window browser?


To connect a JavaScript (JS) file to the browser, you can use two methods: indirect and
direct.

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.

What are the Keywords in JS?


Keywords are (fixed reserved words) used to Declare a Variable in JS. The purpose of using
keywords like var, let, and const in JavaScript is to declare and manage variables.

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).

 const: Variables cannot be re-declared or updated. Has block scope { } . (ES 6,


in 2015)
Example:
const age = 24;
re-declared
const age = 59;
re-declared
const age = 86
console.log(age) = Cannot re-declare or updated block-scoped variable
‘age’.

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 )

Variable names should be meaningful!


When creating variables, the name of the variable should be meaningful, which means it
should clearly describe what the variable represents or stores. This makes your code easier
to understand and maintain.

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 are the Purpose and Benefits of using Keywords in JS.


In JavaScript, when we declare a variable using var, let, or const, they help control two
things:
1. Where we can use the variable: Some variables can be used everywhere in your
code, and others only in small parts.
2. Whether the value can change: Some variables can be changed, and others
cannot.
 var: we can use it anywhere, and you can change the value.
 let: we can only use it in a small part of your code, but you can still change the value.
 const: we cannot change the value once it is set.
These keywords help you organize your code and avoid mistakes.
Data Types in JS?
In JavaScript, data types are classified into two categories: primitive and non-primitive.

Primitive Data Types:


These are basic data types that hold a single value.
 Number: For numbers (e.g., 42, 3.14)
 String: For text (e.g., "hello", 'world', “123”)
 Boolean: For true/false values (e.g, isFollow (true, false).
 Undefined: A variable that has been declared but not assigned a value (e.g., let x;)
 Null: Represents no value or an empty object (e.g., let y = null;)
 BigInt: For large integers (e.g., 123n)
 Symbol: For unique identifiers (e.g., Symbol('id'))

Non-Primitive (Reference) Data Types:


These are complex types that can hold multiple values or objects.
 Object: Used for collections of key-value pairs (e.g., {name: "John", age: 30})
 Array: A list of values (e.g., [1, 2, 3])
 Function: A block of code that performs a task (e.g., function greet() {})

Why is the Typeof null is returns “object”?


In simple terms, Typeof null shows "object" because of a mistake made in the early days of
JavaScript. The mistake has stayed the same to avoid breaking old code.
Even though it says "object", null is not an object—it's just an empty value.

What if, let's say, it is rectified Now?


The person who created JavaScript made a small mistake when developing it. If this
mistake were corrected now, it would break a lot of existing websites and applications that
depend on the current behavior of Typeof null. To avoid causing problems for all the code
that relies on this, they decided to keep it as it is.
This is why the mistake hasn't been fixed, even though developers are aware of it.

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.).

Key Difference of Primitive and Non-Primitive Data Types:


 Primitive types: These are simple data types that hold just one single value. For
example, a number, a word (string), or a true/false value (Boolean). They store the
value directly.
o Example: let age = 25; (Here, age holds the value 25 directly).

 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.

What does it mean for JS to be a dynamically typed language?


In JavaScript, "dynamically typed" means you don't need to specify the type of a
variable when you create it. You can change the type of the value stored in a
variable at any time.
Example:
let value = 10; // Initially a number
value = "Hello"; // Now it's a string

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).

Importance of CASES as Variable Names in JS


(This is not a rule but a convention. Convention means a generally accepted way of
doing something or a standard practice that is widely followed. )

"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.

Here are the main types:


1. Camel Case: The first word is lowercase, and each subsequent word starts
with an uppercase letter.
Example: myVariableName (Recommended)
2. Pascal Case: Each word starts with an uppercase letter.
Example: MyVariableName
3. Snake Case: Words are separated by underscores, and all letters are typically
lowercase.
Example: my_variable_name
4. Kebab Case: Words are separated by hyphens. Note that this is not valid for
variable names in JavaScript.
Example: my-variable-name (not allowed in JS)
Using these naming conventions helps improve code readability.

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;

console.log(total); // Output: 123456789012345678901234567890n


Where It Can Be Used
 Banking Systems: To handle large transactions or account balances.
 Gaming: To manage large scores or levels.

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

// Check if they are the same


console.log(uniqueKey === anotherKey); // Output: false (they are different)

// Using symbols as object keys


let myObject = {
[uniqueKey]: "This value is unique to uniqueKey"
};
console.log(myObject[uniqueKey]); // Output: "This value is unique to uniqueKey"
Where It Can Be Used
 Library Development: To create private properties in objects.
 Avoiding Conflicts: In large applications, to ensure property names don’t clash.
Let’s simplify it even further and explain what a whole number is too.

What is a Whole Number?


 A whole number is any number that is not a fraction or a decimal.
 Whole numbers start from 0 and go up: 0, 1, 2, 3, 4, 5, ... (and so on).
 They do not include negative numbers or any numbers with decimals (like 1.5 or -3).

What Does "Larger Than 253−12^{53} – 1, 253−1" Mean?


1. The Largest Safe Whole Number in JavaScript:
o In JavaScript, the biggest whole number you can safely use without mistakes is
9,007,199,254,740,991.
o This number is written as 253−12^{53} - 1253−1 in math.
o The 2532^{53}253 part means you multiply 2 by itself 53 times, and then
you subtract 1.
2. Why This Limit?:
o JavaScript stores numbers in a special way that has a limit.
o This limit is the highest whole number it can count correctly without making
mistakes.
3. What Happens If You Go Over This Number?:
o If you try to add 1 to the largest safe number, you might not get the correct
answer.
o For example, when you add 1 to 9,007,199,254,740,991, you still get
9,007,199,254,740,991. This is wrong!
o This happens because JavaScript can't handle numbers this big accurately with
its regular number type.

Example to Show This


Let’s see a simple example:
let maxSafeWholeNumber = Number.MAX_SAFE_INTEGER; // This is
9007199254740991

// Try to add 1 to this number


let wrongAnswer = maxSafeWholeNumber + 1;

console.log(maxSafeWholeNumber); // Output: 9007199254740991


console.log(wrongAnswer); // Output: 9007199254740991 (This is NOT the correct
answer)
Why Use BigInt?
 BigInt allows you to work with whole numbers that are bigger than
9,007,199,254,740,991 without making mistakes.
 With BigInt, you can add, subtract, and do math with really big whole numbers and
get the right answers.

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

console.log(maxSafeWholeNumber); // Output: 9007199254740991

// Try to add 1 to the maximum safe whole number


let result = maxSafeWholeNumber + 1;

console.log(result); // Output: 9007199254740991 (Not accurate!)


Summary
 9,007,199,254,740,991 is the largest whole number that JavaScript can count
correctly.
 If you try to work with numbers larger than this, you might not get the right answers.
 That’s why BigInt is used for larger numbers!

Do we Always use 253−12^{53} - 1253−1 in JavaScript?

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.

1. Using 153−11^{53} - 1153−1


 Calculation: 153−1=1−1=01^{53} - 1 = 1 - 1 = 0153−1=1−1=0
 Meaning:
o Since any number raised to the power of 0 is still 1, 1531^{53}153 is just 1.
o So, 153−11^{53} - 1153−1 equals 0.

2. Using 353−13^{53} - 1353−1


 Calculation: 353−13^{53} - 1353−1
 Result:
o This is a much larger number. Let's calculate 3533^{53}353:
o 3533^{53}353 equals approximately 9,075,335,221,537,702,514 (a very
large number).
o Therefore, 353−13^{53} - 1353−1 would be about
9,075,335,221,537,702,513.

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy