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>


JS Variables | Scope

Variables in Javascript

variable or var is a storage area used to store a value in memory. To create a variable in javascriptvar keyword is used. var is a reserved keyword in javascript, used to create variables. We can also create a variable without using var in javascript, but it is not recommended.

JavaScript variables are loosely typed. Means a variable x (var x) can store any type of data, like string, number, function, boolean, undefined, null, array or object.

 

JavaScript Variables

Variables are always initialized first with var keyword.

For exp var x means a variable named x is initialized.

To assign a value in variable, = or assignment operator is used, followed by value.

Example

<script>


    var x="Beta-Labs";      // value of x is "Beta-Labs";
    var y='Beta-Labs';      // value of y is "Beta-Labs";
 var z=9;                // value of z is 9 numeric.
    var a=2, b=3, c=5;      // multiple variables in single line
    var u;                  // u is undefined

</script>

Change value of variable

To change the value of a variable, assign a new value to the same variable.


var x="hello";

console.log(x);        //  "hello" 

x="hola";

console.log(x);        // "hola"     

Note: var keyword is used to declare a variable. To change the value of variable, there is no need to use var keyword again, only the variable name is enough.


Variable naming convention in JavaScript

To declare a variable in javascript, there are some rules. Here are some rules used to declare variables names in javascript.

  • variables names cannot include javascript reserved keywords, like var, for, in, while, true, false, null, class, let, const, function etc.
  • variables cannot start with numbers and hyphenuse alphabets or underscore(_).
  • variables can have strings followed by numbers, like x1 and x2 are allowed but 1x, 2x is not allowed.
  • For separation in variable names, use underscore (_) or camel casingdo not use hyphen (-) separation and white space, i.e, user_name is validusername is also valid, but user-name is invalid.
  • variables names are case sensitive, i.e, x1 and X1 are different.


Strict Mode

ECMAScript 5 includes strict mode in javascript. "use strict" string is used to follow strict mode. In strict mode, var is compulsory, but in sloppy mode, we can also create variables without var keyword.

<script>                                

    "use strict";   
    var x1="beta labs";          // allowed in strict mode
    x2="javascript";             // not allowed in strict mode
     
   
    forvar i=1;i<=10;i++){}    // allowed,
    for( i=1;i<=10;i++){}        // not allowed, i is not declared
   
    var x=10;                    // allowed
    var y=010;                   // not allowed, it is octal notation
   
 </script>

Sloppy Mode

By default javascript is written in sloppy modeSloppy mode allows us to create a variable with or without var keyword.

<script>            
    var x1="Beta Labs";          // allowed 
    x2="javascript";             // also allowed 
</script> 

Variable Hoisting

JavaScript Hoisting is the process to move all variables and functions to the top of the code block or scope, even before execution. Variable Declaration is hoisted, but the variable assignment is not hoisted. This means, a variable x declared at any point can have an undefined value before the assignment, but after assignment, the variable value can be string or number defined.

<script>

    console.log(x);       // return undefined

    var x="hello js";      

    console.log(x);        // return "hello js"

</script>    

It is recommended to declare variables and assign values at the top to avoid variable hoisting issue.


Scope in JavaScript

Scope in JavaScript refers to the accessibility or visibility of variables. That is, which parts of a program have access to the variable or where the variable is visible.

There are three types of scope in JavaScript:

  1. Global Scope:
  2. Function Scope
  3. Block Scope

Global Scope: Any variable that’s not inside any function or block (a pair of curly braces), is inside the global scope. The variables in the global scope can be accessed from anywhere in the program.

Local Scope or Function Scope: Variables declared inside a function is inside the local scope. They can only be accessed from within that function, that means they can’t be accessed from the outside code.

Block Scope: ES6 introduced let and const variables, unlike var variables, they can be scoped to the nearest pair of curly braces. That means, they can’t be accessed from outside that pair of curly braces. 


A variable in javascript can be local or global variable based on its scope. Variables declared outside function are global variables and variable declared inside function are local variables.

Global Variables

Variables declared outside function are global variablesGlobal variables have a global scope. This means a variable in <script> tag is by default globalGlobal Variable once declared can be used anywhere, even inside a function.

var x="hello js";        // global variable

var y=88;                // another global variable
console.log(x);          // returns "hello string"
console.log(y);          // returns 88

function myFunction(){
    console.log(x)           // returns "hello string"
    console.log(y);          // returns 88
}

Local Variables

Variables declared inside functions are local variablesLocal Variables have local scope. This means they are accessible only within their function block, not outside.

Example: JavaScript Local Variables

function myFunction() {
  var x = 'local variable';
  var y = 'local variable';

  console.log(x); // returns "local variable"
  console.log(y); // returns "local variable"
}

myFunction(); // call the function

console.log(x); // x is not defined
console.log(y); // y is not defined

 

Example: JavaScript global Variables

