Tot Webdev - Javascript
Tot Webdev - Javascript
Source: https://www.w3schools.com
Introduction
JavaScript Can Change HTML Content
The example below "finds" an HTML element (with id="demo"), and changes the element content
(innerHTML) to "Hello JavaScript":
JS Can Change HTML Attribute
In this example JavaScript changes the value of the src (source) attribute of an <img> tag:
JS Can Change HTML Style (CSS)
Changing the style of an HTML element, is a variant of changing an HTML attribute:
JS Can Hide HTML Element
Hiding HTML elements can be done by changing the display style:
JS Can Show HTML Element
Showing hidden HTML elements can also be done by changing the display style:
JS Output
The id attribute defines the HTML element. The innerHTML property defines the HTML content:
Using document.write()
For testing purposes, it is convenient to use document.write():
Using window.alert()
You can use an alert box to display data:
Using window.alert()
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
JS Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
JS Semicolons;
Semicolons separate JavaScript statements.
JavaScript ignores multiple spaces. You can add white space to your script to
make it more readable.
let x = y + z;
JS Line Length and Line Breaks
For best readability, programmers often like to avoid code lines longer than 80 characters.
If a JavaScript statement does not fit on one line, the best place to break it is after an
operator:
JS CodeBlocks
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
One place you will find statements grouped together in blocks, is in JavaScript functions:
JS Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.
The two most important syntax rules for fixed values are:
Underscore:
JavaScript programmers tend to use camel case that starts with a lowercase letter:
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
The var keyword is used in all JavaScript code from 1995 to 2015.
If you want your code to run in older browsers, you must use var.
JS Identifiers
All JavaScript variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter.
• Names can also begin with $ and _ (but we will not use it in this tutorial).
• Names are case sensitive (y and Y are different variables).
• Reserved words (like JavaScript keywords) cannot be used as names.
JS Dollar Sign $
Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an
In the JavaScript library jQuery, for instance, the main function $ is used to select HTML elements. In
Cannot be Redeclared
Example
{
let x = 2;
}
// x can NOT be used here
Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.
Example
{
var x = 2;
}
// x CAN be used here
Redeclaring Variables
Redeclaring a variable using the var keyword can impose problems.
Redeclaring a variable inside a block will also redeclare the variable outside the
block:
Example
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
Redeclaring a variable using the let keyword can solve this problem.
Redeclaring a variable inside a block will not redeclare the variable outside the block:
Example
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Browser Support
The let keyword is not fully supported in Internet Explorer 11 or earlier.
The following table defines the first browser versions with full support for the let keyword:
Redeclaring
Redeclaring a JavaScript variable with var is allowed anywhere in a program:
var x = 2;
// Now x is 2
var x = 3;
// Now x is 3
Variables defined with var are hoisted to the top and can be initialized at any time.
let x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it
produce a result?
JavaScript will treat the example above as:
JavaScript evaluates expressions from left to right. Different sequences can produce
different results:
JS Types is Dynamic
JavaScript has dynamic types. This means that the same variable can be used to hold different
data types:
JS String
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Extra large or extra small numbers can be written with scientific (exponential) notation:
JS Booleans
Booleans can only have two values: true or false.
The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.
Typeof Operator
You can use the JavaScript typeof operator to find the type of a JavaScript variable.
The typeof operator returns the type of a variable or an expression:
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is
also undefined.
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is
also undefined.
A car has properties like weight and color, and methods like start and stop:
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different
times.
JS Objects
You have already learned that JavaScript variables are containers for data values.
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
The values are written as name:value pairs (name and value separated by a colon).
Object Definition
You define (and create) a JavaScript object with an object literal:
Spaces and line breaks are not important. An object definition can span multiple lines:
Object Properties
The name:values pairs in JavaScript objects are called properties:
Spaces and line breaks are not important. An object definition can span multiple lines:
Access Object Properties
You can access object properties in two ways:
objectName.propertyName
objectName["propertyName"]
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
firstName John
lastName Doe
age 50
eyeColor blue
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something" invokes (calls)
the function :
If the function was invoked from a statement, JavaScript will "return" to execute the code
after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
Example
Calculate the product of two numbers, and return the result:
let 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
}
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce
different results.
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
The ( ) Operator Invokes the Function
Using the example above, toCelsius refers to the function object, and toCelsius() refers to
the function result.
Accessing a function without () will return the function object instead of the function result.
Function used as Variables
Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations.
Example
Instead of using a variable to store the return value of a function:
let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";
Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations.
Example
Instead of using a variable to store the return value of a function:
let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";
HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to
HTML elements.
JS EVENTS
With single quotes:
In the following example, an onclick attribute (with code), is added to a <button> element:
Common HTML Events
Event Description
Many different methods can be used to let JavaScript work with events:
You can use quotes inside a string, as long as they don't match the quotes surrounding
the string:
let text = "We are the so-called "Vikings" from the north.";
\\ \ Backslash
Escape Character
let text = "We are the so-called \"Vikings\" from the north.";
Code Result
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator
Breaking Long Code Lines
For best readability, programmers often like to avoid code lines longer than 80 characters.
If a JavaScript statement does not fit on one line, the best place to break it is after an
operator:
You can also break up a code line within a text string with a single backslash:
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
JS String as Object
Normally, JavaScript strings are primitive values, created from literals:
let x = "John";
But strings can also be defined as objects with the keyword new:
Primitive values, like "John Doe", cannot have properties or methods (because they are not
objects).
But with JavaScript, methods and properties are also available to primitive values, because
JavaScript treats primitive values as objects when executing methods and properties.
JS String Length
• slice(start, end)
• substring(start, end)
• substr(start, length)
JS String slice()
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
JS String slice()
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
JS String slice()
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
Example
let str = "Apple, Banana, Kiwi";
let part = str.slice(-12, -6);
JS String substring()
Example
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
If you omit the second parameter, substring() will slice out the rest of the string.
JS String substr()
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
If you omit the second parameter, substr() will slice out the rest of the string.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7);
Replacing String Content
The replace() method replaces a specified value with another value in a string:
Example
let text = "Please visit Microsoft!";
let newText =
text.replace("Microsoft", "W3Schools");
Note
• The replace() method does not change the string it is called on.
• The replace() method returns a new string.
• The replace() method replaces only the first match
• If you want to replace all matches, use a regular expression with the /g flag set. See
examples below.
By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case) will not work:
Replacing String Content
Example
let text = "Please visit Microsoft!";
let newText =
text.replace(/MICROSOFT/i, "W3Schools");
To replace all matches, use a regular expression with a /g flag (global match):
Example
let text = "Please visit Microsoft and
Microsoft!";
let newText =
text.replace(/Microsoft/g, "W3Schools");
JS String toUpperCase()
JS String toLowerCase()
JS String trim()
• charAt(position)
• charCodeAt(position)
• Property access [ ]
JS String charArt()
The charAt() method returns the character at a specified index (position) in a string:
JS String charCodeAt()
The charCodeAt() method returns the unicode of the character at a specified index in
a string:
The method returns a UTF-16 code (an integer between 0 and 65535).
Property Access
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values
by referring to an index number.
Creating an Array
Syntax:
const array_name = [item1, item2, ...];
Spaces and line breaks are not important. A declaration can span multiple lines:
Using the JS keyword new
The following example also creates an Array, and assigns values to it:
cars[0] = "Opel";
Access the Full Array
With JavaScript, the full array can be accessed by referring to the array name:
Arrays use numbers to access its "elements". In this example, person[0] returns John
Array Elements can Be Objects
JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can
have arrays in an Array
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and
methods:
The length property of an array returns the length of an array (the number of array elements).
Accessing the First Array
Accessing the Last Array
Looping Array Elements
The easiest way to add a new element to an array is using the push() method:
Adding Array Elements
The easiest way to add a new element to an array is using the push() method:
Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
The Difference Between Arrays and Objects
These two different statements both create a new array containing 6 numbers:
Solution 1:
To solve this problem ECMAScript 5 (JavaScript 2009) defined a new
method Array.isArray():
How To Recognize an Array
Solution 2:
The instanceof operator returns true if an object is created by a given
constructor:
JS Array Method
Converting Arrays to Strings
Result:
Banana,Orange,Apple,Mango
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:
Result:
Banana,Orange,Apple,Mango
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:
The shift() method removes the first array element and "shifts" all
other elements to a lower index.
JS Array unshift()
The unshift() method adds a new element to an array (at the beginning), and
"unshifts" older elements:
JS Array length
The length property provides an easy way to append a new element to an array:
JS Array delete()
JS Array delete()
Merging ( Concatenating ) Arrays
The concat() method creates a new array by merging (concatenating) existing arrays:
The first parameter (2) defines the position where new elements should
be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
The splice() method returns an array with the deleted items:
Using splice() to Remove Elements
With clever parameter setting, you can use splice() to remove elements without leaving
"holes" in the array:
The first parameter (0) defines the position where new elements should be added (spliced in).
The second parameter (1) defines how many elements should be . removed.
The rest of the parameters are omitted. No new elements will be added
JS Array slice()
The slice() method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1 ("Orange"):
Automatic to String()
JavaScript automatically converts an array to a comma separated string when a primitive
value is expected.
This is always the case when you try to output an array.
These two examples will produce the same result:
Source:
https://www.w3schools.com/css/default.asp
Thank you!