003_Javascript_DataTypes

Javascript is a dynamically typed programming language, meaning that there are data types but variables are not bound to any of them. Hence, a variable can at one moment be a number and at another be a string.

There are eight basic data types in Javascript.

  1. Number
  2. BigInt
  3. String
  4. Boolean
  5. "null"
  6. "undefined"
  7. Objects
  8. Symbols

typeof operator/function

  • The typeof operator returns the type of the argument.
  • It supports two forms of syntax:
    1. As an operator: typeof x.
    2. As a function: typeof(x).
typeof undefined // "undefined"

typeof 0 // "number"

typeof 10n // "bigint"

typeof true // "boolean"

typeof "foo" // "string"

typeof Symbol("id") // "symbol"

typeof Math // "object"  (1)

typeof null // "object"  (2)

typeof alert // "function"  (3)

Number

  • The "number" type represents both integer and floating-point numbers.
  • There are some "special numeric values" which also belong to this data type, [ Infinity, -Infinity, NaN ].
  • Infinity represents the mathematical Infinity. (eg: 1/0).
  • NaN represents a computational error. It's a result of an incorrect or an undefined mathematical operation. NaN is sticky any further operation on NaN returns NaN.
  • Javascript consists of two types of numbers:

    1. Regular numbers in JS are stored in 64-bit format, also known as "double-precision floating-point numbers"
    2. BigInt numbers, represent integers of arbitrary length.

More ways to write a Number

let billon = 1000000000; 
//or
let billion = 1e9;

//Similarly, for small numbers
let ms = 0.000001
//or 
let ms = 1e-6;

Hex, Binary, Octal Numbers

  • Hexadecimal numbers ( 0x and then number).
  • Octal numbers ( 0o and then number).
  • Binary numbers ( 0b and then number).
let a = 0b1111111;
let b = 0o377;
alert(a==b); //true

toString(base)

The method num.toString(base) returns a string representation of num in numeral system with the given base.

let num = 255;
console.log( num.toString(16) ); //hex
console.log( num.toString(2) ); //binary
  • The base can vary from 2 to 36, By default it's 10.
  • Base 36 is [0-9a-z] i.e useful case to turn a long numeric identifier into a short string.
// Note: two dots to call a method
98765..toString(36);

This notation allows us to call the method directly on a number.

Rounding

Math.floor(number) 
// Rounds down; 3.1 to 3 and -1.1 to -2.

Math.ceil(number) 
// Rounds down; 3.1 to 4 and -1.1 to -1.

Math.round(number) 
// Rounds to nearest integer, 3.1 to 3 and -1.1 to -1.

Math.trunc(number) 
// Truncates decimel point without rounding off.

number.toFixed(decimelPart)
// eg:
let num = 12.36
console.log( num.toFixed(1) );  // "12.4" string
+num.toFixed(1); //+ unary plus converts string to number

Imprecise Calculations

  • A number is represented in a 64-bit format.
  • 52 bits to store digits.
  • 11 bits to store the position of the decimel points
  • 1 bit to store the sign.
  • If number is too big, it overflows the 64bit storage(gives infinity ).
console.log( 0.1 + 0.2 == 0.3 ) // return false

Since numbers are stored in binary format and converting 1/10 to binary is an endless binary fraction (equivalent to 1/3 in decimal format). Hence there is exactly no way to store such numbers.

  • We could use "toFixed(n)" to work around this issue.

isFinite and isNaN

  • Infinity and -Infinity is a special numeric value that is greater (less) than anything.
  • NaN represents an error.

  • isNan(value), it converts its argument to a number and then tests it for being NaN.

console.log( isNaN(NaN) ); //true
console.log( isNaN("str") ); //false

Note: NaN!=NaN, NaN is unique and it does not equal anything.
  • isFinite(value) converts arguments to a number and returns true if it's a number and not NaN/Infinity/-Infinity.
console.log( isFinite("15") );
console.log( isFinite(Infinity) );
Note: empty-string or space is treated as 0 in all functions.

Compare with Object.is(a,b)

console.log( Object.is(NaN,Nan) ) is true (===)

parseInt and parseFloat

  • Numeric conversion using a plus or Number() is strict. If a value is not exactly a number it fails.(spaces around the value are ignored)

    console.log( +"100px" ); // NaN

  • The parseInt(value) returns an integer and parseFloat(value) returns an floating-point number.

    Note: they start parsing from left to right so alphabet in beginning of a number will result into a NaN.

console.log(parseInt("100px")); //100
console.log(parseInt("a123")); //NaN

The second argrument of parseInt() is base/radix.

parseInt("2n9c",36); //123456

Other Math functions

Math.random()
// returns a random number in a set [0-1) i.e. 1 is not included.

Math.max(a,b,c,....);
//returns greatest number

Math.min(a,b,c,...);
//returns smallest number

