Next-Gen JS



What we are going to learn?


1. Introduction to Javascript
2. How Javascript Executes?
3. Printing Hello World Message.
4. Variables and Constants
5. Operators
6. Control Structures
7. Functions in Javascript
8. Arrays

1. Introduction to Javascript


What is Javascript


          Javascript is a dynamic scripting language, which originally was created to make static webpages more dynamic and reactive.


How web page works?




















What is Static Page?


          HyperText Markup Language      
          Native Language of a Web Browser
          Complete Static Language
          Does not change or modifies at run time



What is Dynamic Page?


          Dynamic page is a web page whose content can be updated or modified at runtime.
HTML can not be used to create a dynamic web content.

Is a programmin language which can be used with HTML to implement dynamic login within the web page.



What is Scripting Language?

          


















Server Side Execution





















Client Side Execution          



















What is Javascript?


          Dynamic Scripting Language
          Interpreted at runtime by Javascript Engine
          Works closely with HTML and CSS
          Can access and manipulate DOM



What we can do using Javascript?


          Add or update web content dynamically 
          Add or update styles dynamically 
          React to user actions or events 
          Store and access data within web browser 
          Send request over network to the server 
          Can use cookies to manage user profiling



Languages over Javascript?


          Transpilation:
          The process of converting Javascript based language code into Javascript code












--------------------------------------------------------------------------------------------------------------------------------------


2. How Javascript Executes?



Javascript Execution










        Chrome – v8 engine                               Node.js
        Firefox – SpiderMonkey                       -On a server machine
        IE – Chakra                                           - On a local machine
        Safari – SquirrelFish



Client Side Execution



















In Browser vs. In Host Execution




               In Browser                                          Vs                              In Host
  1. Can access and manipulate DOM                            Can’t access and manipulate DOM
  2. React to user actions or browser events                   Can’t react to browser events
  3. Store and access data within web browser               Can’t access browser or its storage
  4. Can’t access to local file system                               Can access to local file system
  5. Can’t access to operating system                              Can access to operating system
  6. Can’t access server database directly                        Can access server database direct
--------------------------------------------------------------------------------------------------------------------------------------

3. Hello World!

Setting Up Development Environment



















Adding Script to HTML



          Script Tag - separates the JS code from HTML code and helps JS engine to identify the JS code to execute.

<html lang="en">
<head> <title>Session 1</title> </head>
<body>
<script type=“text/javascript” language=“javascript”>
</script>
</body>
</html>



4 Different ways to display Message in JS



1.Using document.write()

<script>
document.write(“Hello World!”); </script>
<script>

2.Using alert()

<script>
alert(“Hello World”)
</script>

3. Using console.log ()

<script>
console.log(“Hello World!”); 
</script>

4. Using DOM API

<p id=“msg”> </p> 
<script> document.getElementById(“msg”).innerHTML=(“Hello World”); 
</script>

--------------------------------------------------------------------------------------------------------------------------------------


4. Variables and Constants

Variables:


          Variables are the memory locations assigned with specific names
that can store some data in it.

Variable declaration
let variable_name; | let message;

Assign value to variables
variable_name = value; | message = “Hello World”;

Initialization
let variable_name = value; | let message = “Hello World”;

How to declaring multiple variable? 
What is difference between “var” keyword and “let” keyword? 

Naming Conventions?


•Only letters, numbers and special symbol like ‘_’ and ‘$’ are allowed
•Can not start with numbers
•Multiple words can be written in camel case format.

Constants:


         Constants are the variables whose value once assigned, can not be changed or reassigned.

Constant declaration
const message = “Hello World”;
message = “Another Message”; - ERROR

Uppercase Constants
const RED_COLOR = “#F00”;
let bgcolor = RED_COLOR;

Mostly used to store hard code values in programs

Data Types in Javascript


1.Number – integer, float, NaN, Infinity
2.bigInt – larger number represented by n as suffix eg. 1032n
3.String – ‘string’, “string”, `string $, expression -`
4.Boolean – true / false
5.Null - represents nothing or empty value
6.Undefined – represents a unassigned variables
7.Object – complex data type
8.Function – complex data type

