Thursday, August 17, 2017

JavaScript Basics

JavaScript is a scripting language which makes the webpages more interactive.


Like, adding a calculator or a quiz in the webpage, JavaScript is needed.

We require notepad ++ for writing JavaScript commands.

<Script> </Script>  tags should be added so that the browser will know which scripting language we are using.
Example:
<Script type = “javascript”> </Script> 

A variable is nothing but a placeholder.

X = Chocolate
Kids love X.
X is made from Cocoa.

Similarly, in JavaScript, the variable is represented as ‘var’.

var x = 25;
document.write(x);
Result: 25

Different types of variables:


The numbers  can be stored by declaring “var”.

The words can be stored by adding quotation marks “apple”

When you add words like:
var fruit = “Amanda said, “I like oranges””;

Result: <empty page>


We need to add escape characters so that it gets printed:
var fruit = “Amanda said, \“I like oranges\” ”;

Result: Amanda said, “I like oranges”.

We can use escape character if we need to escape something from the result.

In order to use variables and strings together, mention it with “+”.

var fruit = “Orange”;
var color = “Black”;

document.write(fruit + “is my favorite” );

Result: Orange is my favorite

Functions:

The function is defined with the function keyword.
You can use a function declaration and get real values when invoked.

function fruit()
{
alert(“Berry!”);
}
fruit();


In order to use function in HTML:

<form>
<input type =”button” value=”pineapple” onclick=”fruit()”>
</form>


Passing values into function


function fruit(x){

alert(“I love”+x);

}

fruit(“Apple”);
fruit(“Banana”);
fruit(“Cranberry”);


Passing multiple parameters in function:


function fruit(one, two){

document.write(one + “ is better than “+ two + “<br/>”);
}

fruit(“Cranberry”,”Blueberry”);
fruit(“Dog”,”Cat”);
fruit(“Rose”,”Jasmine”);

Result:  Cranberry is better than Blueberry
              Dog is better than Cat
              Rose is better than Jasmine


Return statement:


Return is to return the value passed by parameters in a function.

function addNumbers(a, b){
var c = a+b;
return c;
}
document.write(addNumbers(3,2));

Result:  5




Reference: https://thenewboston.com



No comments:

Post a Comment