Math.pow(n , power);
// return n raised to the given power.

More math functions.

Complete Math Object Docs

~n ---> -(n+1)

BigInt

  • BigInt is a special numeric type that provides support for integers of arbitrary length.
  • A bigint is created by appending n to the end of an integer literal or by calling the function BigInt that creates bigints from strings, numbers etc.
const big1 = 1234567890123456789012345678901234567890n;

const big2 = BigInt("1234567890123456789012345678901234567890");

const bigintFromNumber = BigInt(10); // same as 10n
  • BigInt can mostly be used like a regular number.
  • The unary plus is not supported on bigints.

String

  • A string in JS must be surrounded by quotes.
  • In JS there are 3 types of quotes :
    1. Double quotes : "Hello".
    2. Single quotes: 'Hello'.
    3. Backticks: `Hello`.
  • Double and Single quotes are similar.
  • Backticks are 'extended functionality' quotes. They allow us to embed variables and expressions into a string by wrapping them in ${variable}.
    let name='manish';
    console.log( `Hello, ${name}`);
    
  • The expression inside ${...} is evaluated and the result becomes the part of the string. We can put anything here variable or an arithmetical expression or something complex.

String length

  • length is a property, not a function.

    console.log( str.length );

Accessing Characters

  • To get a character at position pos, use square brackets [pos] or call the method str.charAt(pos).
  • The only difference between them is that if no character is found, [] returns undefined, and charAt returns an empty string.
let str = `Hello`;
alert( str[1000] ); // undefined
alert( str.charAt(1000) ); // '' (an empty string)
  • We can also iterate over characters using for..of:
    for (let char of "string")
     console.log(char);
    

Strings are Immutable

  • Strings can’t be changed in JavaScript. It is impossible to change a character.
  • The usual workaround is to create a whole new string and assign it to str instead of the old one.

Changing the Case

  • toLowerCase()

    str.toLowerCase();

  • toUpperCase();

    str.toUpperCase();

Find a Substring

  • str.indexOf(substr,pos);
  • it looks for the substr in str, starting from the given pos, returns the position where the match was found or -1 if nothing can be found.

    let str = "first second third";
    console.log( str.indexOf("second") );
    
  • str.lastIndexOf(substr,pos)

  • There is also a similar method str.lastIndexOf(substr, position) that searches from the end of a string to its beginning.
  • It would list the occurrences in the reverse order.

    let str = "first second third";
    console.log( str.lastIndexOf("second") );
    
  • str.includes(substr,pos)

  • Returns true/false depending on whether str contains substr within.

    console.log( "Widget".includes("id") ); // true
    console.log( "Widget".includes("id", 3) ); // false, from position 3.
    
  • str.startWith(substr) and str.endsWith(substr).

    console.log( "Widget".startsWith("Wid") ); // true, "Widget" starts with "Wid"
    console.log( "Widget".endsWith("get") ); // true, "Widget" ends with "get"
    `
    

Getting a Substring

There are three methods in JS to get a substring:

  1. str.substring(start, end);
  2. str.substr(start,length);
  3. str.slice(start,end);
    let str = "stringify";
    console.log( str.substring(2,6) );
    // returns the part of the string between start and end.
    // start can be greater then end
    // negative means 0
    
let str = "stringify";
console.log( str.substr(2,6) );
// returns the part of the string from start with the length.
// start can be negative to count from the end.
let str = "stringify";
console.log( str.slice(2,6) );
// returns the part of the string from start to end (not included).
// if no second argument then slice goes till end of string.

Comparing Strings

  • A lowercase letter is always greater than the uppercase.

  • str.codePointAt(pos)

  • Returns the code for the character at position pos.

    console.log( 'zabc'.codePointAt(0) ); // 122

  • str.fromCodePoint(code)

  • Creates a character by its numeric code.

    console.log( String.fromCodePoint(90) ); // Z

  • We can also add unicode characters by their codes using \u followed by the hex code:

    console.log( '\u005a' ); // Z

Boolean

  • The boolean type has only two values: true and false.
  • There are three logical operators in JavaScript: || (OR), && (AND), ! (NOT).

"null"

  • The special null value does not belong to any of the types described above
  • It forms a separate type of its own which contains only the null value.

    let var1 = null;

  • In JS, null is not a “reference to a non-existing object” or a “null pointer” like in some other languages.
  • It’s just a special value which represents “nothing”, “empty” or “value unknown”.

"undefined"

  • The meaning of undefined is “value is not assigned”.
  • If a variable is declared, but not assigned, then its value is undefined
    let x;
    console.log(x); // shows "undefined"
    

Objects and Symbols

  • All other types are called “primitive” because their values can contain only a single thing.
  • Objects are used to store collections of data and more complex entities.
  • The symbol type is used to create unique identifiers for objects.

    link