Data Types - Objects


•Object is variable which is a collection of one or more data in terms of key and value pair.
•Objects in JS are always represented in a {}
•Key should always be a string
•Value can be any valid value like number, string, another object or even a function
•each data member of a object can be accessed individually as obj-name.member-name 

obj-name = { 
         key:value, 
         key:value 
    }

Data Types - Function


•In Javascript function is a value which can be stores in a variable of type function.
•such function variable can be used as a function call to call the function 

let var = function(){} 

var -> will display the definition as a string 
var() -> will call the function in it.

Type Conversions

String Conversion:
          
         String (value) 

         let str = String(true) 
         let str = String(345) 
         alert(typeof(str)) -> string

Type Conversions:


Numeric Conversion

          Number (value) 

         let num = Number(“123”) -> 123 
         let num = Number(“ 123 ”) -> 123 

         let num = Number(“abc”) -> NaN 

        let num = Number(undefined) -> NaN 
        let num = Number(null) -> 0 

        let num = Number(true) -> 1 
        let num = Number(false) -> 0

Boolean Conversion

        Boolean (value) 

        let bool = Boolean(1) -> true 
        let bool = Boolean(0) -> false 

        let bool = Boolean(“ass”) -> true 
        let bool = Boolean(“”) -> false 

        0, “”, null, undefined, Nan -> false

--------------------------------------------------------------------------------------------------------------------------------------

5. Operators

Types of Operators:


           + addition                               > greater than
           - subtraction                           >= greater than equal to
           * multiplication                     < less than
           / division                                 <= less that equal to
           % mod                                    == equal to
       ** exponentiation                  != Not equal to 
                                                            === equal-equal to








  Cond 1          Cond 2      Cond 1 && Cond 2          Cond 1 || Cond 2              ! Cond1
True              True                    True                                 False                           False
    True              False                    False                                True                           False
    False             True                     False                                True                           True
    False             False                    False                                True                           True



let num = 10; alert(num) -> 10
num += 10; alert(num) -> 20
num *= 10; alert(num) -> 200
num /= 10; alert(num) -> 20




Conditional Operator:


Syntax: (cond) ? Value 1 : Value 2; 

let age = 30;

let msg = (age>18) ? “Adult” : “Child”;
Alert(msg); -> Adult

Nullish Coalescing Operator ( Next-Gen Feature ):

Syntax: variable1 ?? variable2

Returns the first defined value.

num1 = undefined;
num2 = 20;
msg = num1 ?? num2;
-> 20

num1 = 12;
num2 = undefined;
msg = num1 ?? num2;
-> 12

num1 = undefined;
num2 = undefined;
msg = num1 ?? num2;
->undefined

num1 = undefined;
num2 = undefined;
msg = num1 ?? Num2 ?? “AA”;
-> AA

Syntax: variable1 || variable2 

Returns the first truthy value.

num = 0;
num = num || 100;
-> 100

num = 10;
num = num || 100;
-> 10

num1 = 0;
num2 = 0;
msg = num1 || num2;
->0

num1 = undefined;
num2 = undefined;
msg = num1 || Num2 || “AA”;
-> AA

--------------------------------------------------------------------------------------------------------------------------------------

6. Control Structures

Types of Operators





















JS Interactive Dialogs:



Alert 

          It shows the small popup dialog called modal window with

•custom message and
•OK button. Once triggered, it waits for user to press OK Button.

alert(“Message”);




Prompt

          It shows the small popup dialog called modal window with –

•Text message
•Input field
•OK Button result = prompt(“title”, *“default value of input fields”+ ); Value of result will be –
•sring value : if input types by user in input field

•null : if nothing is typed





Confirm

          It shows the small popup dialog called modal window with –

•Question text
•OK Button
•Cancel Button let isConfirmed = confirm(“question or text”); Value of result will be –
•True : if OK Button is pressed

•false : if Cancel Button is pressed



