JavaScript-KeyPoints - (1)



πŸ‘‰Key points to remember

✅Datatypes are not strongly typed
Whatever values you assign on the right-hand side, the left-hand side variable becomes of that data type.

var x = 10;
alert (typeof x);
O/P - Numeric

var x = "str"
alert (typeof x);
O/P - string

Datatypes of variables are defined by the value that is assigned during runtime.

✅3 Types of datatypes
Javascript primarily has 3 types of datatypes.
Numeric, string, bool

var x = 10.12 //this is numeric
Int and decimal both fall under numeric datatype, so it is difficult to judge whether you are assigning integer or decimal. 

✅Undefined
Undefined means a variable is declared but the value is not assigned to it.
var x;
alert(typeof x);
O/P - undefined

✅Null
If you want to define the absence of data and represent null.
var x = null;
alert(x);
O/P - Null

✅Access Level
In Javascript, we have only 2 scopes: Private and Global
var x = 10; 
//this variable is global throughout the page
function F1() {
    var x = 5;
//this variable is private to the function
}

In order to conclude, if the variable is private or global, javascript uses a lexical scope approach.

Lexical means depending on the position of the word, the meaning of the word can change.

Depending on the physical position of your variable declaration, javascript decides whether it's public or private.

In the above example, when JS compiler looks at "var x = 10", it considers "x" as a global variable.
When it looks at "var x = 5" and that "x" is inside function, it makes "x" as private. 

✅Use of "Strict" keyword
If you don't declare a variable using "var" and just assign a value to it, it becomes by default global, and no lexical scope approach is respected.

function F1(){
       x = 5;
}
F1();
alert(x);
//you can access this "x" outside, because it has now become global.

<Script>
     "use strict"
     Function F1() {
            x = 5;
     }
//this gives an error that can be viewed in developer tools.
"use strict" ensures that you do not have variables that is created just by assigning values. This prevents confusion during coding.

Also, without the usage of "Strict" keyword, you can have many global variables scattered across the page and it becomes difficult to maintain.

✅Javascript Hosting
In Javascript, variable declarations are hoisted. The meaning of hoist is to pull up.

alert(x);
//This gives an error in developer tools that x is not defined.

alert(x); 
var x = 10;
//This doesn't give an error, you get an alert as "undefined". This means that the variable exists, but it's not assigned value.

So, internally javascript has created code as shown below:
var x;
alert(x);
x = 10;

Variable declaration is automatically moved up before its usage, hence this concept is termed Javascript Hoisting. 

Comments

Popular posts from this blog

SQL-ForeignKeyConstraint-Page6

Javascript-OOPs(Part3)-Inheritance - (9)

OraclePLSQL-Page3