Does type matters π€
Questions π€
- Does JS have any type or is it strongly typed?
- What are the primitive and non-primitive data types?
- What is the difference between global.isFinite and Number.isFinite?
- What is difference between global.parseInt/parseFloat and Number.parseInt/parseFloat?
null
vsundefined
- What is an array and its methods?
- What is a string and its methods?
- Template Literals in JS or String Interpolation?
- What is the difference between map and foreach
- What are the different ways to iterate over an array?
- How to achieve both stack and queue for an array?
- How can we shuffle array elements?
- Different ways to empty an array
- Remove duplicated from an array
- How do you flatten an array
- What are the different ways to merge and concat an array?
- What is a symbol and what is the benefit of using
symbol
Yes, type matters a lot in all of the programming languages. which is an identity to a variable.
There is an overall 8 different datatype present in Javascript which is further divided into primitive and non-primitive
Primitive Datatype
There are 7 primitive data types and these datatypes are immutable
1. Boolean
Boolean is just true and false like any other programming language
2. Number
πΈ Numbers represent both integer and floating value along with this two there are many other types like
Infinity
represent mathematical βΎοΈ which is special value greater than any number
πΈNaN
(Not a Number) is sticky, If any mathematical operation breaks it will return NaN
Mathematical operations are safe
Doing Math is safe in Js. We can divide 1/0, treat non-numeric string or number to the expression, the script will never not with a fatal error (die). At worst case, you can get NaN as a result
Number Extension Methods
πΈ Binary and Octal Literals
0b
or 0B
prefix to number represent binary integer literals
0o
or 0O
prefix to number represent octal integer literals
0x
or 0X
prefix to number represent hexadecimal integer literals
πΈ Number.isFinite
global.isFinite Vs Number.isFinite
When we execute global.isFinite it internally concise to Number.isFinite and does the same job same for parseInt and parseFloat
πΈ Number.parseInt
πΈ Number.parseFloat
πΈ Number.isInteger
πΈ Number.EPSILON
This is a literally small number.
3. BigInt
Number type can not allow value larger than (2^53-1) and lesser than -(2^53-1) for this BigInt is the rescuer.
4. Null
Null is a special value that doesn't belong to any of the types. Its separate type altogether. Which simply represents zero, empty, or nothing.
In javascript
null
is a Existing Object and doesn't lead to Null Pointer Exception
5. Undefined
Undefined in like a null which stands out of the group. Undefined means not assigned any value
If any variable is declared and used that variable without assigning any value that that will return undefined
Null and undefined both are primitive and falsy value
Null and undefined both are different type but share some similar functionality
double equal test for the loose equality and perform type coercion
.
Javascript is both dynamically typed language meaning its strongly and weakly typed game. And all the master game is being played by
COERCION
. This is kind of debatable topic
6. String
A string datatype is the most commonly used datatype to store textual data. In javascript, there is no separate type for single character char
like any other programming language.
String Extension Methods
πΈ charAt
Return character for a given index (subscript) value
πΈ toUpperCase
Convert sting to uppercase
πΈ toLowerCase
Convert string to lowercase
πΈ indexOf
Get the index of given character from the beginning of the string
πΈ lastIndexOf
Get the index of given character from the end of the string
πΈ include
Check if string include given string or not and return true or false
πΈ startWith
Check if any string starts with given string or not and return true or false
πΈ endsWith
Check if any string ends with given string or not and return true or false
πΈ slice
Break the string based on given character and return an array
πΈ subString
Return part of the string
πΈ codePointAt
Return code for the character at position
πΈ frameCodePoint
Create character by its numeric code
πΈ padStart
Add space at the beginning of the string based on the given value
7. Symbol
Itβs a very peculiar data type. Once you create a symbol
, its value is kept private and for internal use.
It represents a unique
identifier.
One can create a symbol just by calling the Symbol() global factory function and upon creation, we can give the symbol a description (also called a symbol name)
Symbols are guaranteed to be unique. Even if we create many symbols with the same description, they are different values. The description is just a label that doesnβt affect anything.
Remember
Most values in JavaScript support implicit conversion to a string. For instance, we can alert almost any value, and it will work. Symbols are special. They donβt auto-convert.
Thatβs a βlanguage guardβ against messing up because strings and symbols are fundamentally different and should not accidentally convert one into another.
If we want to show a symbol, we need to explicitly call .toString() on it
Or get symbol.description
property to show the description only
Hidden properties of symbol
Symbols allow us to create the hidden
properties of an object, that no other part of code can accidentally access or overwrite.
Whatβs the benefit of using Symbol("id") over a string "id"?
The best benefit is to avoid the name clash since symbol creates a new instance even with the same name we can eliminate the risk of name collision and these hidden properties can be used for the internal functionality purpose.
Consider you have a user object which is used by much other class in your project but you want to add one more key with the same property present in a user object you can achieve that with the symbol.
This is also called symbol literal
for an object
Remember
Symbols are not enumerated, which means that they do not get included in a for..of or for..in loop ran upon an object.
Symbols are not part of the Object.keys() or Object.getOwnPropertyNames() result.
You can access all the symbols assigned to an object using the Object.getOwnPropertySymbols() method.
let user = { name: "John" };let id = Symbol("id");user[id] = 1;Object.getOwnPropertySymbols(user); // [Symbol(id)]
Global Symbol
Usually, all symbols are different, even if they have the same name. But sometimes we want same-named symbols to be the same entities. For instance, different parts of our application want to access symbol "name" meaning exactly the same property.
To achieve that, there exists a global symbol registry. We can create symbols in it and access them later, and it guarantees that repeated accesses by the same name return exactly the same symbol.
In order to read (create if absent) a symbol from the registry, use Symbol.for(key).
This checks the global registry if there is a symbol described by a key then it will return else it will create a new one by the given key in the registry and return it
GLobal Symbol
Symbols inside the registry are called global symbols. If we want an application-wide symbol, accessible everywhere in the code β thatβs what they are for.
There are various other symbol
method which serves different purposes
* Symbol.keyFor
Not only Symbol.for(key) returns a symbol by name, but thereβs a reverse call: Symbol.keyFor(sym), that does the reverse: returns a name by a global symbol
* Symbol.hasInstance
* Symbol.isConcatSpreadable
* Symbol.iterator
* Symbol.toPrimitive
Non-Primitive Datatype
Apart from 7 primitive datatype everything else is an Object in javascript
Ex: Array, function, Object, Set, Regexp etc are Object
1. Array
An array is the most commonly used data type in all of the programming languages to store a list of objects.
Array Extension Methods
πΈ Array.push
Pushing new element at the end of the queue AKA enqueue
πΈ Array.pop
Removing new element at the end of the queue AKA dequeue
πΈ Array.shift
Add an object from the front and push all the element
πΈ Array.unshift
Remove element from the first and shift all the elements one step before
Array Fact π³
Fact 1: In javascript array can act as both Queue
and Stack
data structure
- If we perform
shift
andpush
operation then we can achieveQueue
- If we perform
push
andpop
operation then we can achieveStack
Fact 2: Both push and unshift can add multiple items at once
Fact 3: Internally sports[0]
is nothing but object[0]
since the array is an object everything behind the scene deals with an object.
Notice above snippet I declared expression
array and assigned to humanExpression
array and did a comparison and the result is true. Then I removed one element from the expression
array and logged both array and the changes are also reflected in humanExpression
array. This is because when we assign one object to another object both object will refer to the same address
Fact 4: Since an array is an object we can add a different kind of property to an array as a property
In the log, we can see empty x 9996
since we have added value at position 9999 js engine left the remaining empty positioned value
πΈ Array.spice
Splice can be used to delete an array element
In the above code, we created an array, and then we deleted an item from position one but the length of the array is still 3.
This is because the delete
keyword will just delete content but space will remain. Which cost the memory hence delete
keyword is not recommended solution to delete any item
So to solve this problem we can use splice
We can also play more with splice
πΈ Array.concat
To merge two arrays different array into one single array
πΈ Array.slice
slice
is used to split an array into smaller array chunk
We can use slice
without an arg to create a copy of an original array without affecting the original one
πΈ Array.indexOf
Look for an array item based on a given index and return item else it will return -1
πΈ Array.lastIndexOf
Same as indexof but Look for an array item from the end and based on a given index and return item else it will return -1
πΈ Array.includes
Look for a given item in the array and return true if it found else it will return false
πΈ Array.isArray
Similar to typeOf for an array
πΈ Array.sort
Sort the given array item
Am I lying? π€ even after sorting it dint sort why? π€― This is because javascript converts an array element to string for comparison and for sort it in string lexicographic order (Like Dictionary order)
to achieve sorting we need to struggle a bit
πΈ Array.reverse
Iterate over an array
πΈ While loop
πΈ for loop
πΈ for each loop
forEach
loop does not provide an index of an item
πΈ map
map
will provide an index of an item
πΈ reduce
as the name says it reduces the array item and resulting in a single result
πΈ filter
To filter the array item based on boolean expression
πΈ every
When we want to check the given condition is satisfied with all array element or not
πΈ some
When we want to check the given condition is satisfied with at least some array element or not
Template Literals - Expression Interpolation
πΈ We can use +
to concat multiple strings to construct a single string
πΈ To make it more robust we can use String Interpolation