function myFunction(){
        
    var x="local variable";
    y="global variable";    
         
    console.log(x);    // returns "local variable"
    console.log(y);    // returns "global variable"
}

    myFunction()        // call the function
     
    console.log(x);    // x is not defined
    console.log(y);    // y is defined

Note: In the Example above, JavaScript allows variable declaration without var keyword. You must assign a value when you declare a variable without var keyword. Scope of the variables declared without var keyword become global irrespective of where it is declared. Global variables can be accessed from anywhere in the web page.


Declaring JavaScript global variable within function

To declare JavaScript global variables inside function, you need to use window object. For example:


    window.value = 90;

Now it can be declared inside any function and can be accessed from any function. For example:


function m() {
  window.value = 100; //declaring global variable by window object
}

function n() {
  alert(window.value); //accessing global variable from other function
}

 

let and Const block scope

let and const were introduced in ECMA 6. let is used to declare temporary values with block scope, inside {} . Whereas const is used to declare permanent values, which can't be change. Like value of pi, e, G and other constants.

JavaScript let

JavaScript Let is used to declare variable in block scope only. 

{
  let x = 'user'// to store values in block scope
}
var i = 2// global scope
if (i == 2) {
  let i = 3// block scope
  console.log(i); // 3
}
console.log(i); // 2

JavaScript const

JavaScript const is used to declare fixed values that are not changeable.

const pi=Math.PI;    // pi is a constant, and can't be changed

const user="avi";

user="xyz";  //Assignment to constant variable.

Although it is not compulsory to start variables with var keyword, but still we prefer var. let and const are supported in IE 11 and above, edge, firefox 36 and above, chrome 21 and above, safari 5.1 and above.
 

Difference between varlet, and const

JavaScript has three different keywords to declare a variable, which adds an extra layer of intricacy to the language. The differences between the three are based on scope, hoisting, and reassignment.

You may be wondering which of the three you should use in your own programs. A commonly accepted practice is to use const as much as possible, and let in the case of loops and reassignment. Generally, var can be avoided outside of working on legacy code.

 

 

Saturday, September 26, 2020

JS Introduction

JavaScript is a client-side scripting language of web developed by Netscape in 1995 with the name LiveScriptJavaScript is used to build interactive websites with dynamic features and to validate form data. JavaScript is high-leveldynamic and browser interpreted programming language, supported by all modern web browsers. Apart from web browser, JavaScript is also used to build scalable web applications using Node JS. JavaScript is also being used widely in game development and Mobile application development.

JavaScript is also known as the Programming Language of web as it is the only programming language for Web browsers. JavaScript is an object-based scripting language which is lightweight and cross-platform. The programs in this language are called scripts. They can be written right in a web page’s HTML and run automatically as the page loads. Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run. The browser has an embedded engine sometimes called a “JavaScript virtual machine”.

 

JavaScript Applications

JavaScript is the widely used programming language, all over the world. It has the largest open-source package repository in the world (npm). Every type of software uses JavaScript, including the server code (Node.js), productivity apps, 3D games, robots, IoT devices. JavaScript has achieved the goal, set by Java a long time ago: write once, run anywhere. There are various JavaScript uses in different segments.

 

JavaScript Facts

Some popular facts about JavaScript.

  • JavaScript is the only client-side scripting (i.e. browser interpreted) language.
  • JavaScript can build interactivity Websites.
  • JavaScript is Object-Based.
  • JavaScript is Case Sensitive.
  • JavaScript can put dynamic content into a webpage.
  • JavaScript can react to events like Clickmouse overmouse outform submit etc known as JavaScript Events.
  • JavaScript can validate form data.
  • JavaScript can detect user browser using navigator Object.
  • JavaScript can be used to create cookies.
  • JavaScript can add cool animation to a webpage JS timing functions.
  • JavaScript can detect user physical location using HTML5 Geolocation API.
  • JavaScript can also be used to draw shapes, graphs, create animations and games development using HTML5 Canvas.
  • At present, JavaScript has lot of libraries and framework, exp JQuery, Angular JS, React JSBackbone JS etc, thus making JavaScript more popular.
  • JavaScript can also be used in developing server-side application using Node JS.
  • Popular Editors like, Brackets and VS Code are written in JavaScript. 


JavaScript History

WWW was formed in 1990. Initially, it was a bunch of web-pages linked together. But soon people want more interactive websites. So on-demand of Netscape, Brenden Eich, (inventor of JavaScript) in 1995 invented a prototype based (Classless) language for their Navigator Browser. Initially, it was called "LiveScript", but later on renamed as " JavaScript ".

In today's world, JavaScript is the Topmost demanding technology as it can handle both front end and Back-end.

 

JavaScript Engines

JavaScript Engines are the computer programs used to interpret JavaScript into machine code. JavaScript was primarily developed for browser environment only, but non-browser environments are also using JavaScript now, like Node JS, and Deno.

