Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
442 views

JavaScript Notes 1

Uploaded by

gourabdas2128
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
442 views

JavaScript Notes 1

Uploaded by

gourabdas2128
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

JavaScript

Writing JavaScript into HTML


<html>
<head>
<title>
Basics Java Script
</title>
<script >
var str1 = "Hello World";
console.log(str1.length);
</script>
</head>
<body>
This is Sample Page of JavaScript which just print the length of
string "Hello World"
</body>
</html>

Variables and Constants

let currentTempC = 22; // degrees Celsius


currentTempC = 22.5;

let targetTempC; // equivalent to "let targetTempC = undefined";


//You can also declare multiple variables with the same let statement:
let targetTempC, room1 = "conference_room_a", room2 = "lobby";

Constant

const ROOM_TEMP_C = 21.5, MAX_TEMP_C = 30;


Primitive Types and Objects
• Number
• String
• Boolean
• Null
• Undefined
• Symbol
The built-in object types we’ll cover are as follows:
• Array
• Date

const blue = 0x0000ff; // hexadecimal (hex ff = decimal 255)


const umask = 0o0022; // octal (octal 22 = decimal 18)
const roomTemp = 21.5; // decimal
const c = 3.0e6; // exponential (3.0 × 10^6 = 3,000,000)
const e = -1.6e-19; // exponential (-1.6 × 10^-19 =
0.00000000000000000016)
const inf = Infinity;
const ninf = -Infinity;
const nan = NaN; // "not a number"

but what if you want to use quotes in a string? To solve


this problem, there needs to be a method of escaping characters so they are not taken
as string termination. Consider the following examples (which do not require escaping):

const dialog = 'Sam looked up, and said "hello, old friend!", as
Max walked in.';
const imperative = "Don't do that!";

const dialog1 = "He looked up and said \"don't do that!\" to Max.";


const dialog2 = 'He looked up and said "don\'t do that!" to Max.';
const s = "In JavaScript, use \\ as an escape character in strings.";

null and undefined


JavaScript has two special types, null and undefined. null has only one possible
value (null), and undefined has only one possible value (undefined). Both null and
undefined represent something that doesn’t exist, and the fact that there are two separate
data types has caused no end of confusion, especially among beginners.
The general rule of thumb is that null is a data type that is available to you, the programmer,
and undefined should be reserved for JavaScript itself, to indicate that
something hasn’t been given a value yet.

Objects

const obj = {};//empty object


obj.color= 'yellow';
console.log(obj.size);//undefined
console.log(obj.color);//yellow

More examples on Object


const sam1 = {
name: 'Sam',
age: 4,
};
const sam2 = { name: 'Sam', age: 4 }; // declaration on one line
const sam3 = {
name: 'Sam',
classification: { // property values can
kingdom: 'Anamalia', // be objects themselves
phylum: 'Chordata',
class: 'Mamalia',
order: 'Carnivoria',
family: 'Felidae',
subfaimily: 'Felinae',
genus: 'Felis',
species: 'catus',
},
};

Dates

const now = new Date();


now; // example: Thu Aug 20 2015 18:31:26 GMT-0700 (Pacific
Daylight Time)
const halloweenParty = new Date(2016, 9, 31, 19, 0); // 19:00 =
7:00 pm
//Once you have a date object, you can retrieve its components:
halloweenParty.getFullYear(); // 2016
halloweenParty.getMonth(); // 9
halloweenParty.getDate(); // 31
halloweenParty.getDay(); // 1 (Mon; 0=Sun, 1=Mon,...)
halloweenParty.getHours(); // 19
halloweenParty.getMinutes(); // 0
halloweenParty.getSeconds(); // 0
halloweenParty.getMilliseconds(); // 0

Difference between let and var


https://www.programiz.com/javascript/let-vs-var