--------------------------------------------------------------------------------------------------------------------------------------

7. Functions in Javascript


What is Function?


          Function is a group of one or more statements, collectively performing a particular task.                      In Javascript - Functions are values. They can be copied, assigned, passed as a parameter.



Function Declarations


1. Defining a function

function function_name(parameters…){
//code line 1..
//code line 2..
}

2. Calling a function

function_name();


Scope of Variables


Local Variables :

Variables declared within the function are local to that function and can not be accessed from outside it.

Global Variables :

Variables declared outside of any function, are global variables and can be accessed from within any functions as well as out side the functions.

Local variables with same name as of global variables, shadows the global variable inside its function.


Function Parameters


//Function Definition

function add(num1, num2 = 10)
{
let sum = 0;
sum = num1 + num2;
alert(“Addition : “ + sum)
}

//Function Calling

add(10, 20);


Return value from function

//Function Definition

function add(num1, num2 = 10)
{
let sum = 0;
sum = num1 + num2;
return sum;
}

//Function Calling

let sum = add(10, 20);
alert(sum)

Return value of function which return nothing is undefined

function demo() {
alert(“Hello”);
}
let val = demo(); -> undefined

Returning a long or multiline expression from function

return(
//Expression…
)


Function Expressions


Instead of defining a function block, we create a function and assign it to a variable. So it’s a statement not a definition.

let func = function(){
alert(“Expression Function”);
};

func();

let demo = func;
demo();


Call Back Functions

function ask( question, yes, no){
            if(confirm(question)){
                    yes();
            }else{
                        no();
            }
}

function ok() , alert(“Saved Successfully!”) -
function cancel() { alert(“Cancelled action!”) -
ask( “Do you want to save?”, ok , cancel );


Function Definition Vs. Function Declaration


    Function Definition                     Vs.             Function Declaration

Function definition is a block                       Function declaration is a statement

Can be called before or after                      Can be called only after execution
the definition                                               reaches the statement

function function_name(){ }                        let var = function(){ };

Does not ends with ;                                     Ends with ;


Arrow Functions 


Arrow function is a new syntax of writing function expressions, which more simple and concise.

let func = () => {};

let func = () => alert(“Arrow Function”);
let func = message => alert(message);
let func = (num1, num1) => num1 + num2;

let func = () => {
let sum = 10 + 20;
alert(sum)
};

let func = (num1, num2) => {
let sum = num1 + num2;
alert(sum)
};

--------------------------------------------------------------------------------------------------------------------------------------

8. Arrays

What is Arrays?


Array is an ordered collection of data where each element can be accessed using a unique index assigned to it starting from 0

let arr = [] -> Empty Array

let arr = [10, 20, 30, 40, 50];

Let arr = new Array(10,20,30,40,50);



Array Operations


Accessing individual elements

alert( arr[0]); -> 10
alert( arr[1]); -> 20

Updating individual elements

arr[2] = 300
arr[3] = 400

Adding new item

Arr[5] = 60

Getting length of an array

alert(arr.length) -> 6

Printing whole array

alert(arr) -> [10, 20, 30, 40, 50];
alert(Str(arr)) -> “10,20,30,40,50”

Copying array

let brr = arr;
alert(arr === brrr) -> true
alert(brr) -> [10, 20, 30, 40, 50];

Traversing Array


Option 1:

for(let i=0; i<arr.length; i++){
alert(arr[i]);
}

Option 2:

for(let item of arr){
alert(item)
}

Option 3:

for(let itemIndex in arr){
alert(“Item at”+itemIndex+” is : “ + arr[itemIndex]);
}

Array Functions


push(item)
pop()
shift()
unshift(item)

splice(index, deleteCount, [item1, tem2..])
slice(start, end)

indexOf(item)
lastIndexOf(item)

reverse()

foreach( (item, index, array) => {} )
find((item, index, array) => {} )
filer((item, index, array) => {} )
map((item, index, array) => {} )

split() -> String to array
join() -> array to String


Array.isArray(itemToCheck)