There are so many JavaScript engines available, but the most popular JavaScript Engine is Chrome V8 is open source and the most popular JavaScript Engine. Being the fastest JavaScript Engine, a non-browser environment like Node JS is also using Chrome V8 Engine. SpiderMonkey is the First JavaScript Engine developed by Brendan Eich at Netscape. It is currently maintained by Mozilla Foundation.

 

How to write JavaScript in Webpage

Based on where JavaScript coding is written, JavaScript is categorized in three parts, Internal JavaScriptExternal JavaScript, and Inline JavaScript. 

Internal JavaScript : In Internal JavaScript, JavaScript coding is written inside head or body within <script> tag.

<script>
  document.write('Hello Javascript');
</script>                                  


External JavaScript In External JavaScript, javascript code is written in external file with .js extension and then linked with script tag. Here is an example of external js. 

<script src="custom.js"></script>                   


Inline JavaScript : In Inline JavaScript, javascript code is written directly inside html tags. All though this is not recommended. Script should be written in separate file( external) or in <script> tag. See example 

<button onclick="alert('Hello JS')">Check</button>

<marquee onmouseover="stop()" onmouseout="start()">Hello Javascript</marquee>

<a href="javascript:void(0)" onclick="print()">Print</a>

 

How to run JavaScript code

JavaScript can be placed on both Head or Body tag of our HTML Page using <script> tag. When Webpage loads, script code executes and can slow down page speed.

Write JavaScript coding in head tag only when we want script to execute first, like to disable text selection, page redirection, notifications etc. Rest all script like JQueryAngular JS or custom JS should be written just before body closing tag. This can load DOM content first, then scripts will execute, and hence optimize webpage performance.

 

Run JavaScript  Code in Head 

<!DOCTYPE html>

<html>
  <head>
    <title>Javascript</title>
    <meta charset="utf-8" />

    <script>
      // Write Script here
    </script>

  </head>

  <body>
    // body content
  </body>
  
</html> 

Run JavaScript Code in Body 

<!DOCTYPE html>

<html>
  <head>
    <title>Javascript</title>
    <meta charset="utf-8" />
  </head>
  <body>
    // content in body

    <script>
      // Write Script here
    </script>

  </body>
</html>

 

JS console.log()

To print JavaScript output in console window of web browser, use JavaScript and use console.log() function. console is a JavaScript Object and log() is a Function of console object. Any syntax error in JavaScript is shown in console window. Also global variables and functions are accessible in console.

To view console window, use these shortcuts.

Console Shortcuts

Browser

Console Shortcut for Windows / Linux

Console Shortcut for Mac

Chrome

Ctrl + Alt + j

Cmd + Alt + j.

Firefox

Ctrl + Shift + k

Cmd + Alt + k

Internet Explorer

Ctrl + 2 or F12

NA

Edge

Ctrl + 2 or F12

Cmd + Alt + j

Safari

Ctrl + Alt + c

Cmd + Alt + c

Print in JavaScript Console

hello string

<script>
  var x = 'hello string';

  console.log(x);
</script>

error found

<script>
  console.error('error found');
</script>

To clear console, use console.clear()

 

JavaScript Dialog Box

JavaScript supports three dialog box. These dialog boxes are build in functions of window object. Three dialog box in JavaScript are alert, prompt and confirm.

 

JavaScript Alert, alert(): Alert box, i.e alert() or window.alert() is used to show output in dialog box. For alerts, use alert(). Alert generally block the code, thus next code block will run only after alert is closed. 

Alert Box Example

<script>
  var x = 'hello js';

  alert(x);
</script>

JS Prompt, prompt(): prompt() or window.prompt() dialog box is used to receive input from user.

Prompt Box Example

<script>
  var x = prompt('Enter Name');

  alert(x);
</script>


JS Confirm, confirm(): confirm() or window.confirm() dialog box is used to get confirmation from user. This will show Ok or Cancel in dialog box.

Confirm Box Example

<script>
  var x = confirm('Press Ok or Cancel');

  alert(x);
</script>

 

JavaScript Comments

Comments are used to write explanations, hints, and to stop execution of code. JavaScript use two comments syntax. One is Single line comment, and second is Multi-line comment.

Single Line Comment in JavaScript: Single Line comments in JavaScript are used using //. This will comment only right hand side of code.

Example

<script>
  // single line comment
</script> 

Multiline Comment in JavaScript: JavaScript Multiline Comments are recommended comments as they have opening and closing. Multiline Comments are used using /* opening and */ closing, same like css comments. 

Example

<script>
  /* Multiline Comment */
</script>

Always prefer Multiline comments in JavaScript for production. Single line comments in JavaScript are good for development purpose. But in production, they can create errors after JS Minification.

 

Noscript Tag

<noscript> tag is an html element used when JavaScript is disabled in web browser. If JavaScript is enable, noscript tag is invisible.

Example

<noscript> 
    Please Enable Javascript 
</noscript> 

In HTML5, type and language attributes from script tag has been deprecated. So we can write JavaScript code directly in script tag without any attribute.