Wednesday, September 30, 2020

JS Strings | Numbers

Strings are collection of characters stored within quotes (double or single). Strings can have lower case, upper case, special characters or numbers within quotes. Strings can store data, like name, email id, age etc. Default datatype for input, select, textarea value is always a string. 

In JavaScript, Strings are declared inside double quotes "" or single quotes ''. Strings started with double quotes should be closed by double quote and same strings started with single quote should be closed by single quote. Both var x="hello" and var x='hello' are same in javascript.

Backslash, i.e. \ is used inside strings to ignore character. For exp var x="abc\"pqr";

Example 

  var x="Beta Labs";    // string;

 var y='Beta Labs';    // string;
 var z=`Beta Labs`;    // template literal in ES6
 var i="9";            // string
 var j='9';            // string


Template Literals

ES6 introduced Template Literals or Template Strings in JavaScript by using back-tick or grave characters. To insert a placeholder variable in template literal, use ${expression} inside.

var x=3;
var y=5;

console.log(`sum of ${x} and ${y} is ${x+y}`);  //ES6
console.log("sum of " + x + " and " + y + " is " + (x+y));  //ES5

// returns "sum of 3 and 5 is 8"

String Methods and Properties

Primitive values, like "John Doe", cannot have properties or methods (because they are not objects). Properties are information about that string. Properties are checked using Dot notation (.) or brackets [ ] with property name in quotes. See example 

String.length property shows the number of characters in string.

var x = 'hello js';
x.length; // 8

String length property is immutable, means if length of string is 8 and we assign string.length to 10, it will still return 8. See example

var x = 'hello js';

x.length; // 8

x.length = 10;

x.length; // 8

x.length = 2;

x.length; // 8 


Empty String: An empty string is the string with length equals to zero.

var x = '';
x.length; // 0

String Methods

JavaScript Methods are build in functions used to perform an action to strings. All methods are called by method name and then parenthesis. Parameters are passed inside parenthesis if required. For exp, x.age is property, but x.getAge() is a method. 

indexOf: This method returns index of first matched substring. The return value of indexOf() methods is always a number.

If substring is not found, it will return -1.

var x = 'Beta Labs';


x.indexOf('B'); // return 0;

x.indexOf('e'); // return 1;

x.indexOf('f'); // return -1;

lastIndexOf: This method returns index of last matched substring. The return value of lastIndexOf() method will also be number.

If substring is not found, it will return -1.

var x = 'beta labs';

x.indexOf('b'); // return 0;

x.lastIndexOf('a'); // return 6;

x.lastIndexOf('e'); // return 1;

concat: concat() method is used to concatenate or merge two strings into one. The second string should be passed as argument.

var x = 'beta';
var y = 'labs';

x.concat(y); // return betalabs 

+ operator can also concat two strings in javascript.

var x = 'beta';
var y = 'labs';

x + y; // return betalabs

charAt: charAt() method return character at given index in argument.

var x = 'betalabs';

x.charAt(0); // return b

x.charAt(1); // return e

x.charAt(x.length - 1); // return s

x.charAt(x.length); // return ""

charCodeAt: charCodeAt() method return ASCII code of character at given index in argument.

var x = 'betalabs';

x.charCodeAt(0); // return 98

x.charCodeAt(1); // return 101


 toUpperCase: toUpperCase() method convert all lowercase characters to uppercase.

 var x = 'betlabs';


x.toUpperCase(); // return "BETALABS"

toUpperCase method only return string in uppercase, but value of x will remain same, .ie. lowercase

 

toLowerCase: toLowerCase() method convert all uppercase characters to lowercase.

var x = 'Beta Labs';

x.toLowerCase(); // return "beta labs"

substr : substr() method return substrings from index (first argument ) to given no of characters (second argument). First argument is always index and second is no of characters. If second argument is missing, it will return substrings after first index. See examples

var x = 'betalabs';

x.substr(2); // return "talabs"

x.substr(4); // return "labs"

x.substr(04); // return "beta"

x.substr(22); // return "ta"

x.substr(44); // return "labs"

For IE8 and below, use substring

 

search: search() method search for a matched pattern between string and regular expression and return index of matched pattern.

