Tuesday, September 29, 2020

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.

 


Wednesday, September 23, 2020

HTML iFrame | Video and Audio

Introduction to iframe

An iframe or inline frame is used to display external objects including other web pages within a web page. An iframe pretty much acts like a mini web browser within a web browser. Also, the content inside an iframe exists entirely independent of the surrounding elements. The HTML <iframe> tag defines an inline frame, hence it is also called as an Inline Frame.

The basic syntax for adding an iframe to a web page can be given with:

<iframe src="URL"></iframe>

The URL specified in the src attribute points to the location of an external object or a web page.


Setting Width and Height of an iFrame

The height and width attributes are used to specify the height and width of the iframe.

Example

<iframe src="hello.html" width="400" height="200"></iframe>

You can also use CSS to set the width and height of an iframe, as shown here:

<iframe src="hello.html" style="width: 400px; height: 200px;"></iframe>

Note: The width and height attribute values are specified in pixels by default, but you can also set these values in percentage, such as 50%, 100% and so on. The default width of an iframe is 300 pixels, whereas the default height is 150 pixels.

 

Removing Default Frameborder

The iframe has a border around it by default. However, if you want to modify or remove the iframe borders, the best way is to use the CSS border property.

The following example will simply render the iframe without any borders.

Example

 <iframe src="hello.html" style="border: none;"></iframe>

Similarly, you can use the border property to add the borders of your choice to an iframe. The following example will render the iframe with 2 pixels blue border.

Example

 <iframe src="hello.html" style="border: 2px solid blue;"></iframe>

 

Using an iFrame as Link Target

An iframe can also be used as a target for the hyperlinks. An iframe can be named using the name attribute. This implies that when a link with a target attribute with that name as value is clicked, the linked resource will open in that iframe. Let's try out an example to understand how it basically works:

Example

 <iframe src="demo-page.html" name="myFrame"></iframe>

<p><a href="https://www.beta-labs.in" target="myFrame">Open Beta-Labs.in</a></p> 


Embed YouTube video using iframe

You can also add a YouTube video on your webpage using the <iframe> tag. The attached video will be played at your webpage and you can also set height, width, autoplay, and many more properties for the video.

Following are some steps to add YouTube video on your webpage:

  • Goto YouTube video which you want to embed.
  • Click on SHARE under the video.
  • Click on Embed <> option.
  • Copy HTML code.
  • Paste the code in your HTML file
  • Change height, width, and other properties (as per requirement). 
iframe Important attribute
  • src: The src attribute is used to give the pathname or file name which content to be loaded into iframe.
  • name: It gives the name to the iframe. The name attribute is important if you want to create a link in one frame.
  • height: It defines the height of the embedded iframe, and the default height is 150 px.
  • width: It defines the width of the embedded frame, and the default width is 300 px.
  • frameborder: It defines whether iframe should have a border or not. (Not supported in HTML5).
  • allowfullscreen: If true then that frame can be opened in full screen.
  • sandbox: This attribute is used to apply extra restrictions for the content of the frame
    • allow-formsIt allows submission of the form if this keyword is not used then form submission is blocked.
    • allow-popups:  It will enable popups, and if not applied then no popup will open.
    • allow-scripts:   It will enable the script to run.
    • allow-same-origin:  If this keyword is used then the embedded resource will be treated as downloaded from the same source.
  • srcdoc: The srcdoc attribute is used to show the HTML content in the inline iframe. It overrides the src attribute (if a browser supports).
  • scrolling: It indicates that browser should provide a scroll bar for the iframe or not. (Not supported in HTML5) 


HTML5 - Audio & Video

HTML5 features include native audio and video support without the need for Flash. The HTML5 <audio> and <video> tags make it simple to add media to a website. You need to set src attribute to identify the media source and include a controls attribute so the user can play and pause the media.

Embedding Video

HTML5 Video tag or <video> is used to add videos on a webpage. Video tag supports mp4oggmov and H.264 files. To embed a video, create a video tag. src is compulsory attribute for video tag. controls attribute can add play/pause button, video timeline, mute button, volume controller, full screen, subtitles options on player. Here is the simplest form of embedding a video file in your webpage –

Example

 <video src = "intro.mp4"  width = "425" height = "240" controls>

        Your browser does not support the <video> element.   
 </video>

You can use <source> tag to specify media along with media type and many other attributes. A video element allows multiple source elements and browser will use the first recognized format.

Video Attribute Specification

The HTML5 video tag can have a number of attributes to control the look and feel and various functionalities of the control −

  • src: The URL of the video to embed. This is optional; you may instead use the <source> element within the video block to specify the video to embed.
  • width: This attribute specifies the width of the video's display area, in CSS pixels.
  • height: This attribute specifies the height of the video's display area, in CSS pixels.
  • controls: If this attribute is present, it will allow the user to control video playback, including volume, seeking, and pause/resume playback.
  • autoplay: This Boolean attribute if specified, the video will automatically begin to playback as soon as it can do so without stopping to finish loading the data.
  • loop: This Boolean attribute if specified, will allow video automatically to seek back to the start after reaching at the end.
  • autobuffer: This Boolean attribute if specified, the video will automatically begin buffering even if it's not set to automatically play.
  • preload: This attribute specifies that the video will be loaded at page load, and ready to run. Ignored if autoplay is present.
  • poster: This is a URL of an image to show until the user plays or seeks.


Embedding Audio

HTML5 Audio tag is used to play audio files, like mp3ogg and AAC. All browsers supporting audio tag are having built-in player. 

The easiest way to include Audio Tag in a webpage is to use audio tagsrc is compulsory attribute in audio tag. controls attribute can show control bar to user. User can play/pause, change timeline, mute, and increase the volume of audio playing using controls.

HTML5 Audio Example

<audio src = "sound.wav" controls autoplay>
        Your browser does not support the <audio> element.   
</audio>

You can use <source>; tag to specify media along with media type and many other attributes. An audio element allows multiple source elements and the browser will use the first recognized format. Audio Attribute Specification almost the same as the video. The HTML5 audio tag can have a number of attributes to control the look and feel and various functionalities of the control.