What is Java Scrip 1

Embed Size (px)

Citation preview

  • 8/3/2019 What is Java Scrip 1

    1/22

    What is JavaScript?

    JavaScript is scripting language used for client side scripting. JavaScript developed by Netscape

    in 1995 as a method for validating forms and providing interactive content to web site. Microsoft

    and Netscape introduced JavaScript support in their browsers.

    Benefits of JavaScript

    Following are the benefits of JavaScript.

    associative arrays

    loosely typed variables

    regular expressions

    objects and classes

    highly evolved date, math, and string libraries

    W3C DOM support in the JavaScript

    Disadvantages of JavaScript

    Developer depends on the browser support for the JavaScript

    There is no way to hide the JavaScript code in case of commercial application

    Creating your first JavaScript Program

    In the first lesson we will create very simple JavaScript program and run in the Internet Explorer.

    This example simply displays "Welcome to JavaScript World!" message in the browser.

  • 8/3/2019 What is Java Scrip 1

    2/22

  • 8/3/2019 What is Java Scrip 1

    3/22

    JavaScript Statement

    The JavaScript language supported Two type Condition.

    1.if statement

    2.Function

    if Statement

    The if statement is used to make decisions in JavaScript. Boolean operators are also used in

    along with the if statement. The if statement is the most used features of JavaScript. It is

    basically the same in JavaScript as it is in other programming languages.

    Example

    my program successfully completed

    Function

    The function keyword identifies as a function. The parameters in the parenthesis ( ) provide a

    means of passing values to the function. There can be as many parameters separated by

    commas as you need. This is perfectly ok to have a function with no parameters. These

    parameters are variables which are used by the JavaScript statements inside the curly braces { }.

    The variable keyword is not needed to declare the parameters in a function as variables becausethey are automatically declared and initialized when the function is called. The function can return

    a value by using the return keyword.

    Example

  • 8/3/2019 What is Java Scrip 1

    4/22

    function prod(a,b){

    var x=a*b

    return x;

    }

    var mul=prod(2,5);

    document.write("multipication:"+mul);

    Conditional JavaScript if-else Statement

    The JavaScript Conditional Statement used to different actions and used to based on different

    conditions. you want to execute some code if a condition is true and another code the condition is

    not true, use the if....else statement.

    Example

    script type="text/javascript">

    var a = new Date()var time = a.getHours()

    if (time < 20)

    {

    document.write("Good morning!")}

    else

    {

    document.write("Good day!")}

  • 8/3/2019 What is Java Scrip 1

    5/22

    JavaScript Variables

    .Every piece of data is known as a value. When a value is referred in a statement, it is called a

    literal value. For the same reason people are identified by names as opposed to "human" or

    "person", literal values can be named in order to make repeated reference to them practical,

    efficient and readable. These names are called variables.

    Declaring and Initializing the Variables

    var num // declare variable, has null value

    num = 20 // assign a value, null value is replaced

    //OR

    var num=20 // declare AND assign value (initialize)

    var a,b,c,d //multiple variables may be declared simultaneously

    var a = 5, b = 6, c = 7,d=8 //multiple variables may be initialized simultaneously

    Variable Names

    Variable names cannot contain spaces, begin with a number and can not be used the underscore

    (_) . JavaScript Variable name can not use any reserved keywords. The two words can either be

    separated by an underscore (my_variable) or (myVariable).

    Variable Scope

    There are two types of Variable scope:-

    1. Globle scope Variable,

    2 . Local scope Variable.

    1.Globle scope Variable:- A variable declared or initialized outside a function body has a global

    scope, making it accessible to all other statements within the same document.

    2. Globle scope Variable:-A variable declared or initialized within a function body has a local

    scope, making it accessible only to statements within the same function body.

    [NOTE:- If a variable is initialized inside a function body but the var keyword is left off, the

    variable has a global scope and is only accessible after the function containing it is invoked. It is

    safer to always use the var keyword ]

    Java script Data type

    Data Type:- A data type is defined by the value assigned to it . A variable could be a number on

    one line, then assigned a string value and later be assigned an object reference. JavaScript

    would change its data type dynamically .It also represent the data's nature. Data is directly

    treated on those data types and calculate up on the works .

  • 8/3/2019 What is Java Scrip 1

    6/22

    There are two types of the data types, As follow:-

    1.Primitive data types

    2.Compositive data types

    1.Primitive data types:- Primitive data types are the simplest building blocks of a program.

    There are following types :-

    numeric:-JavaScript supports both integers and floating point numbers .Integers are

    whole numbers and it does not support the decimal numbers .Such as : 145 . Floating

    point numbers are fractional numbers or decimal numbers . Such as : 12.50

    string:- String is a collection of characters enclosed in either single quotes and double

    quotes .If the string starts with a single quotes and it must end with single quotes .If the

    string starts with a double quotes and it must end with double quotes . Such as :

    'Welcome to JavaScript'

    or "Welcome to JavaScript".

    Boolean:-Boolean literals are logical values that have only one of two values, true or

    false. It used to conditional sanitations. Our statements

    are checked true or false then we use the Boolean variables.

    null:-The null value represents no value that means strings are empty .

    undefined:- A variables to be declared but given no any initial value then it runtime error

    display

    Example for :-This example is represent the sum of two floating numbers and print the messages

    in single quotes and double quotes.

    function showAlert()

    {

    var a=200.40;

    var b=10.50;

    var sum=0;

    sum=a+b;

    document.write(" sum= "+sum);

    document.write("\t\tHello\nworld!\n");

    document.write('\nWelcome to JavaScript');

    }

  • 8/3/2019 What is Java Scrip 1

    7/22

    showAlert();

    This program is used to Boolean expression and it display the numbers between 1 to 500 and if

    user to not enter the number then it display the you

    did not enter any number.

    var n=0;

    n=prompt("Enter a number");

    document.write("Your entered number is :"+n);

    if (n>=1 && n=10 && n=20 && n=30 && n=40 && n=100 && n

  • 8/3/2019 What is Java Scrip 1

    8/22

    What is String Number Operation?

    The JavaScript String is a loosely type language. This is not mean that it has no data types that

    the value of a variable or a JavaScript object property does not need to have a particular type of

    the value assigned, or that it should be always hold the same type of value. JavaScript also freely

    type-converts values into a type require by the context of their use. JavaScript being is the loosely

    typed and willing to type-convert still does not save the programmer from need to the think about

    the actual type of values that they are dealing with. A very common error in browser scripting. for

    example, it is to read the value property of a form control into which the user is expected to type a

    number and then add that value to another number. Because the value properties of form

    controls are strings if the even then character is sequence they contain represents a number of

    the attempt to add that string to a value, even if the value happens to be a number, results in the

    second value being type-converted into a string and concatenated to the end of the first string

    value from the from control. The problem arises from dual nature of the + operator used for the

    both numeric addition and string concatenation. which the nature of the operation performed is

    determined by the context, where only both the operation are numbers to start with the + operator

    perform addition. Otherwise it converts all of its operands to strings and does concatenation.

    Converting String:

    The String most often from the action + Operators. when one of its operators not a number. The

    easy way of getting the string that results from type-conversion is to concatenate a value to string.

    The alternative method of convert a value into a string to pass it is argument to the String

    constructor called as a function. Exam:-

    Var string Value= String(d);

    Converting Number:

    The Converting values to numbers especially to strings numbers, it is an extremely common

    requirement and many methods can be used. There are any mathematical operation except the

    concatenation addition operator will force type-conversion. So the conversion of a string to a

  • 8/3/2019 What is Java Scrip 1

    9/22

    number might entail performing a mathematical operation on the string representation of the

    number that would not affect the resulting number, such as subtracting zero or multiplying by one.

    var numValue =

    stringValue - 0;var numValue =

    stringValue * 1;

    var numValue =

    stringValue / 1;

    String in JavaScript

    The JavaScript language until now we have been focusing on the language constructs of

    JavaScript: if statements, loops, functions, etc. This primer are going to take a step back and

    cover the inner workings of some of the native JavaScript objects: Strings, Numbers and Arrays.

    Example:

    document.write(' Test'.indexOf('T'));

    document.write('This '.lastIndexOf('T'));

    document.write('This is

    test'.charAt(10));

    document.write('This programTest'.length);

    document.write(' program'.substring(1,

    10));

    document.write('my exam Test'.substr(7,

    10));

    document.write('my

    program'.toUpperCase());

    document.write(' first JavaScript

    program'.toLowerCase());

    document.write("
    ")

  • 8/3/2019 What is Java Scrip 1

    10/22

    Array in JavaScript

    Array is the basically just a list of items. Each item an array can be whatever you want, but they

    are usually related to one-another.

    Example:

    var students = ['amar', 'rani', 'vinod',

    'susil','santosh'];

    var suffixes = ['1st', '2nd', '3rd',

    '4th','5th'];

    for(var i=0; i

  • 8/3/2019 What is Java Scrip 1

    11/22

    document.write("mul:"+mul);

    document.write("divided:"+divided);

    document.write("modulus:"+modulus);

    About Conditional Statement

    First of all we write the code after that we want to perform the different actions for different

    decisions. We can use conditional statements in our code. Conditional statements in JavaScript

    are used to perform different actions based on different conditions.

    There are following types of Conditional Statements:-

    if statement:- It means the condition is true then our writing code is executed other wise

    our code is not execute .

    Syntax for the if statement:-

    if ( expression )

    {

    statement1

    statement2

    }

    if - else statement:- This statement is used to when the condition is true then our code

    to execute and when the condition is false then our written code is not execute.

    Syntax for the if - else statement:-

    if (expression)

    statement1

    else if (expression2)

    statement2

    else

    statement3

  • 8/3/2019 What is Java Scrip 1

    12/22

    if...else if....else statement -This statement is used to if you want to select one of many

    blocks of code to be executed .

    switch statement:-This statement is used to if you want to select one of many blocks of

    code to be executed.

    Syntax for the switch statement:-

    switch (expression)

    {

    case1:

    statement1

    break

    case2:

    statement2

    breakdefault:

    statement3;

    }

    This example is if - else statement. It display the first of all the sum of two numbers and check

    the condition after that it execute the code.

    function showAlert()

    {

    var a=20;

    var b=10;

    var sum=0;

    sum=a+b;

    document.write(" sum= "+sum);

    if(sum==3)

    {

    document.write("Condition is true");

    document.write("This is my first if statement program");}

    false

    {

    document.write("Condition is false");

    document.write(" This is my first if -else statement program");

    }

    }

  • 8/3/2019 What is Java Scrip 1

    13/22

    showAlert();

    This example is display to all months in a year for using the switch case:-

    var n=0;

    n=prompt("Enter a number between 1 to 12:")

    switch(n)

    {

    case(n="1"):

    document.write("January");

    break

    case(n="2"):document.write("Febuary");

    break

    case(n="3"):

    document.write("March");

    break

    case(n="4"):

    document.write("April");

    break

    case(n="5"):

    document.write("May");

    breakcase(n="6"):

    document.write("June");

    break

    case(n="7"):

    document.write("July");

    break

    case(n="8"):

  • 8/3/2019 What is Java Scrip 1

    14/22

    document.write("August");

    break

    case(n="9"):

    document.write("September");

    break

    case(n="10"):document.write("October");

    break

    case(n="11"):

    document.write("November");

    break

    default:

    document.write("December");

    break

    }

    Conditions In Java Script

    About JavaScript

    Java Script is Netscape's Cross - platform, Object - based Scripting language for Client and

    Server applications. It is a Case sensitive application. JavaScript programs are usually embedded

    directly in HTML files. The script executes when the user's browser opens the HTML file.

    JavaScript is different from the Java language. Now the biggest problem is the imperfect

    JavaScript implementations that today's browsers offer. Although all major browsers that are

    version 3.0 or higher include JavaScript code support, they deal with JavaScript differently. In

    fact, different versions of the same browser handle JavaScript differently. This makes it difficult tocreate a complicated JavaScript code that work across all browsers. So always check your pages

    on as many different browsers (and even platforms) as possible.

    The Simple Example to display the Sum of two Digits :-

  • 8/3/2019 What is Java Scrip 1

    15/22

    function showAlert()

    {

    val1=20;

    val2=10;document.write("sum="+(val1+val2));

    }

    showAlert();

    JavaScript code is embedded in HTML within a tag. It can be used to any number of

    JavaScript Statements. showAlert() is a function to use in JavaScript language. Val1 and Val2 is

    a data type. we take the value 20 and 10 in val1 and val2. Document.write is also a function to

    use print the Message and values. The result is 20 display on the Screen.

    Looping In Java Script

    What is JavaScript loop?

    The JavaScript loops used to execute the same block or code a specified number of times and

    while a specified condition. JavaScript loops Very often write code, you want the same block of

    code to run over and over again in a row. The Instead of adding several almost equal lines in ascript we can use loops to perform a task.

    JavaScript supported Two different type looping :-

    1.The For Loop

    2.The while Loop

  • 8/3/2019 What is Java Scrip 1

    16/22

    For Loop:

    The JavaScript for loop is used the know in advance how many times of the script should run.

    JavaScript loop Use a For loop to run time same block of code a specified the number.

    Example:

    var i=0

    for (i=0;i

  • 8/3/2019 What is Java Scrip 1

    17/22

  • 8/3/2019 What is Java Scrip 1

    18/22

    Javascript looping Break and continue

    There are two statements supported in javascript used in loop:- Break and continue

    Break:

    The JavaScript break command will break the loop and continue executing the code the follows

    after the loop.

    Example:

    var i=0for (i=0;i

  • 8/3/2019 What is Java Scrip 1

    19/22

    }

    JavaScript Functions

    What is JavaScript Function?

    Java script Function is nothing but it is a reusable code-block that is execute when the function is

    called. Function is defined in the head section of the code. The syntax of JavaScript function is as

    follows:

    function fname(prameter1,parameter2, ...)

    {

    JavaScript code 1

    JavaScript code 2

    ....

    }

    While defining JavaScript function its important to remember that the keyword function should be

    in lowercase other wise JavaScript won't understand it as function. If you write function in

    uppercase the code will generate error. In the JavaScript semicolon is optional but its better to put

    semi-colon as part of best practices. All the java script code are written inside the curly braces.

    Example:

    function showmessage(){alert("How are you");

    }

  • 8/3/2019 What is Java Scrip 1

    20/22

    onclick="showmessage()" >

    Function starts with the function keyword and code of the function is enclosed in {..} brackets.

    Functions are written inside the head section of the html document, because function does not

    execute when the page loads. The alert function displays the message "How are you", when you

    clicked on the button ("Click Here")..

    What is the use of JavaScript Functions:

    The java Script Function is very useful in writing the JavaScript code. It is used to group many

    JavaScript codes under one name. For example you can write a function to validate email

    address.

    Built-in functions

  • 8/3/2019 What is Java Scrip 1

    21/22

    JavaScript provides many built in functions that ease the development of JavaScript programs.

    Here are the list of the built-in JavaScript functions:

    JavaScript Build in Function Function Description

    alert() The alert() built-in function displays thealert dialog box.

    confirm()

    The confirm() built-in function display the

    confirmation dialog box. and ask the user

    to determine from the two option .

    focus()The focus() built -in function built thepointed object active and put the curser on

    the text field.

    indexOf()

    prompt()The prompt() built -in function display theprompt dialog box. Inquiring the user for

    input.

    select()The select() built -in function used to

    select the pointed object.

    write()The write() built in function used to write

    something on the document.

    Function arguments: Through variable you can pass argument to function. The out put of the

    function looks on the arguments given by you .

    Example:

    function myfunction(text)

    {

    confirm(text)

    }

  • 8/3/2019 What is Java Scrip 1

    22/22