Arrays
// array literals
const arr1 = [1, 2, 3]; // array of numbers
const arr2 = ["one", 2, "three"]; // nonhomogeneous array
const arr3 = [[1, 2, 3], ["one", 2, "three"]]; // array containing
arrays
// accessing elements
arr1[0]; // 1
arr1[2]; // 3
arr3[1]; // ["one", 2, "three"]
// array length
arr1.length; // 3
// Array constructor (rarely used)
const arr5 = new Array(); // empty array
const arr6 = new Array(1, 2, 3); // [1, 2, 3]
const arr7 = new Array(2); // array of length 2 (all elements
undefined)
const arr8 = new Array("2"); // ["2"]
JavaScript in Browser

● Access the content of the page


● Modify the content of the page
● Program rules or instructions the browser can follow
● React to events triggered by the user or browser

WINDOW OBJECT
The browser represents each window or tab using a window object. The location property of
the window object will tell you the URL of the current page.
PROPERTIES
location http://www.javascriptbook.com/

DOCUMENT OBJECT
The current web page loaded into each window is modeled using a document object
PROPERTIES
URL: http://www.javascriptbook.com/
lastModified 09/04/2014 15:33:37
title: Learn JavaScript & jQuery -A book that teaches youvin a nicer way

PROPERTIES
Properties describe characteristics of the current web page (such as the title of the page).
METHODS
Methods perform tasks associated with the document currently loaded in the browser (such
as getting information from a specified element or adding new content).
EVENTS
You can respond to events, such as a user clicking or tapping on an element.
HOW A BROWSER SEES A WEB PAGE
1: RECEIVE A PAGE AS HTML CODE
2: CREATE A MODEL OF THE PAGE AND STORE IT IN MEMORY
3: USE A RENDERING ENGINE TO SHOW THE PAGE ON SCREEN

Load the script file


<script src="js/ add-content.js"></ script>

You may see JavaScript in the HTML between opening <script> and closing </script> tags
(but it is better to put scripts in their own files).
<script>document.write(' <h3>Welcome !</h3>');

getElementById

<html lang="en">

<head>
<title>getElementById example</title>
<script>
function changeColor(newColor) {
const elem = document.getElementById('para');
elem.style.color = newColor;
}
</script>
</head>

<body>
<p id="para">Some text here</p>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
</body>

</html>

Unlike some other element-lookup methods such as Document.querySelector() and


Document.querySelectorAll(), getElementById() is only available as a method of the
global document object, and not available as a method on all element objects in the
DOM. Because ID values must be unique throughout the entire document, there is no
need for "local" versions of the function.

<!DOCTYPE html>
<html lang="en-US">

<head>
<meta charset="UTF-8">
<title>Document</title>
</head>

<body>
<div id="parent-id">
<p>hello word1</p>
<p id="test1">hello word2</p>
<p>hello word3</p>
<p>hello word4</p>
</div>
<script>
const parentDOM = document.getElementById("parent-id");
const test1 = parentDOM.getElementById("test1");
// throw error
// Uncaught TypeError: parentDOM.getElementById is not a function
console.log(parentDOM);
console.log(test1);

</script>
</body>

</html>

functions

anonymous function : Anonymous Function is a function that does not have any name
associated with it. Normally we use the function keyword before the function name to
define a function in JavaScript, however, in anonymous functions in JavaScript, we use
only the function keyword without the function name.

const myFunction = function () {


statements
}

Example 1
<script>
var greet = function () {
console.log("Welcome to GeeksforGeeks!");
};

greet();
</script>

Example 2
<script>
var greet = function (platform) {
console.log("Welcome to ", platform);
};
greet("GeeksforGeeks!");
</script>

Example 3
In this example, we pass an anonymous function as a callback function to the
setTimeout() method. This executes this anonymous function 2000ms later.

<script>
setTimeout(function () {
console.log("Welcome to GeeksforGeeks!");
}, 2000);
</script>

var hotel = {
name: 'Quay',
rooms : 40,
booked: 25,
checkAvailability: function() {
return this.rooms - this.booked;
}
};

Object with Function

var hotel = {
name: 'Quay',
rooms: 40,
booked: 25,
checkAvailability: function () {
return this.rooms - this.booked;
}
};
console.log(hotel.checkAvailability());
Output : 15
Built-in Objects

You might also like