var x = 'beta labs';

x.search('t'); // return 0

x.search('T'); // return -1

x.search(/\s/);

// return 4, i.e, white space found at 4th index

x.search(/\d/);

// return -1, i.e, no digit found

To know more about regular expressions, click here. JavaScript Regular Expressions

 

trim: trim() method trim extra whitespace from beginning and end.

var x = ' beta labs ';

x.trim(); // return "beta labs"

replace: replace() method is used to replace a single or multiple characters with a new characters. The first argument is replaced character, and second is replacing one.

var x = 'beta labs';


x.replace('b''B'); // return "Beta labs"

x.replace('labs''LABS'); // return "beta LABS"

x.replace(' ''-'); // return "beta-labs"

split: split() method splits a string to array

var x = 'beta labs';

x.split(' '); // return ["beta","labs"]
 

 

    

JavaScript Numbers can be integers (example 3) or whole numbers (example 3.14). JavaScript Numbers can perform addition, subtraction, multiplication, division and Modulus. Thus all arithmetic operations can be performed using JavaScript numbers. JavaScript Supports all numbers systems, including Binary, Octal, Decimal, and Hexadecimal numbers. A number starting with 0 is by-default octal in JavaScript. For example, 010 is 8 in JavaScript.

  •  var is used to declare numbers in JavaScript.
  • For fixed numbers, const is also used.
  • typeof operator can check datatype of numbers.

var a = 3// number;
var b = 3.6// number with decimal;
var c = 2e3// exponential number (2000)
var d = 0xa// number in hexadecimal
var e = 010// number in octal
var f = 0o10// number in octal
var g = 0b100// number in binary
var h = NaN// not a number
var i = Infinity// number more than 10308

 

Binary, Octal, Decimal and Hexadecimal Numbers

Here is a comparison of Binary numbersOctal numbersDecimal numbers and Hexadecimal numbers.


Number

Binary
(0-1)
(2 bit)

Octal
(0-7)
(8 bit)

Decimal
(0-9)
(10 bit)

Hexadecimal
(0-f)
(16 bit)

0

0

0

0

0

1

1

1

1

1

2

10

2

2

2

8

1000

10

8

8

10

1010

12

10

a

15

1111

17

15

f

16

10000

20

16

10


Numbers Method: Numbers Methods are used to convert a number to string, exponential, precision and fixed. Here are number methods with examples.

JavaScript Number Methods

Method

use

Example

toString()

convert number to string.

var x=6;
x.toString()="6";

toLocalString()

convert number to local string.

var x=6;
x.toLocalString()="6";

toExponential()

convert decimal to exponential notation.

var x=6;
x.toExponential()="6e+0";

toPrecision(1)

convert number to Precise .

var x=1.23456;
x.toPrecision(1)="1";

toPrecision(2)

convert decimal to precision 2 .

var x=1.23456;
x.toPrecision(2)="1.2";

toPrecision(3)

convert decimal to precision 3 .

var x=1.23456;
x.toPrecision(3)="1.23";

toFixed()

to convert a number to string with fixed decimal value

var pi=3.1416;
pi.toFixed(); // "3"
pi.toFixed(1); // "3.1"
pi.toFixed(2); // "3.14"
pi.toFixed(3); // "3.142"

String to Number in JavaScript: JavaScript variables can be strings or numbers. Like var x="5" is string, but var y=5 is number. Both can be used in arithmetic operations. Except addition, all arithmetic operations are possible with x and y. Functions to convert string to number.

  1. Number Function

  2. parseint Function
  3. parsefloat Function

Number Function: Number Function can convert string to numbers. Number Function can convert both floating/decimal and non-floating/integers. But if a string contains string character like alphabets or special character, number function will return NaN.

var a = '100';
var b = '100.5';
var c = '100px';
var d = 'abc100';

Number(a); //100
Number(b); //100.5
Number(c); //NaN - Not a Number
Number(d); //NaN - Not a Number

 


parseInt Function

parseInt Function can convert string to numbers, but non-floating/integers values only. parseInt can also convert binary, octal and hexadecimal to decimal numbers.

var a = '100';
var b = '100.5';
var c = '100px';
var d = 'abc100';

