JavaScript
Javascript
Javascript is the programming language of HTML and the Web.
Javascript is easy to learn.
Operators
Assign values t variable to sum together.
var x = 5;
var y = 2;
var z = x + y;
var y = 2;
var z = x + y;
(=) the assignment operator gives a value to a variable.
(+) addition operator adds the numbers you given .
(*) multiplication operator multiplies the numbers.
var x = 5;
var y = 2;
var z = x * y;
var y = 2;
var z = x * y;
+= concatenate the the strings
when + operator is used in strings we call this as concatenate operator.
var txt1 = "What a very ";
txt1 += "nice day";
txt1 += "nice day";
What a very nice day
Adding strings and numbers
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;
var y = "5" + 5;
var z = "Hello" + 5;
10
55
Hello5
55
Hello5
If u add a string and a number the result will be strong strings.
Assignment
+= assignment operator adds a value to variable.
-= assignment operator substracts the value from a variable.
*= operator multiplies a variable.
/= assignment divides a variable.
%= assignments that assigns a remainder for a variable.
Data Types
var length = 16; Number
var lastName = "Johnson"; String
var x = {firstName:"John", lastName:"Doe"}; Object
var lastName = "Johnson"; String
var x = {firstName:"John", lastName:"Doe"}; Object
JavaScript is evaluated from left to right.
Strings are wriiten within quotes it can be double quote or single. both ways are acceptable.
Numbers can be written with decimal or without.
Numbers that are so long and so short can be written in scientific natation.
Booleans are used only as yes or no conditions.
Arrays are written with square brackets and items are seperated by using commas.
Objects are written by using curly brackets.
Functions
JS Functions is a block code designed to perform particular task.
function myFunction(p1, p2) {
return p1 * p2; }
Function syntax
A Javascript function is defined with the function followed by parantheses () or by name.
function name(parameter1, parameter2, parameter3) {
}
Invocation
Functions
JS Functions is a block code designed to perform particular task.
function myFunction(p1, p2) {
return p1 * p2; }
Function syntax
A Javascript function is defined with the function followed by parantheses () or by name.
function name(parameter1, parameter2, parameter3) {
}
Invocation
The code inside the function will execute when "something" invokes (calls) the function:
Return
When JavaScript reaches a return statement, the function will stop executing.
If function invoked, it will return to execute the code ater invoking statement.
var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b}
function myFunction(a, b) {
return a * b; // Function returns the product of a and b}
Objects
JavaScript variables are containers for data values.
Objects are variables too. But objects can contain many values.
This code assigns many values to a variable.
var car = {type:"Fiat", model:"500", color:"white"};
Definition
We create a JavaScript object with an object literal:
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
spaces and breaks are not important.
Properties
The name:values pairs in JavaScript objects are called properties:
We can access object properties in two ways.
objectName.propertyName
eg:- person.lastName;
objectName["propertyName"]
eg:-person["lastName"];
Methods
Objects can also have methods.
Methods are actions performed on objects.
Methods arestored in properties as function definition.
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
Accessing object methods
objectName.methodName()
name = person.fullName();
Events
An HTML event can be something the browser does, or something a user does.
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>
Strings
written inside quotes.
You can use single or double quotes:
var carname = "Volvo XC60";
var carname = 'Volvo XC60';
Length
length property returns the length of a string:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Numbers
JavaScript has only one type of number. Numbers can be written with or without decimals.
var x = 3.14;
var y = 3;
Extra large or extra small numbers can be written with scientific (exponent) notation:
spaces and breaks are not important.
Properties
The name:values pairs in JavaScript objects are called properties:
We can access object properties in two ways.
objectName.propertyName
eg:- person.lastName;
objectName["propertyName"]
eg:-person["lastName"];
Methods
Objects can also have methods.
Methods are actions performed on objects.
Methods arestored in properties as function definition.
In a function definition, this refers to the "owner" of the function.
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
Accessing object methods
objectName.methodName()
name = person.fullName();
Events
An HTML event can be something the browser does, or something a user does.
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>
onchange | An HTML element has been changed |
onclick | The user clicks an HTML element |
onmouseover | The user moves the mouse over an HTML element |
onmouseout | The user moves the mouse away from an HTML element |
onkeydown | The user pushes a keyboard key |
onload | The browser has finished loading the page |
written inside quotes.
You can use single or double quotes:
var carname = "Volvo XC60";
var carname = 'Volvo XC60';
Length
length property returns the length of a string:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Numbers
JavaScript has only one type of number. Numbers can be written with or without decimals.
var x = 3.14;
var y = 3;
Extra large or extra small numbers can be written with scientific (exponent) notation:
var x = 123e5;
var y = 123e-5;
Integers are accurate up to 15 digits.
var x = 999999999999999;
If you add two numbers, the result will be a number:
var x = 10;
var y = 20;
var z = x + y;
add two strings, the result will be a string concatenation:
var x = "10";
var y = "20";
var z = x + y; // z will be 1020 (a string)
add a number and a string, the result will be a string concatenation:
var x = 10;
var y = "20";
var z = x + y; // z will be 1020 (a string)
var y = 123e-5;
Integers are accurate up to 15 digits.
var x = 999999999999999;
If you add two numbers, the result will be a number:
var x = 10;
var y = 20;
var z = x + y;
add two strings, the result will be a string concatenation:
var x = "10";
var y = "20";
var z = x + y; // z will be 1020 (a string)
add a number and a string, the result will be a string concatenation:
var x = 10;
var y = "20";
var z = x + y; // z will be 1020 (a string)
NaN
NaN is a JavaScript reserved word indicating that a number is not a legal number.
Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):
var x = 100 / "Apple"; // x will be NaN (Not a Number)
if the string contains a numeric value , the result will be a number:
var x = 100 / "Apple";
isNaN(x); // returns true because x is Not a Number
isNaN(x); // returns true because x is Not a Number
Array
An array is a special variable, which can hold more than one value at a time.
An array is a special variable, which can hold more than one value at a time.
var fruits = ["Apple", "Pineapple", "Orange"];
You access an array element by referring to the index number.
You access an array element by referring to the index number.
var fruits = ["Apple", "Pineapple", "Orange"];
document.getElementById("demo").innerHTML = fruits[0];
This statement changes the value of the first element in cars:
document.getElementById("demo").innerHTML = fruits[0];
This statement changes the value of the first element in cars:
var fruits = ["Apple", "Pineapple", "Orange"];
fruits[0] = "Grapes";
document.getElementById("demo").innerHTML = fruits[0];
Date
new Date() creates a new date object with the current date and time:
fruits[0] = "Grapes";
document.getElementById("demo").innerHTML = fruits[0];
Date
new Date() creates a new date object with the current date and time:
var d = new Date();
ISO 8601 is the international standard for the representation of dates and times.
The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:
var d = new Date("2015-03-25");
ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ):
var d = new Date("2015-03-25T12:00:00Z");
var d = new Date("2015-03-25T12:00:00-06:30");
If you have a valid date string, you can use the Date.parse() method to convert it to milliseconds.
Date.parse() returns the number of milliseconds between the date and January 1, 1970:
var msec = Date.parse("March 21, 2012");
var d = new Date(msec);
document.getElementById("demo").innerHTML = d;
var d = new Date(msec);
document.getElementById("demo").innerHTML = d;
Math
Math.round(x) returns the value of x rounded to its nearest
integer:Math.round(4.7); returns 5
Math.pow(x, y) returns the value of x to the power of y:
Math.pow(8, 2); returns 64
Math.sqrt(x) returns the square root of x:
Math.sqrt(64); returns 8
Math.abs(x) returns the absolute (positive) value of x:
Math.abs(-4.7); returns 4.7
Math.ceil(x) returns the value of x rounded up to its nearest integer:
Math.ceil(4.4); returns 5
Math.floor(x) returns the value of x rounded down to its nearest integer:
Math.floor(4.7); returns 4
Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):
Math.random(); returns a random number
Boolean
You can use the Boolean() function to find out if an expression (or a variable) is true.
(10 > 9) // also returns true.
10 > 9 // also returns true.
The Boolean value of 0 (zero) is false:
The Boolean value of -0 (minus zero) is false:
The Boolean value of "" (empty string) is false:The Boolean value of undefined is false:
The Boolean value of null is false:
The Boolean value of NaN is false:
Conditions
if statement to specify a block of JavaScript code to be executed if a condition is true.
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
else statement to specify a block of code to be executed if the condition is false.
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
greeting = "Good day";
} else {
greeting = "Good evening";
}
else if statement to specify a new condition if the first condition is false.
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Switch
The switch statement is used to perform different actions based on different conditions.
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
default keyword specifies the code to run if there is no case match:
switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
Loop
for loops through a block of code a number of times
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
text += "The number is " + i + "<br>";
}
The JavaScript for/in statement loops through the properties of an object:
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
var text = "";
var x;
for (x in person) {
text += person[x];
}
The while loop loops through a block of code as long as a specified condition is true.
while (i < 10) {
text += "The number is " + i;
i++;
}
text += "The number is " + i;
i++;
}
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
do {
text += "The number is " + i;
i++;
}
while (i < 10);
text += "The number is " + i;
i++;
}
while (i < 10);
No comments