parseInt(a); //100
parseInt(b); //100
parseInt(c); //100
parseInt(d); //NaN - Not a Number

parseInt function is also used to convert decimal to binarydecimal to octal and decimal to hexadecimal numbers. To do this, pass second parameter in parseInt function as 2 for binary8 for octal, and 16 for hexadecimal. See example.


var a = '100';
var b = '100.5';
var c = '100px';
var d = 'abc100';

parseInt(a); //100
parseInt(b); //100
parseInt(c); //100
parseInt(d); //NaN - Not a Number

 
parseFloat Function
parseFloat Function can convert string to numbers, floating/decimals and non-floating/intergers both. parseFloat can also convert binary, octal and hexadecimal to decimal numbers.

var a = '100';
var b = '100.5';
var c = '100px';
var d = '100.5px';
var e = 'abc100';

parseFloat(a); //100
parseFloat(b); //100.5
parseFloat(c); //100
parseFloat(d); //100.5
parseFloat(e); //NaN - Not a Number

isNaN, is Not a Number Function

JavaScript isNaN function returns a boolean value. For example, isNaN("2") is false and isNaN("a") is true. Even isNaN(NaN) is also true.


isNaN(NaN); // returns true
isNaN(1); // returns false
isNaN('1'); // returns false
isNaN('a'); // returns true
isNaN('2a'); // returns true

isFinite

isFinite function tells whether a number is finite or not. In JavaScript, number less than 1e308 or 1e+308 are finite numbers. Numbers greater than 1e308 are Infinite, for example, 2e308 and more are infinite numbers in JavaScript.


isFinite(Infinity); // false
isFinite(2e308); // false
isFinite(1e308); // true
isFinite(1e307); // true
isFinite(123); // true

- Never starts a number with 0.
- Floating numbers can have maximum 16 characters after decimal.
- Binary i.e.0b100 and Octal 0o100 are not supported in all browsers.


Tuesday, September 29, 2020

JS Datatypes | Operators

JavaScript Datatypes


Datatypes in javascript mean the type of data stored in a variable.

As JavaScript is loosely typed scripting language, there is no typecast in javascript. JS supports dynamic typing. We can create any type of data using a single variable i.e. var.

var means a variable that can store any type of data. Datatype of variable is not declared.

Declaring var means creating a new variable in memory with the variable name after white-space. Assignment Operator (=) means assigning value to variable declared.

We can also use const and let to declared variables.

Datatypes in JavaScript

  1. Primitive Data Types
  2. Reference Data Types

Primitive Datatypes in JavaScript

Primitive datatypes are the basic or common data types in javascript. Like stringnumbersbooleanundefined, and null. They are very commonly used data types.

var is used to declare primitive datatypes in javascript.

Primitive Type

Data Meaning

var x;

undefined

var x=undefined;

undefined

var x=null;

null type data

var x=3;

Data Type is number.

var x=3.5

Data Type is number with decimal

var x="3"

Data Type is string

var x='3'

Data Type is string

var x="HELLO"

Data Type is string

var x=true

Boolean data type

var x=false;

Boolean data type

Strings

Anything written in single and double quotes is strung in javascriptStrings are used to store name, email, city name, password, etc in javascript. JavaScript String

     var name="js string";      

Numbers

JavaScript Numbers are used to perform Arithmetic Operations (+,-,*,/,%). Numbers are written without quotes. JavaScript Numbers.

        var num=20;

Boolean

JavaScript Boolean are true and false. Booleans are used in conditions, comparison etc.

        var t=true;


    var f=false;    

Undefined

JavaScript Undefined means any variable whose value is not assigned yet. Anything variable whose value is not assigned is undefined.


     var u;

     var t=undefined;  

Null

JavaScript null is a special object with empty value. null is used where value is defined, but still it is not there. It is also used in exception handling.

        var u=null;


Reference Data Type in JAVASCRIPT

Reference are datatypes based on primitive. Like ArrayObject and Functions. Everything is JavaScript is either a primitive datatype or Object. Even Arrays and Functions are objects, but they are build-in objects.

var is also used to declare reference datatypes.


Reference Data Type

Meaning

var x=[ "Jan", "Feb", "Mar" ]

Array

var x={ "name" : "ABC", "age" : "22", "gender" : "male" }

Object

var x=function(x,y){ return x+y;}

Function Expression

function sum(x,y){ return x+y;}

Function Declaration

var x=new Date();

Date

var x=/^[0-9]{6}$/

Regex


typeof Operator

typeof operator in javascript is used to check datatype of a variable. It can return string, number, boolean and undefined. For reference type and null, typeof operator will return object.

    var x;                 // undefined
    var y=9;               // number
    var z="Tech Altum";    // string
                                                                           
    typeof(x) and typeof x will return undefined,
    typeof(y) and typeof y will return number,
    typeof(z) and typeof z will return string;


JavaScript Operators


Javascript Operators are used to assign, add, subtract, compare variables value. JavaScript is having Arithmeticlogicalassignment and comparison operators.

JavaScript has binaryunary, and ternary operators.

Binary operators required two operands, one before and one after the operator.  x+y=z

Unary operators required only one operand, either before or after the operator.  i++

Type of Operators in Javascript

  1. Arithmetic Operators
  2. Logical Operators
  3. Assignment Operators
  4. Comparison Operators
  5. Conditional Operator
  6. Bitwise Operators

Arithmetic Operators

An Arithmetic Operator is used to perform Arithmetic operations between values. Like Addition, Subtraction, Multiplication, Division etc

Arithmetic operators in JavaScript

Operator

Description

Example

+

Addition

2+3=5

-

Subtraction

5-3=2

*

Multiply

2*3=6

/

Divide

6/3=2

%

Modulus, check reminder

6%3=0

++

Increment, y++ means y = y+1

var y=2; ++y; y=3

--

Decrement, y-- means y = y-1

var y=2; --y; y=1

Logical Operators

Logical Operators are used to check logic between two operators. and (&&)or (||) and not (!) are logical operators.

Logical Operators in JavaScript

Operator

Description

Example

&&

and, when both are correct

2 < 5 && 2> 1 is true

||

or, when any one is correct

var x=2, 2>5 || x==2 is true

!

not

!(2==3) is true

Assignment Operators

Assignment operators are used to assign some value to js variables. =, +=, -=, *=, /= are all assignment operators in javascript.

Assignment Operators in JavaScript

Operator

Description

Example

=

Assignment

x=2; means x is 2

+=

Addition Assignment

var x=2; x+=2 means x=x+2

-=

Subtraction Assignment

var x=2; x-=2 means x=x-2

*=

Multiplication Assignment

var x=2; x*=2 means x=x*2

/=

Division Assignment

var x=2; x/=2 means x=x/2

Comparision Operators

Comparison operators are used in a statement to compare two values.

Comparison Operators in JavaScript

Operator

Description

Example

==

Equal to

2=="2" is true

===

Strict equal to

2==="2" is false

!=

not equal

2!=1 is true

!==

not strict equal

2!=="2" is true

> 

greater than

2> 5 is false,
& 2 <5 is true

>=

greater than or equal to

3>=3 is true

< 

less than

1< 3 is true

<=

less than or equal to

2<=2 is true

Conditional operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is false. This operator is frequently used as a shortcut for the if statement.

 function getFee(isMember) {

    return (isMember ? '$2.00' : '$10.00');
  }
  console.log(getFee(true));
  // expected output: "$2.00"
  
  console.log(getFee(false));
  // expected output: "$10.00"
  
  console.log(getFee(null));
  // expected output: "$10.00"
  

Bitwise operator 

Like C, C++, Java, Python, and various other languages, JavaScript also supports bit-wise operations. In JavaScript, a number is stored as a 64-bit floating-point number but the bit-wise operation is performed on a 32-bit binary number i.e. to perform a bit-operation JavaScript converts the number into a 32-bit binary number (signed) and perform the operation and convert back the result to a 64-bit number.

<script>  
    var a = 4;  
    var b = 1;  
      
    document.write("A & B = " + (a & b) + '<br>');  
    // expected output: 0

    document.write("A | B = " + (a | b) + '<br>');  
    // expected output: 5

    document.write("~A = " + (~a) + '<br>');  
    // expected output: -5
</script>